mirror of
https://github.com/praktimarc/kst4contest.git
synced 2026-09-11 19:55:40 +02:00
Compare commits
23
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
548f95c9bb
|
||
|
|
1204acaa82
|
||
|
|
174c77a037
|
||
|
|
e5e6036188
|
||
|
|
3b631e25f6
|
||
|
|
e435368840
|
||
|
|
c579105bcb
|
||
|
|
74ac1139ad
|
||
|
|
63a4bae858
|
||
|
|
5086eae816
|
||
|
|
2023b2cb28
|
||
|
|
681419f169
|
||
|
|
4ad1cf71dd
|
||
|
|
ad212e3e71 | ||
|
|
08d65a0e23 | ||
|
|
edf71b4105
|
||
|
|
885bf83c2f
|
||
|
|
634b88238d
|
||
|
|
830e4020a2 | ||
|
|
7ee50267ec | ||
|
|
113e843111 | ||
|
|
79161d2afa | ||
|
|
3ed1cad5ab |
@@ -551,6 +551,9 @@ jobs:
|
||||
name: Publish Flatpak OSTree Repo (nightly)
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-flatpak
|
||||
concurrency:
|
||||
group: flatpak-repo-publish
|
||||
cancel-in-progress: false
|
||||
|
||||
steps:
|
||||
- name: Install Flatpak tooling
|
||||
|
||||
@@ -646,6 +646,9 @@ jobs:
|
||||
name: Publish Flatpak OSTree Repo (${{ github.ref_name }})
|
||||
runs-on: ubuntu-latest
|
||||
needs: build-flatpak
|
||||
concurrency:
|
||||
group: flatpak-repo-publish
|
||||
cancel-in-progress: false
|
||||
|
||||
steps:
|
||||
- name: Install Flatpak tooling
|
||||
@@ -786,45 +789,45 @@ jobs:
|
||||
release-assets/macos/KST4Contest-${{ github.ref_name }}-macos-*.dmg,
|
||||
release-assets/docs/KST4Contest-${{ github.ref_name }}-manual-en.pdf,
|
||||
release-assets/docs/KST4Contest-${{ github.ref_name }}-manual-de.pdf
|
||||
|
||||
# The update feed is generated only after GitHub has published the
|
||||
# release. Otherwise the Releases API cannot return the release notes
|
||||
# belonging to the tag which triggered this workflow.
|
||||
- name: Set up Node.js for website build
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
cache: npm
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Build and validate website after release publication
|
||||
working-directory: website
|
||||
run: |
|
||||
npm ci
|
||||
npm test
|
||||
npm run build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
# The update feed is generated only after GitHub has published the
|
||||
# release. Otherwise the Releases API cannot return the release notes
|
||||
# belonging to the tag which triggered this workflow.
|
||||
- name: Set up Node.js for website build
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "24"
|
||||
cache: npm
|
||||
cache-dependency-path: website/package-lock.json
|
||||
|
||||
- name: Verify Stable release in update feed
|
||||
if: ${{ !startsWith(github.ref_name, 'beta-') }}
|
||||
working-directory: website
|
||||
run: npm run validate:version-info
|
||||
env:
|
||||
EXPECTED_STABLE_VERSION: ${{ github.ref_name }}
|
||||
- name: Build and validate website after release publication
|
||||
working-directory: website
|
||||
run: |
|
||||
npm ci
|
||||
npm test
|
||||
npm run build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Attach verified version info to tagged release
|
||||
run: >-
|
||||
gh release upload "${GITHUB_REF_NAME}"
|
||||
website/_site/kst4ContestVersionInfo.xml
|
||||
--clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Verify Stable release in update feed
|
||||
if: ${{ !startsWith(github.ref_name, 'beta-') }}
|
||||
working-directory: website
|
||||
run: npm run validate:version-info
|
||||
env:
|
||||
EXPECTED_STABLE_VERSION: ${{ github.ref_name }}
|
||||
|
||||
- name: Upload verified website artifact
|
||||
uses: actions/upload-artifact@v4.3.4
|
||||
with:
|
||||
name: kst4contest-website-${{ github.ref_name }}
|
||||
path: website/_site/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
- name: Attach verified version info to tagged release
|
||||
run: >-
|
||||
gh release upload "${GITHUB_REF_NAME}"
|
||||
website/_site/kst4ContestVersionInfo.xml
|
||||
--clobber
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Upload verified website artifact
|
||||
uses: actions/upload-artifact@v4.3.4
|
||||
with:
|
||||
name: kst4contest-website-${{ github.ref_name }}
|
||||
path: website/_site/
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
# Konzept: In-App-Update für KST4Contest
|
||||
|
||||
> Status: Konzept, noch nicht umgesetzt. Zielrelease **1.50**. Alle Zeilenanker beziehen sich auf `nextMajorRelease/version1_50` (Version 1.50.0) und wurden gegen den Branch verifiziert.
|
||||
|
||||
## Ziel
|
||||
|
||||
Stable-Updates werden nach Zustimmung des Nutzers heruntergeladen. KST4Contest beendet sich danach kontrolliert und startet den plattformspezifischen Aktualisierungsvorgang. Updates dürfen den Programmstart nicht blockieren und während eines Contests nicht erzwungen werden.
|
||||
|
||||
## Ausgangslage
|
||||
|
||||
Der vorhandene Mechanismus erfüllt das nicht:
|
||||
|
||||
- `UpdateChecker.downloadLatestVersionInfoXML()` (`src/main/java/kst4contest/controller/UpdateChecker.java:54-71`) benutzt `new URL(...).openStream()` + `Files.copy(..., REPLACE_EXISTING)` **direkt auf die Zieldatei** — ohne Timeouts, ohne HTTP-Statusprüfung, ohne temporäre Datei. Ein Fehlschlag beschädigt zusätzlich die lokale Feed-Kopie.
|
||||
- Der Aufruf steht **synchron im Konstruktor** von `ChatController` (`ChatController.java:2937-2941`); `ChatController` wird in `Kst4ContestApplication.start(Stage)` erzeugt (`Kst4ContestApplication.java:6971`, `start` ab `:6914`). Der Netzwerkaufruf läuft damit unbegrenzt **auf dem JavaFX-Application-Thread während des Starts** — genau der Punkt „darf den Programmstart nicht blockieren".
|
||||
- `parseUpdateXMLFile()` (`UpdateChecker.java:73-236`) liest Kindelemente **positionsabhängig** über einen Zähler in `String[7]` bzw. `String[3]` (`:144-145`, `:182-183`). Ein achtes Kindelement in `<changeLog>` erzeugt eine `ArrayIndexOutOfBoundsException` und killt den gesamten Check.
|
||||
- Die Anzeige ist ein eigenes `Stage` mit `setAlwaysOnTop(true)` (`Kst4ContestApplication.java:9162`), inline in `start()` aufgebaut (`:9152-9294`) und beim Start automatisch geöffnet (`:9280`). Es gibt **keinen Menüpunkt** zum erneuten Prüfen. Ein Catch-All bei `:9289-9292` schaltet die Funktion stillschweigend ab, sobald der Feed fehlt oder nicht passt.
|
||||
- Toter Code: `main()` (`:27-34`) und ein Testdatenblock (`:208-234`).
|
||||
|
||||
## Bestätigte Festlegungen
|
||||
|
||||
| Punkt | Entscheidung |
|
||||
|---|---|
|
||||
| Contest-Schutz | Hinweis wird unterdrückt, solange eine ON4KST-Verbindung besteht |
|
||||
| Update-Starter | Kein eigenes Starter-Programm; Installer/Paketverwaltung wird direkt gestartet, danach beendet sich KST4Contest |
|
||||
| Flatpak | Nur Hinweis mit Update-Befehl, kein Download, kein Artefakt |
|
||||
| AppImage | Kontrollierter Dateiaustausch, kein `AppImageUpdate` |
|
||||
| Kanal | Ausschließlich Stable |
|
||||
| Feed-Auslieferung | Bleibt wie bisher: der Webserver zieht das Repo alle 5 Minuten per Git und baut die Website selbst |
|
||||
| Zuschnitt | Drei Stufen |
|
||||
| Signatur | SignPath Foundation, als **optionaler additiver** CI-Schritt; unsigniert bleibt lauffähig |
|
||||
| Windows-ZIP | Bleibt als portable Alternative |
|
||||
|
||||
## Was unverändert bleibt
|
||||
|
||||
1. **Alte Clients (≤ 1.44) am erweiterten Feed.** `UpdateChecker` sucht per `getElementsByTagName` nach `latestVersion`, `versionNumber`, `semanticVersion`, `adminMessage`, `majorChanges`, `latestVersionPathOnWebserver`, `changeLog`, `bug`. Das ist eine **Descendant-Suche** — deshalb kommt der neue Block als *Geschwister* neben `<latestVersion>` und benutzt ausschließlich neue Elementnamen.
|
||||
2. **`<changeLog>` behält exakt seine 7 Kinder** (`changedVersionNumber, date, description, added, changed, fixed, removed`) in unveränderter Reihenfolge, `<bug>` seine Struktur. `<needUpdateSinceLastVersion>`, `<roadmap>`, `<bugsReported>` bleiben unangetastet.
|
||||
3. **`~/.praktiKST/`** — nur ein neues Unterverzeichnis `updates/`. `kst4ContestVersionInfo.xml` behält Name und Ort, damit ein Downgrade auf 1.44 funktioniert.
|
||||
4. **Windows-ZIP als Portable** — die App verändert ihr eigenes Verzeichnis nie und führt für diesen Typ keinen Installer aus.
|
||||
5. **Kein Eingriff** in Flatpak-, AUR-, DEB-, RPM- oder Arch-Installationen; **kein `sudo`/`pkexec`** aus der Anwendung heraus.
|
||||
6. **Offlinebetrieb** — ein fehlgeschlagener Check ist stumm (nur `java.util.logging`), der Programmstart ist davon vollständig entkoppelt.
|
||||
7. **Legacy-Vergleich** — `APPLICATION_CURRENTVERSIONNUMBER` und `<versionNumber>` bleiben als Fallback; `VersionUtils.compareStableVersions` wird wiederverwendet und nicht verändert.
|
||||
8. **Bei unbekannter Installationsart** wird ausschließlich die Downloadseite geöffnet.
|
||||
|
||||
---
|
||||
|
||||
## Stufe 1 — Feed, Paketkennzeichnung, Prüfdienst, Hinweis-UI
|
||||
|
||||
Kein Download, kein Installationsstart.
|
||||
|
||||
### 1a. Installationsart zur Buildzeit kennzeichnen
|
||||
|
||||
Es existiert heute **keinerlei** Build-Metadatum: kein `--java-options`, keine `.properties` unter `src`, kein Resource-Filtering in `pom.xml`, keine Manifest-Einträge.
|
||||
|
||||
**Gewählter Mechanismus:** jpackage-Flag `--java-options -Dkst4contest.packageType=<typ>`.
|
||||
|
||||
| Alternative | Warum nicht |
|
||||
|---|---|
|
||||
| Gefilterte `.properties`-Resource | **Alle Pakettypen entstehen aus demselben Maven-Artefakt**; die Unterscheidung fällt erst im jpackage-Aufruf. Lokale Builds und Tests bekämen einen falschen Marker. |
|
||||
| Manifest-Eintrag | Gleiches JAR-Problem, mehr Bewegungsteile. |
|
||||
| Verzeichnis-/Prozessheuristik | Laut Zielbild ausdrücklich ausgeschlossen; bei ZIP-Portable ohnehin frei verschiebbar. |
|
||||
| Reines Env-Sniffing | Erkennt Flatpak und AppImage, aber nicht deb/rpm/arch/zip/msi. |
|
||||
|
||||
Vorteile: keine Auswirkung auf `mvn`/Tests/lokale Entwicklung (Property fehlt → `UNKNOWN` → sicherer Fallback); der Wert landet in `lib/app/<Name>.cfg` des app-image und wird dadurch vom AUR-`-bin`-Repack (`packaging/aur/kst4contest-bin/PKGBUILD` macht nur `cp -a usr`) und vom Flatpak-Build (bindet das app-image als `type: dir`-Source ein) **automatisch mitkopiert**.
|
||||
|
||||
Werte: `windows-zip`, `windows-msi`, `macos-dmg`, `linux-appimage`, `flatpak`, `linux-deb`, `linux-rpm`, `linux-arch`.
|
||||
|
||||
**15 Aufrufstellen:**
|
||||
|
||||
| Datei | Zeilen | Wert |
|
||||
|---|---|---|
|
||||
| `.github/workflows/tagged-release.yml` | 53 / 104 / 184 / 238 / 292 / 403 | `windows-zip` / `linux-appimage` / `linux-deb` / `linux-rpm` / `linux-arch` / `flatpak` |
|
||||
| `.github/workflows/nightly-artifacts.yml` | 69 / 127 / 214 / 275 / 338 / 458 | dieselbe Reihenfolge |
|
||||
| `packaging/macos/build-signed-dmg.sh` | 72 | `macos-dmg` |
|
||||
| `packaging/aur/kst4contest/PKGBUILD` | 44 | `linux-arch` |
|
||||
| `packaging/aur/kst4contest-git/PKGBUILD` | 37 | `linux-arch` |
|
||||
|
||||
`packaging/aur/kst4contest-bin/PKGBUILD` erbt korrekt — **keine Änderung**.
|
||||
|
||||
PowerShell-Syntax (tagged-release:53, nightly:69) braucht einfache Anführungszeichen, sonst frisst PowerShell das `-D`:
|
||||
`--java-options '-Dkst4contest.packageType=windows-zip'`
|
||||
|
||||
**Auflösung zur Laufzeit** (`RuntimePackageTypeResolver`), bewusst konservativ:
|
||||
|
||||
1. `System.getProperty("kst4contest.packageType")`; unbekannter Wert → weiter.
|
||||
2. `/.flatpak-info` vorhanden **oder** `FLATPAK_ID` gesetzt → `FLATPAK`. Diese Prüfung **überschreibt** die Property — eine Fehlklassifikation richtet ausgerechnet im Flatpak den größten Schaden an (Download in eine Sandbox, die den Host nie aktualisieren kann).
|
||||
3. `APPIMAGE` gesetzt → `LINUX_APPIMAGE`.
|
||||
4. sonst `UNKNOWN`.
|
||||
|
||||
### 1b. Feed erweitern
|
||||
|
||||
Der Feed wird **von der Website** erzeugt (`website/src/_data/versionInfo.js`, ausgeliefert über `website/src/version-info.njk`), gespeist aus der GitHub-Releases-API — nicht aus den Build-Jobs. Der Webserver zieht das Repository alle 5 Minuten per Git und baut selbst; eine geänderte `versionInfo.js` wird dadurch automatisch wirksam, **ohne** Upload-Schritt in den Workflows.
|
||||
|
||||
**Platzierung: neues Top-Level-Element als Geschwister von `<latestVersion>`.** Ein Kindelement *innerhalb* `<latestVersion>` wäre riskant, weil der alte Parser dort per Descendant-Suche liest; als Geschwister ist jede Kollision strukturell ausgeschlossen.
|
||||
|
||||
```xml
|
||||
<updatePackages formatVersion="1" semanticVersion="1.45.0">
|
||||
<updatePackage>
|
||||
<packageType>linux-deb</packageType>
|
||||
<operatingSystem>linux</operatingSystem>
|
||||
<architecture>x86_64</architecture>
|
||||
<fileName>KST4Contest-v1.45.0-debian-amd64.deb</fileName>
|
||||
<downloadUrl>https://github.com/praktimarc/kst4contest/releases/download/v1.45.0/…</downloadUrl>
|
||||
<fileSizeBytes>142335488</fileSizeBytes>
|
||||
<sha256>9f2c…</sha256> <!-- 64 hex, klein -->
|
||||
<signatureState>unsigned</signatureState> <!-- unsigned | authenticode | apple-notarized | gpg-repo -->
|
||||
<releaseNotesUrl>…/releases/tag/v1.45.0</releaseNotesUrl>
|
||||
<installHint>package-manager</installHint> <!-- run | package-manager | portable | hint-only -->
|
||||
</updatePackage>
|
||||
<updatePackage>
|
||||
<packageType>flatpak</packageType>
|
||||
<operatingSystem>linux</operatingSystem>
|
||||
<architecture>x86_64</architecture>
|
||||
<signatureState>gpg-repo</signatureState>
|
||||
<releaseNotesUrl>…/releases/tag/v1.45.0</releaseNotesUrl>
|
||||
<installHint>hint-only</installHint>
|
||||
<hintCommand>flatpak update de.x08.KST4Contest</hintCommand>
|
||||
<!-- bewusst ohne downloadUrl/sha256 -->
|
||||
</updatePackage>
|
||||
</updatePackages>
|
||||
```
|
||||
|
||||
**Datenherkunft in `versionInfo.js`:**
|
||||
|
||||
- `fileName`, `downloadUrl`, `fileSizeBytes` stehen **bereits in der vorhandenen `/releases`-Antwort** (`release.assets[]` mit `name`, `browser_download_url`, `size`) — kein zusätzlicher API-Aufruf. Aktuell werden die Assets weggeworfen.
|
||||
- `packageType`/`operatingSystem`/`architecture` über einen deterministischen Klassifikator auf die Assetnamen, die die Workflows fest vergeben (`tagged-release.yml:783-791`): `-windows-x64.zip`, `-linux-x86_64.AppImage`, `-debian-amd64.deb`, `-fedora-x86_64.rpm`, `-archlinux-*.pkg.tar.zst`, `-macos-*.dmg`. `.flatpakref` erzeugt keinen Download, sondern den synthetischen Hint-Eintrag. Manuals und der Feed selbst werden übersprungen.
|
||||
- **`sha256` muss der Release-Workflow erzeugen.** Im Job `release-tag` liegen alle Artefakte bereits unter `release-assets/*`, bevor `ncipollo/release-action` läuft. Dort nach den `download-artifact`-Schritten und **vor** „Create tagged release":
|
||||
```yaml
|
||||
- name: Compute release asset checksums
|
||||
run: |
|
||||
cd release-assets
|
||||
find . -type f ! -name SHA256SUMS.txt -print0 \
|
||||
| xargs -0 sha256sum | sed 's#\./##' > SHA256SUMS.txt
|
||||
```
|
||||
und `release-assets/SHA256SUMS.txt` in die `artifacts:`-Liste (`:783-791`) aufnehmen. Die bestehende Reihenfolge (Release zuerst, dann Website-Build, `:771-825`) bleibt korrekt — die Summen liegen zum Zeitpunkt des Website-Builds bereits am Release. `versionInfo.js` lädt die Datei **nur für das neueste Stable-Release** und baut daraus eine `filename → sha256`-Map; das ist ein Download-URL-Abruf und belastet das API-Ratelimit nicht.
|
||||
- `signatureState` aus einer statischen Tabelle je packageType (`macos-dmg → apple-notarized`, `flatpak → gpg-repo`, Rest `unsigned`). In Stufe 3 wird `windows-msi` nur dann auf `authenticode` gesetzt, wenn ein signiertes Asset tatsächlich existiert — der Feed darf nicht lügen, wenn der SignPath-Schritt übersprungen wurde.
|
||||
|
||||
**Robustheit:** Weil der Server unabhängig vom Release-Workflow baut, kann er einen Feed erzeugen, bevor `SHA256SUMS.txt` am Release hängt. Fehlt `<sha256>`, gilt das Artefakt als **nicht automatisch ladbar** — der Client öffnet nur die Downloadseite. Ein Artefakt ohne Prüfsumme wird nie geladen und nie gestartet. Die bestehende `try/catch`-Klammer in `versionInfo.js` bricht den Website-Build bei einem unvollständigen Feed ab; die neue Sektion darf **nicht** so scharf sein — bei Problemen wird `<updatePackages>` weggelassen, der Rest des Feeds bleibt gültig.
|
||||
|
||||
**Mitzuziehen:**
|
||||
- `website/scripts/validate-version-info.js` — bekannter `packageType`; `sha256` matcht `^[0-9a-f]{64}$`; `downloadUrl` beginnt mit `https://github.com/praktimarc/kst4contest/releases/download/`; `fileSizeBytes` numerisch > 0. **Zusätzlich neu und wichtig:** `<changeLog>` muss weiterhin exakt die 7 Kinder in der Altreihenfolge haben — das nagelt die Alt-Client-Kompatibilität fest.
|
||||
- `website/test/version-info.test.js` — Klassifikator, SHA256SUMS-Parsing, „Release ohne Assets".
|
||||
|
||||
**Warnung, nicht Teil dieser Umsetzung:** `.github/workflows/test-publish-version-xml.yml` (ungetrackt, nur `workflow_dispatch`) erzeugt mit einem eigenen Python-Generator einen konkurrierenden Feed **ohne** `<semanticVersion>` und lädt ihn per WebDAV hoch. Würde er ausgelöst, fielen alle Clients auf den kaputten Double-Vergleich (`1.41.1` → `1.411`) zurück.
|
||||
|
||||
### 1c. Prüfdienst neu bauen
|
||||
|
||||
Neues Package `kst4contest.service.update` (konsistent zum vorhandenen `kst4contest/service/path/`).
|
||||
|
||||
| Datei | Verantwortung |
|
||||
|---|---|
|
||||
| `model/PackageType.java` | Enum + `feedId()`, `fromFeedId()` (null/unbekannt → `UNKNOWN`, wirft nie), `updateStrategy()` |
|
||||
| `model/UpdatePackageInfo.java` | Transport-DTO, **explizite Klasse, kein Record** (AGENTS.md) |
|
||||
| `model/UpdateCheckResult.java` | Ergebnis-DTO inkl. `resultSource` (`NETWORK`/`CACHE`/`NONE`) |
|
||||
| `service/update/UpdateFeedParser.java` | **Reiner Parser**, kein IO, kein Netz |
|
||||
| `service/update/UpdateFeedClient.java` | **Nur HTTP**, injizierbarer `HttpClient` + Timeouts |
|
||||
| `service/update/UpdateCheckService.java` | Orchestrierung, injizierbare Abhängigkeiten + `Clock` |
|
||||
| `service/update/RuntimePackageTypeResolver.java` | Installationsart, Test-Konstruktor für Property/Env/Pfad |
|
||||
|
||||
Muster: `OpenMeteoTerrainProfileProvider.java:76-88` (injizierbarer Client, konfigurierbare Timeouts), `TerrainPackageDownloader.java:107-145` (Temp-Datei → Statusprüfung → `Files.move`).
|
||||
|
||||
Verhalten:
|
||||
|
||||
- Aufruf **asynchron im Daemon-Thread, erst nach `primaryStage.show()`** — nie vorher. `ChatController.java:2937-2941` entfällt.
|
||||
- Ergebnis über eine `ObjectProperty<UpdateCheckResult>` im `ChatController`, gesetzt via `Platform.runLater`. Muster: `lastUiReminderEvent` (`ChatController.java:4236-4243`). Der Worker fasst **keine** `ObservableList` an.
|
||||
- Versionsvergleich über `VersionUtils.compareStableVersions`. **Achtung:** `parseVersion` wirft bei leerem oder nicht-numerischem Input (`IllegalArgumentException`/`NumberFormatException`) — der Dienst muss das fangen und auf den Double-Pfad zurückfallen. Heute ist das in der View (`:9266-9278`) nicht abgesichert.
|
||||
- Ausschließlich Stable. Fehlende Verbindung erzeugt **keine** Meldung, nur einen Logeintrag über `java.util.logging` statt `System.out`. Höchstens eine Meldung je Sitzung. Bei Netzfehler Rückfall auf die zuvor gecachte Datei.
|
||||
|
||||
**Positionales Parsing entschärfen:** Primärpfad namensbasiert (`readChildText(element, "changedVersionNumber")` …), Ergebnis weiterhin als `String[7]` in derselben Reihenfolge, damit der TreeView-Aufbau im Update-Fenster unverändert bleibt. Kompatibilitätspfad für uralte Feeds behält den positionalen Walk, aber mit `if (counter >= entry.length) break;`. Präfixe (`"Date: "`, `"Desc: "`) exakt erhalten. Bei `<bug>` ist `aChangeLogEntry[2]` heute uninitialisiert → explizit `""`.
|
||||
|
||||
`UpdateChecker.java` wird durch den Dienst ersetzt.
|
||||
|
||||
### 1d. Hinweis-UI
|
||||
|
||||
Wiederverwendet wird das etablierte Muster `initSkedWarnIndicatorButton()` (`Kst4ContestApplication.java:5790-5807`) und `initBandUpgradeIndicatorButton()` (`:5965`): versteckt per Default, `managedProperty().bind(visibleProperty())`, eingehängt in `flwpne_StatusBar` (Aufbau `:7158`, `setTop` `:7161`, Indicator-Buttons `:7163`, `:7166`, `:7189`).
|
||||
|
||||
Abweichung: **nicht** `setMouseTransparent(true)` — der Button ist klickbar und öffnet ein `ContextMenu`.
|
||||
|
||||
- Text: `KST4Contest 1.x.y is available`
|
||||
- Aktionen: Änderungen anzeigen · Update herunterladen (Stufe 1: deaktiviert bzw. „Release-Seite öffnen") · für diese Sitzung schließen
|
||||
- **Contest-Regel:** `visible = updateAvailable && !dismissedForSession && Verbindungszustand != ONLINE`. `onConnectionStateChanged(...)` (`:12566`) ruft zusätzlich `refreshUpdateHintVisibility()` im vorhandenen `Platform.runLater`-Block — der Hinweis verschwindet beim Login in den Chat und kommt beim Trennen zurück.
|
||||
- FX-Thread-Guard-Idiom aus `:5833` übernehmen.
|
||||
- **Neuer Menüpunkt** im Info-Menü (Info-Menü, `helpMenu.getItems().addAll(...)` `:5774`): „Check for updates…" und „Show update details…". Damit existiert erstmals ein manueller Re-Check.
|
||||
- Das bestehende `stage_updateStage` wird aus `start()` in eine eigene, **lazy** aufgerufene Methode herausgezogen; gespeicherte Fenstergröße (`getGUIstage_updateStage_SceneSizeHW`, `:9253-9260`) bleibt. Das Auto-`show()` (`:9280`) entfällt, `setAlwaysOnTop(true)` (`:9162`) wird entfernt — ein Always-on-Top-Fenster über einem laufenden Contest ist genau das, was das Ziel verbietet.
|
||||
|
||||
### 1e. Versionsdrift absichern
|
||||
|
||||
`pom.xml:9` und `ApplicationConstants.APPLICATION_CURRENT_VERSION` werden **von Hand gepflegt, ohne jede Prüfung**. Für einen Mechanismus, der genau diese Zeichenkette vergleicht, ist das die riskanteste Stelle. Analog zu `packaging/AddModules.java --verify-pom` (an `validate` gebunden, `pom.xml:219-240`) einen `--verify-version`-Wächter ergänzen. Kein Auto-Bump.
|
||||
|
||||
`docs/PROJECT_CONTEXT.md:198` beschreibt zusätzlich die Kodierung von `APPLICATION_CURRENTVERSIONNUMBER` (`1.43.1` → `1.431`) — beim Bump mitführen, solange das Legacy-Feld existiert. Auf 1.50 stehen die Werte in `ApplicationConstants.java:23` und `:30`.
|
||||
|
||||
### 1f. `--app-version` nachziehen
|
||||
|
||||
Außer im macOS-Skript (`build-signed-dmg.sh:75`) setzt **kein** jpackage-Aufruf `--app-version`. DEB und RPM tragen dadurch intern die Vorgabeversion `1.0`; ein `apt install ./KST4Contest-v1.45.0.deb` wäre für dpkg **kein Upgrade**. Vor Stufe 3 zwingend, sinnvollerweise überall — dieselbe `sed`-Ableitung wie `build-signed-dmg.sh:59-65`. Nebenwirkung: bestehende DEB/RPM-Installationen springen einmalig von `1.0` auf die echte Version.
|
||||
|
||||
---
|
||||
|
||||
## Stufe 2 — Gesicherter Download
|
||||
|
||||
Erst nach „Update herunterladen".
|
||||
|
||||
| Datei | Verantwortung |
|
||||
|---|---|
|
||||
| `service/update/UpdateDownloadPolicy.java` | Reine Validierung, kein IO |
|
||||
| `service/update/UpdateDownloadService.java` | Download + Verifikation |
|
||||
| `service/update/UpdateStorage.java` | `~/.praktiKST/updates/`, Aufräumen verwaister Dateien |
|
||||
| `model/UpdateDownloadResult.java` | Ergebnis-DTO |
|
||||
|
||||
**Ablauf** (Muster `TerrainPackageDownloader.java:93-165`):
|
||||
|
||||
1. Download nach `<fileName>.download`;
|
||||
2. Prüfung von Dateigröße **und** SHA-256 (`computeSha256`, `:175-187`, 8-KiB-Puffer + `HexFormat`);
|
||||
3. `Files.move` erst nach erfolgreicher Prüfung;
|
||||
4. bei Abbruch oder falscher Prüfsumme temporäre Datei löschen, verständliche Meldung;
|
||||
5. **niemals** ein ungeprüftes Artefakt starten.
|
||||
|
||||
Empfehlung: `BodyHandlers.ofInputStream()` + `DigestInputStream` statt `ofFile` — ein Durchlauf statt zwei, und ein Fortschrittsbalken ist bei 150-MB-Dateien Pflicht. Short-circuit, wenn die Zieldatei bereits mit passendem Hash existiert.
|
||||
|
||||
**Sicherheitsschranke — nicht optional:** SHA-256 aus dem Feed beweist nur, dass die Datei zum Feed passt. Da der Feed über einen selbst gebauten Host ausgeliefert wird, ist eine **Host-Allowlist** (`github.com`, `objects.githubusercontent.com`) die eigentliche Schutzschicht: selbst ein manipulierter Feed kann keine beliebige URL unterschieben. `UpdateDownloadPolicy` prüft zusätzlich: Schema `https`; `sha256` matcht `^[0-9a-fA-F]{64}$`; `fileName` ohne `/`, `\`, `..`; `fileSizeBytes` > 0 und < 1 GiB; ausreichend Plattenplatz; `packageType` erlaubt Download.
|
||||
|
||||
Stufe 2 führt **nichts** aus. Nach Erfolg: „Jetzt beenden und aktualisieren" / „Später installieren". Flatpak erhält gar keinen Download-Pfad, sondern den Hinweistext aus `<hintCommand>`.
|
||||
|
||||
---
|
||||
|
||||
## Stufe 3 — Plattformausführung, Windows-Installer, Signatur
|
||||
|
||||
### 3a. Windows-Installer
|
||||
|
||||
`--type msi` mit **dauerhaft konstanter** `--win-upgrade-uuid`, dazu `--win-menu --win-shortcut --win-dir-chooser`. `choco install wixtoolset` steht bereits in beiden Workflows (`tagged-release.yml:33-35`, `nightly-artifacts.yml:49-51`) und wird bisher **nicht genutzt** — die Voraussetzung ist vorhanden. Der ZIP-Build bleibt bestehen.
|
||||
|
||||
Die GUID muss dokumentiert werden (z. B. `packaging/windows/README.md`) — ändert sie sich, sind MSI-Upgrades dauerhaft kaputt. Asset in die `artifacts:`-Liste und in den SHA256SUMS-Schritt aufnehmen.
|
||||
|
||||
### 3b. Ausführung je Installationsart
|
||||
|
||||
| Installation | Verhalten |
|
||||
|---|---|
|
||||
| `windows-msi` | `msiexec /i "<datei>" /qb` detached, danach beenden |
|
||||
| `windows-zip` | Keine Ausführung. Installer laden, Ordner öffnen, Benutzerdaten bleiben. **Hinweis nötig**, dass der alte ZIP-Ordner bestehen bleibt und künftig der Installer-Eintrag zu starten ist — sonst startet der Nutzer weiter die alte `praktiKST.exe` und sieht nie wieder ein Update |
|
||||
| `macos-dmg` | `open "<dmg>"`, danach beenden; der Nutzer zieht selbst. Ein laufendes `.app` kann sich ohne separates Updater-Binary nicht ersetzen |
|
||||
| `linux-appimage` | Neues AppImage neben `$APPIMAGE` ablegen, `chmod +x`, Ordner öffnen, beenden. Kein In-Place-Overwrite einer laufenden Datei |
|
||||
| `flatpak` | Nur Verweis auf `flatpak update de.x08.KST4Contest`; keine Datei im Paket anfassen |
|
||||
| `linux-deb/rpm/arch` | `xdg-open "<datei>"` → GNOME Software / Discover / gdebi übernehmen inkl. Rechteabfrage. **Bewusst kein `pkexec`/`sudo`** aus der Anwendung heraus |
|
||||
| AUR | Verweis auf den vorhandenen AUR-Helper |
|
||||
| `UNKNOWN` | Ausschließlich Downloadseite öffnen |
|
||||
|
||||
Kein eigener Update-Starter. Der kontrollierte Ausstieg: Verbindung prüfen und ggf. bestätigen lassen → ON4KST sauber trennen → Layout/Preferences flushen → DB schließen → Installer starten → `Platform.exit()` + `System.exit(0)`. Kein `Runtime.halt`. Der vorhandene Weg über `Kst4ContestApplication.stop()` (`disconnect("CLOSEALL")` + `System.exit(0)`) bleibt die Basis.
|
||||
|
||||
### 3c. SignPath
|
||||
|
||||
Eigener Step im MSI-Job, gegated über das Vorhandensein des Secrets. Fehlt es (bis zur Foundation-Freigabe), läuft die Pipeline unverändert durch und liefert ein unsigniertes MSI. Signiertes Ergebnis unter eigenem Namen hochladen; `versionInfo.js` setzt `signatureState` nur, wenn dieses Asset existiert.
|
||||
|
||||
**Vorbedingung für die Abhängigkeitsprüfung:** `module-info.java:14-15` deklariert `requires org.junit.jupiter.api;` und `requires org.mockito;`, weil Testklassen unter `src/main/java/` liegen (u. a. `controller/On4KstProtocolTest.java`, `controller/On4KstSocketThreadTest.java`, `controller/ReadUDPByWintestThreadTest.java`, `test/MockKstServer.java`, `view/map/mapTest.java`). `pom.xml` deklariert `junit-jupiter-api` und `mockito-core` deshalb mit `<scope>compile</scope>`, und JUnit, Mockito, ByteBuddy und Objenesis landen im ausgelieferten Runtime-Image — im Flatpak in `lib/app/` nachgewiesen. Ausgerechnet ByteBuddy/Mockito (Bytecode-Manipulation, Agent) in einem signierten Produktionsbinary ist für so eine Prüfung ungünstig. Als **eigener, abgegrenzter Commit vor dem Antrag** bereinigen: Klassen nach `src/test/java/`, `requires` entfernen, Scopes zurück auf `test`.
|
||||
|
||||
---
|
||||
|
||||
## Tests
|
||||
|
||||
Alle neuen Tests unter `src/test/java/kst4contest/service/update/` bzw. `.../model/`, Fixtures unter `src/test/resources/update/`. **Nichts Neues unter `src/main/java`** — die dort liegenden Testklassen sind Altlast, keine Vorlage.
|
||||
|
||||
| Testklasse | Assertions |
|
||||
|---|---|
|
||||
| `UpdateFeedParserTest` | Legacy-Feed 1.44 ohne `<updatePackages>` parst korrekt; erweiterter Feed, Reihenfolge irrelevant; `<changeLog>` mit 8 Kindern → **keine** `ArrayIndexOutOfBoundsException`; kaputtes XML → leeres Ergebnis statt Exception; XXE-Payload wird nicht expandiert; `sha256` in Großbuchstaben wird normalisiert |
|
||||
| `UpdateFeedClientTest` | 200 → Zieldatei ersetzt; 404/500 → Temp gelöscht und **vorhandene Zieldatei unverändert** (die konkrete Regression gegenüber `UpdateChecker:54-71`); Timeout → `success=false`, kein Throw; leerer Body verworfen |
|
||||
| `UpdateCheckServiceTest` | 1.44.0/1.44.0 → kein Update; /1.45.0 → Update; /1.4.4 → kein Update; /1.44.1 → Update; kaputte `semanticVersion` → Double-Fallback statt Exception; Netz down + Cache → `CACHE`; ohne Cache → `NONE`; Paketauswahl je Typ; `UNKNOWN` → kein Paket; injizierte `Clock` für den Prüfrhythmus |
|
||||
| `RuntimePackageTypeResolverTest` | Property gewinnt; unbekannter Wert → `UNKNOWN`; `/.flatpak-info` → `FLATPAK` **auch gegen** widersprechende Property; `APPIMAGE` → AppImage; alles `null` → kein NPE |
|
||||
| `UpdateDownloadPolicyTest` | `http://` abgelehnt; fremder Host abgelehnt; fehlende/zu kurze/nicht-hex `sha256` abgelehnt; `fileName` mit `../` abgelehnt; Größe ≤ 0 abgelehnt; `FLATPAK`/`UNKNOWN` abgelehnt |
|
||||
| `UpdateDownloadServiceTest` | Ohne Netz über `com.sun.net.httpserver.HttpServer` auf Port 0 (JDK-only, keine neue Dependency): Hash-Mismatch → Temp gelöscht, Ziel **nicht** angelegt; Match → Bytes identisch; Non-2xx → Temp gelöscht; bereits gültige Datei → kein HTTP-Call; Progress monoton bis `totalBytes`; Abbruch → Temp gelöscht |
|
||||
| `UpdateLauncher*Test` (Stufe 3) | Injizierter `ProcessStarter` fängt die Kommandozeile: MSI → `[msiexec, /i, <abs>, /qb]`; deb/rpm/arch → `[xdg-open, <abs>]`; dmg → `[open, <abs>]`; **kein Kommando enthält `sudo` oder `pkexec`** (explizite Assertion); `FLATPAK`/`UNKNOWN`/`WINDOWS_ZIP` → `ProcessStarter` nie aufgerufen |
|
||||
| `website/test/version-info.test.js` | Klassifikator für alle Namensmuster; SHA256SUMS-Parsing inkl. Doppelspace; Release ohne Assets → Feed bleibt valide; erzeugter Feed hat weiterhin exakt 7 `<changeLog>`-Kinder |
|
||||
|
||||
Versionsvergleich: bestehende `VersionUtils`-Abdeckung um nicht-numerische Eingaben ergänzen.
|
||||
|
||||
---
|
||||
|
||||
## Dokumentation
|
||||
|
||||
Nach jeder Stufe eine gezielte Einordnung, kein Voll-Audit (`AGENTS.md`):
|
||||
|
||||
- `github_docs/de-Installation.md` und `github_docs/en-Installation.md` — Windows-Installer, Verhältnis zum ZIP, Update-Weg je Paketformat, Flatpak-Hinweis. Beide Sprachversionen semantisch gleichziehen.
|
||||
- Neuer Abschnitt zur Updatefunktion (Hinweis, Zustimmung, Contest-Regel, Verhalten je Installationsart) — DE und EN.
|
||||
- `docs/PROJECT_CONTEXT.md` — Abschnitt „Website / Deployment Relationship" (`:192-200`) um Feed-Format, Paketkennzeichnung, Host-Allowlist und die Entscheidung gegen ein Updater-Binary ergänzen.
|
||||
- `website/src/features/` prüfen, ob die Funktion dort dargestellt werden soll.
|
||||
- Screenshots des Hauptfensters veralten durch den Hinweisbereich — als veraltet markieren, nicht erfinden.
|
||||
|
||||
## Verifikation
|
||||
|
||||
1. `./mvnw -B test` — **Surefire-Berichte einzeln lesen**, nicht am Exit-Code messen (`AGENTS.md`: Testfehler brechen den Build nicht ab). Hinweis: auf Host-JDK 26 schlagen 8 Mockito-Tests umgebungsbedingt fehl; mit Temurin 21 prüfen.
|
||||
2. `cd website && npm test && npm run build && npm run validate:version-info` gegen einen erweiterten Beispiel-Feed.
|
||||
3. **Abwärtskompatibilität:** erweiterten Feed gegen den **alten** `UpdateChecker` laufen lassen und bestätigen, dass `<latestVersion>` und `<changeLog>` unverändert gelesen werden.
|
||||
4. **Startverhalten:** Anwendung mit nicht erreichbarer Feed-URL starten — die UI muss ohne Verzögerung und ohne Meldung hochkommen.
|
||||
5. **Contest-Regel:** mit ON4KST verbunden erscheint kein Hinweis; nach dem Trennen erscheint er.
|
||||
6. **Paketkennzeichnung:** je Artefakt einmal starten und die erkannte Installationsart prüfen. Der Flatpak lässt sich lokal testen — die Sandbox ist netzwerkseitig transparent (verifiziert).
|
||||
7. **Stufe 2:** Download mit absichtlich falscher Prüfsumme — es darf keine Zieldatei entstehen und nichts gestartet werden.
|
||||
|
||||
## Offene Punkte
|
||||
|
||||
1. **Zweite Feed-Quelle?** Wenn der serverseitige Build hinterherhinkt, sehen Clients einen veralteten Feed. Soll der Client hilfsweise `https://github.com/praktimarc/kst4contest/releases/latest/download/kst4ContestVersionInfo.xml` verwenden?
|
||||
2. **`test-publish-version-xml.yml`** bleibt vorerst unverändert, ist aber scharf (Feed ohne `<semanticVersion>`). Bei der späteren Umstellung auf GitHub Actions zusammenführen oder entfernen.
|
||||
3. **`--app-version` überall setzen** ändert die Paketversion bestehender DEB/RPM-Installationen einmalig von `1.0` auf die echte. Akzeptabel?
|
||||
4. **`UpdateChecker.java`** löschen oder als deprecated Fassade behalten? (`module-info.java` exportiert `kst4contest.controller`.)
|
||||
5. **MSI vs. ZIP** — soll MSI der empfohlene Windows-Weg werden? Beide Installationen können parallel existieren; ein MSI-Upgrade findet eine ZIP-Installation nicht.
|
||||
6. **Opt-out-Preference?** Soll `ChatPreferences` ein „Check for updates on start" bekommen? Der Abruf verrät IP und Version an den Feed-Host.
|
||||
7. **Prüfrhythmus** — einmal pro Start, oder höchstens alle 24 h über einen Zeitstempel in `~/.praktiKST/`?
|
||||
8. **Beta-Nutzer** — `1.46.0-beta` gegen Stable `1.45.0` ergibt „kein Update", weil `compareStableVersions` das Suffix abschneidet. Gewollt?
|
||||
9. **Signaturzustand** darf nur automatisch aus dem Build stammen, sonst driftet er.
|
||||
10. **Vertrauensmodell** — soll der Feed mittelfristig selbst signiert werden (Detached-Signatur + eingebauter Public Key)?
|
||||
11. **ZIP-Migration** — der Hinweistext für den Wechsel ZIP → Installer muss formuliert und in beiden Sprachversionen dokumentiert werden.
|
||||
+38
-1
@@ -52,7 +52,7 @@ JavaFX ObservableList / UI state
|
||||
|
||||
## Configuration and Layout Persistence
|
||||
|
||||
- The current `preferences.xml` configuration version is 7. Version 6 introduced optional managed leaf-column widths below `guiOptions`, identified by stable table and column IDs. Parent-column widths remain derived from their leaf columns.
|
||||
- Configuration and layout live in the `preferences.xml` of the **active operator profile**; see "Operator Profiles and Per-Profile Persistence" below. The current `preferences.xml` configuration version is 7. Version 6 introduced optional managed leaf-column widths below `guiOptions`, identified by stable table and column IDs. Parent-column widths remain derived from their leaf columns.
|
||||
- `GUIstationMapClusteringEnabled` is a layout preference below `guiOptions`. It defaults to `true`, is selectively autosaved and controls only screen-based clustering of nearby map markers. Missing or malformed values retain the enabled default for backward compatibility.
|
||||
- Stored widths take precedence. Without a usable entry, a managed column is sized once when meaningful table data first becomes available. Message and similar free-text columns use a flexible initial width instead of following the longest value.
|
||||
- Main-window and separate-monitor DXCluster/QSO tables use distinct layout IDs even though they share the underlying message stores.
|
||||
@@ -61,6 +61,27 @@ JavaFX ObservableList / UI state
|
||||
- Full and selective writes are synchronized and replace `preferences.xml` atomically. Missing, unknown or malformed width entries do not prevent loading and fall back to initial sizing.
|
||||
- Older configuration files require no migration. Older KST4Contest versions can ignore the additional elements; a complete rewrite by such a version may discard column widths without invalidating the remaining file.
|
||||
|
||||
## Operator Profiles and Per-Profile Persistence
|
||||
|
||||
- One operator profile owns one `preferences.xml` and one worked-station database. Everything else under `~/.praktiKST/` stays global: CSS, audio files, DEM and terrain packages, the error log and the version-info feed.
|
||||
- The **root profile** is the historic flat installation: `preferences.xml` and `praktiKST.db` directly below the application directory. It is never moved, and it always uses the common station database, because that database is the installation's own.
|
||||
- Additional profiles live under `profiles/<profileId>/`. `profileId` is a stable, file-system-safe slug assigned once; renaming a profile changes only its display name and never moves a directory.
|
||||
- The registry `profiles.xml` is created lazily. An installation that has only the flat layout gets no registry and no `profiles/` directory; the root profile is synthesised in memory. Startup with no or exactly one profile therefore asks nothing and writes nothing, and a downgrade to an older release is a no-op.
|
||||
- The registry stores `profileId`, `displayName`, `rootProfile` and `sharedWorkedDatabase`, never a path. Both file names are derived in `OperatorProfilePaths` alone, so a stored path cannot drift apart from the flag that produced it.
|
||||
- `sharedWorkedDatabase` resolves to a path, not to a schema change: a sharing profile points at the flat `praktiKST.db`, an owning profile at its own file. There is no owner column, and no SQL statement in `DBController` knows about profiles.
|
||||
- A profile database is created **empty**. The bundled `/praktiKST.db` resource carries several thousand foreign callsigns and `user_version = 0`; seeding an additional profile from it would show a new operator foreign data and trigger the full callsign-normalization rebuild. Only the root installation is seeded from the resource. `preferences.xml` of a new profile *is* seeded from `/praktiKSTpreferences.xml`, because its defaults are what a first installation gets.
|
||||
- Worked-state semantics are unchanged and now apply per database file: normalized base callsign as key, worked state shared across suffix variants, three-day expiry, manual reset.
|
||||
- `stn_loginCallSign` and `stn_loginCallSignRaw` default to empty. The preferences reader treats an empty element as "not set" and falls back to the field default, so a non-empty default would make a profile created without credentials come up carrying a compiled-in callsign.
|
||||
- Passwords remain plaintext per profile. Profiles separate configuration; they are explicitly not an access-control boundary. This is documented in both manuals.
|
||||
|
||||
### Runtime profile switching
|
||||
|
||||
- A switch tears the current runtime down through `Kst4ContestApplication.shutdownRuntime()` and builds a **new** `Kst4ContestApplication` instance. Reusing the instance is not possible: many controls are inline-initialised instance fields, so a second `start()` would re-parent mounted nodes and register every listener twice. The approach is only sound because the class holds no mutable static state.
|
||||
- `Platform.setImplicitExit(false)` is required, because closing every window during a switch would otherwise end the process. All exits therefore run through `ApplicationRuntimeLauncher.exitApplication()`, including the main window's close handler; JavaFX calls `stop()` only on the instance it launched itself.
|
||||
- `shutdownRuntime()` is idempotent and must release everything that outlives a disconnect: the ON4KST supervisor thread, the sked reminder scheduler, the reachability executor, the PSTRotator retry scheduler, the map tile proxy, the station map bridge listeners and its coalescing animation, both view timers and every owned stage. Several of these were real leaks before; they only became visible once a second runtime could exist.
|
||||
- `ApplicationConstants.sessionRuntimeUniqueId` must not be regenerated during a switch, so UDP readers started earlier still recognise their own poison pill.
|
||||
- The layout autosave is flushed and then cancelled before a switch, so a pending debounced write cannot land after the profile changed.
|
||||
|
||||
## External Interfaces
|
||||
|
||||
Treat current implementation/tests and authoritative upstream documentation as source of truth before modifying any interface.
|
||||
@@ -101,9 +122,21 @@ CR/LF framing, XML framing, ports/transports, callsign normalization and frequen
|
||||
- External logger threads do not read or mutate the JavaFX user-list projection. `ChatController` applies global and per-band Worked state to every active variant of the base callsign on the JavaFX Application Thread before evaluating a band-upgrade notice.
|
||||
- The established Win-Test handling for 24, 47 and 76 GHz remains unchanged. Their Worked flags are retained, while only frequencies represented by the project `Band` model can create worked-grid state.
|
||||
|
||||
### Win-Test log recovery
|
||||
|
||||
- Win-Test only broadcasts new QSOs. A listener started later never sees the earlier ones, so KST4Contest pulls them with the Win-Test `IHAVE` / `NEEDQSO` protocol, ported from the wtKST `WtLogSync` implementation. The answers are ordinary `ADDQSO` packets and reuse the established Worked path; the recovery itself never touches database or UI.
|
||||
- The recovery is not configurable. It is bound to the existing Win-Test network listener, runs automatically once a station is detected through `HELLO` or `STATUS`, and stays active so gaps caused by lost broadcasts are refetched.
|
||||
- The station-name filter remains a QRG-sync setting. Log recovery covers every station in the network, because each band station of a multi-station setup keeps its own log and contributes per-band Worked state.
|
||||
- A QSO is identified by `StationName@LogUniqueID` plus the Win-Test QSO number. That identity deduplicates the answers of overlapping requests, so a recovered log is written once instead of once per resend.
|
||||
- Win-Test framing must be resolved on the raw datagram bytes: the checksum byte is not valid ASCII and would otherwise corrupt the trailing fields, which carry the log ID of `ADDQSO` and the run-length inventory of `IHAVE`. A broken checksum discards `IHAVE` only; the established handling of the other message types is unchanged and still does not verify checksums.
|
||||
- Win-Test answers broadcasts only; an identical unicast request to the same station stays unanswered (verified against Win-Test). Outgoing Win-Test packets therefore derive their broadcast address from the source address of received Win-Test packets, with the configured address as fallback for a station behind a router. A configured address pointing at a non-existent network raises no send error, so it silently disabled both log recovery and SKED handover before. Only genuine Win-Test message types update that address; internal control packets such as the poison pill must not redirect outgoing traffic.
|
||||
- `IHAVE` inventories are run-length encoded and may be split, so the announced first row is honoured instead of assuming that an inventory starts at QSO number one. A station that never sends a usable inventory is served by a blind block fallback starting at QSO number one.
|
||||
|
||||
### Terrain data providers
|
||||
|
||||
- The active terrain profile provider is Open-Meteo using Copernicus GLO-90 data.
|
||||
- The terrain profile cache lives in its own global database `~/.praktiKST/terrainprofilecache.db`. It is deliberately not part of an operator profile: terrain profiles are pure geometry derived from two locators and a sample count, and at a multi operator station both operators share one location, so a per-profile copy would only double the traffic against the terrain service.
|
||||
- Cached entries are separated by owner identity through the primary key (`owner_callsign_raw` + `owner_locator6`). Earlier versions stored a single owner identity in a meta table and dropped the whole cache whenever the configured callsign or locator changed; with several operator profiles that would discard every computed profile on each switch. The old `TerrainProfileCache*` tables inside `praktiKST.db` are left in place and are still readable by older releases; the new file starts empty and refills itself.
|
||||
- `OfflineDemImportService` only prepares a local directory and copies manually selected Copernicus GLO-30 GeoTIFF files into it. Importing files does not activate an offline provider or change the active calculation chain.
|
||||
|
||||
### ON4KST session and authentication
|
||||
@@ -162,6 +195,10 @@ The repository contains the KST4Contest website under `website/`, published sepa
|
||||
|
||||
Current website/deployment scripts and update-feed behaviour must be inspected before changes; do not rely on historical assumptions.
|
||||
|
||||
- `APPLICATION_CURRENT_VERSION` is the user-visible semantic version and must use the dotted `major.minor.patch` form. `APPLICATION_CURRENTVERSIONNUMBER` is retained only for older feeds and encodes patch releases by appending the patch digit, for example `1.43.1` as `1.431`.
|
||||
- The tagged-release workflow creates the GitHub Release before building the website update feed. This ordering is required because `versionInfo.js` reads the published release body through the GitHub Releases API.
|
||||
- After publication, the workflow tests and builds the website, validates the expected Stable version, attaches `kst4ContestVersionInfo.xml` to the release and uploads the complete website build as a workflow artifact.
|
||||
|
||||
## Important Decisions and Workarounds
|
||||
|
||||
- Preserve full callsign/category identity while applying base-call normalisation only to specifically defined features.
|
||||
|
||||
+103
-12
@@ -8,6 +8,107 @@ Die veröffentlichten Stable-Versionen und ihre Programmpakete stehen unter [Git
|
||||
|
||||
---
|
||||
|
||||
## v1.50 (in Entwicklung)
|
||||
|
||||
**Operator-Profile**
|
||||
|
||||
Mehrere Operateure an einem Rechner können jetzt eigene Rufzeichen, Locators und Layouts verwenden, ohne sich gegenseitig die Konfiguration zu überschreiben. Damit ist [Issue #57](https://github.com/praktimarc/kst4contest/issues/57) umgesetzt.
|
||||
|
||||
### Neu
|
||||
|
||||
- **Operator-Profile:** Jedes Profil hat seine eigene `preferences.xml` und damit eigene fachliche Einstellungen und einen eigenen Layoutstand. Verwaltet werden Profile im neuen Reiter **Profiles** des Einstellungsfensters: anlegen, duplizieren, umbenennen, löschen und aktivieren.
|
||||
|
||||
- **Gemeinsame oder eigene gearbeitete Stationen:** Pro Profil wird entschieden, ob es eine eigene Worked-Datenbank bekommt oder die gemeinsame Stationsdatenbank benutzt. Eine Multi-OP-Station mit einem einzigen Stationslog teilt den Worked-Status, zwei OMs mit verschiedenen Rufzeichen an einem Rechner trennen ihn.
|
||||
|
||||
- **Profilwahl beim Start:** Mit nur einem Profil fragt KST4Contest beim Start nichts und verhält sich unverändert. Ab zwei Profilen erscheint eine kleine Auswahl mit vorausgewähltem letzten Profil; Enter oder Doppelklick starten sofort. Der Aufrufparameter `--profile=<Name>` überspringt die Auswahl.
|
||||
|
||||
- **Profilwechsel im laufenden Betrieb:** **File → Switch operator profile...** trennt die Verbindung und baut die Oberfläche mit den Einstellungen des gewählten Profils neu auf, ohne Programmneustart.
|
||||
|
||||
### Geändert
|
||||
|
||||
- **Zwischenspeicher der Geländeprofile getrennt:** Berechnete Geländeprofile liegen jetzt in der eigenen, gemeinsam genutzten Datei `terrainprofilecache.db` und werden nach Besitzer getrennt gespeichert. Bisher wurde der gesamte Zwischenspeicher gelöscht, sobald sich Rufzeichen oder Locator änderten; bei einem Profilwechsel wäre damit jedes berechnete Profil verloren gegangen.
|
||||
|
||||
- **Rufzeichen-Vorgabe ist leer:** Fehlt in der `preferences.xml` ein Login-Rufzeichen, bleibt das Feld jetzt leer, statt auf ein im Programm hinterlegtes Rufzeichen zurückzufallen. Ein neu angelegtes Profil startet damit bewusst ohne Anmeldedaten.
|
||||
|
||||
### Behoben
|
||||
|
||||
- **Freigegebene Hintergrundressourcen:** Der ON4KST-Überwachungsthread, der Sked-Erinnerungs-Scheduler, der Reachability-Executor, der PSTRotator-Wiederholungs-Scheduler und der Kachel-Proxy der Karte werden beim Schließen des Chatcontrollers freigegeben. Bisher liefen sie bis zum Programmende weiter.
|
||||
|
||||
### Hinweise zur Aktualisierung
|
||||
|
||||
- Bestehende Installationen werden **nicht** verändert: `preferences.xml` und `praktiKST.db` bleiben genau dort liegen, wo sie sind, und werden zum Profil **Default**. Es wird keine Datei verschoben oder kopiert.
|
||||
- Eine Profil-Registry entsteht erst beim Anlegen des zweiten Profils. Wer nur ein Profil benutzt, merkt von der Änderung nichts.
|
||||
- Eine Rückkehr zu einer älteren KST4Contest-Version bleibt möglich; sie findet ihre Dateien unverändert vor.
|
||||
- Passwörter stehen weiterhin im Klartext in der `preferences.xml` des jeweiligen Profils. Profile trennen die Konfiguration, sie sind kein Zugriffsschutz.
|
||||
|
||||
---
|
||||
|
||||
## v1.43.1 (2026-09-03)
|
||||
|
||||
**Korrigierte Versionsmetadaten**
|
||||
|
||||
v1.43.1 enthält dieselben funktionalen Änderungen wie v1.43.0. Korrigiert wurden die Anwendungs- und Build-Metadaten für Anzeige, ON4KST-Kennung und Update-Vergleich. Ein Teil der Metadaten des ersten v1.43.0-Pakets wies den Build noch als Version 1.42 aus.
|
||||
|
||||
### Behoben
|
||||
|
||||
- **Einheitliche semantische Version:** Die sichtbare Anwendungsversion verwendet jetzt vollständig `1.43.1`. Der kompakte Wert `1.431` bleibt ausschließlich im veralteten numerischen Feld für die Kompatibilität mit älteren Update-Feeds erhalten.
|
||||
|
||||
- **Update-Feed im Tagged-Release-Workflow:** Website-Build, Prüfung des Versionsfeeds und Upload der Artefakte laufen jetzt tatsächlich nach der Veröffentlichung des GitHub Releases. Diese Schritte waren zuvor versehentlich in die Artefaktliste der Release-Action eingerückt und wurden deshalb übersprungen.
|
||||
|
||||
Wer v1.43.0 installiert hat, sollte v1.43.1 verwenden. Die Funktionen bleiben unverändert; korrigiert werden nur die Versionsmetadaten und der Release-Workflow.
|
||||
|
||||
Die korrigierte Version ist als [Release v1.43.1](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.1) verfügbar.
|
||||
|
||||
---
|
||||
|
||||
## v1.43.0 (2026-09-03)
|
||||
|
||||
**Zuverlässigere Log-Synchronisation, gespeicherte Tabellenlayouts und bessere DX-Cluster-Kompatibilität**
|
||||
|
||||
v1.43 konzentriert sich auf die zuverlässige Verarbeitung externer Logdaten und den stabilen Betrieb während längerer Conteste. Hinzu kommen praktische Einstellmöglichkeiten für Tabellenlayouts und die Stationsgruppierung auf der Karte.
|
||||
|
||||
### Neu
|
||||
|
||||
- **Optionale Kartencluster:** **Group nearby stations** schaltet die räumliche Gruppierung bei niedrigen Zoomstufen unmittelbar ein oder aus. Die gespeicherte Auswahl verändert weder Kartenausschnitt noch Stationsauswahl; die Zusammenfassung aktiver Varianten desselben Basisrufzeichens bleibt davon unabhängig. Damit ist [Issue #79](https://github.com/praktimarc/kst4contest/issues/79) umgesetzt.
|
||||
|
||||
- **Tabellenlayout automatisch gesichert:** Tabellen erhalten beim ersten brauchbaren Inhalt sinnvolle Breiten. Manuell geänderte Spaltenbreiten, Fenstergrößen und relevante Divider werden nach kurzer Verzögerung in `preferences.xml` geschrieben. Haupt- und Monitorfenster behalten getrennte Layouts für DXCluster und QSO of the other.
|
||||
|
||||
- **Tooltips für gekürzte Tabellenwerte:** Normale Tabellenzellen zeigen ihren vollständigen Inhalt, wenn die sichtbare Spalte zu schmal ist. Funktionale Tooltips und anklickbare Links bleiben davon unberührt.
|
||||
|
||||
- **Hinweis bei neu angelegtem Simplelogfile:** Fehlt die ausgewählte Datei, legt KST4Contest sie an und zeigt einen Hinweis mit Dateipfad, konkretem Testablauf und Link zum passenden Abschnitt des Handbuchs.
|
||||
|
||||
### Geändert
|
||||
|
||||
- **Robuste Simplelogfile-Auswertung:** Die ausgewählte Datei wird einmal pro Minute ausgewertet und nach jedem Durchlauf geschlossen, damit das Logprogramm sie ersetzen oder rotieren kann. Erkannte Rufzeichen setzen den globalen Worked-Status für alle aktiven Suffixvarianten des Basisrufzeichens. Bei deaktivierter Funktion findet kein Dateizugriff statt; Lese- oder Erstellungsfehler beenden die periodische Aufgabe nicht mehr.
|
||||
|
||||
- **Einheitliche Bandwerte externer Logger:** UCXLog-kompatible Pakete und Win-Test-Ereignisse verwenden eine gemeinsame Bandnormalisierung. Numerische Werte, Meter- und Zentimeterangaben sowie die vorhandenen Win-Test-IDs setzen damit dieselben Worked-Markierungen und Worked-Großfelder. Insbesondere `2320`, `5760` und `10368` werden zuverlässig verarbeitet; bei fehlendem oder unbekanntem Band wird nur der globale Worked-Status gesetzt.
|
||||
|
||||
- **Kompakte vollständige Frequenzen erkannt:** Vollständige Frequenzangaben ohne Dezimaltrenner werden auf allen unterstützten Bändern akzeptiert; die letzten drei Ziffern bilden den kHz-Anteil. Nackte dreistellige Zahlen benötigen weiterhin einen erkennbaren Frequenzkontext, damit Signalrapporte und andere Zahlen nicht als QRG behandelt werden.
|
||||
|
||||
- **DXSpider-kompatibles Spotformat:** Lokale DX-Cluster-Spots verwenden eine feste 75-Zeichen-Nutzzeile mit dem DX-Rufzeichen ab Spalte 27, einem 30 Zeichen breiten Kommentarfeld und der UTC-Zeit ab Spalte 71. Das Format bleibt bis 24 GHz stabil. Überlange DX-Rufzeichen werden verworfen und protokolliert, statt unbemerkt abgeschnitten zu werden. Damit ist [Issue #86](https://github.com/praktimarc/kst4contest/issues/86) behoben.
|
||||
|
||||
- **Aktive ON4KST-Verbindungsprüfung:** Ein ruhiger Chatserver wird mit einer expliziten, sitzungsweiten Abfrage geprüft, bevor die Verbindung als unterbrochen gilt. Heartbeat und Prüftelegramme behalten das erforderliche CR/LF-Framing.
|
||||
|
||||
- **Zuverlässige Altersmarkierung privater Nachrichten:** Eingehende Privatnachrichten verwenden bis zu fünf Minuten lang die definierten grünen Altersstufen. Eigene Nachrichten behalten ihre separate Darstellung; leere oder wiederverwendete Tabellenzeilen kehren zum normalen Design zurück und behalten keine veraltete Hervorhebung.
|
||||
|
||||
### Behoben
|
||||
|
||||
- **Worked-Status nach dem Login:** Persistierte SQLite-Informationen werden vor der Veröffentlichung jeder initialen ON4KST-Benutzerliste geladen und angewendet. Erneute Verbindungen, beide Kategorien und alle aktiven Varianten eines Basisrufzeichens starten dadurch mit dem richtigen Status. Damit ist [Issue #85](https://github.com/praktimarc/kst4contest/issues/85) behoben.
|
||||
|
||||
- **Fehlerhafte Trennung bei ruhigem Server:** Eine gültige ON4KST-Verbindung wird nicht mehr beendet, nur weil der Server gerade keine Aktivitätszeilen überträgt.
|
||||
|
||||
### Dokumentation und Auslieferung
|
||||
|
||||
- Das deutsche und englische Handbuch wurden mit der Implementierung abgeglichen und überarbeitet. Ein neues Kapitel zum Contest-Workflow verbindet die einzelnen Funktionen zu einem praktischen Betriebsablauf; außerdem wurden die Abschnitte zu Dual Chat, Privatnachrichten, QRG-Synchronisation, Simplelogfile-Auswertung und Konfiguration präzisiert.
|
||||
|
||||
- Die Website beschreibt Band- und Richtungsgelegenheiten, Stationskarte, QRG-Verarbeitung, Filter, globale Nachrichtenansichten, Privatnachrichten und Log-Synchronisation jetzt ausführlicher.
|
||||
|
||||
- Die AUR-Paketdefinitionen wurden auf v1.43.0 aktualisiert.
|
||||
|
||||
Die vollständige Funktionalität von v1.43.0 steht im [Release v1.43.0](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.0) bereit. Wegen der inkonsistenten eingebetteten Versionsmetadaten ist v1.43.1 der empfohlene Paketstand.
|
||||
|
||||
---
|
||||
|
||||
## v1.42.0 (2026-08-22)
|
||||
|
||||
**Gemeinsamer Bandkontext, sitzungsbasierte ON4KST-Verbindung und signierte macOS-Pakete**
|
||||
@@ -38,21 +139,17 @@ v1.42 führt mehrere bisher getrennte Auswertungen zusammen. Bandinformationen,
|
||||
|
||||
- **Filter zurücksetzen:** Ein eigener Reset-Button entfernt die aktiven Filterprädikate der Benutzerliste zuverlässig.
|
||||
|
||||
- **Optionale Kartencluster:** **Group nearby stations** schaltet die räumliche Gruppierung bei niedrigen Zoomstufen unmittelbar ein oder aus. Die automatisch gespeicherte Auswahl verändert weder Kartenausschnitt noch Stationsauswahl; die Zusammenfassung aktiver Varianten desselben Basisrufzeichens bleibt davon unabhängig. Damit ist [Issue #79](https://github.com/praktimarc/kst4contest/issues/79) umgesetzt.
|
||||
- **Kartencluster:** Räumlich dicht beieinanderliegende Stationen werden bei niedrigen Zoomstufen zusammengefasst. Die ausgewählte Station und relevante Richtungsgelegenheiten bleiben einzeln sichtbar.
|
||||
|
||||
- **Ausblendbare Streckenanalyse:** Geländeprofil und Analysebereich der Stationskarte können vollständig ausgeblendet werden. Die Auswahl wird gespeichert und beim nächsten Programmstart wiederhergestellt.
|
||||
|
||||
### Geändert
|
||||
|
||||
- **Tabellenlayout automatisch gesichert:** Tabellen werden beim ersten brauchbaren Inhalt sinnvoll dimensioniert. Manuell geänderte Spaltenbreiten, Fenstergrößen und relevante Divider werden verzögert in `preferences.xml` gespeichert; Haupt- und Monitorfenster behalten für DXCluster und QSO of the other getrennte Layouts. Gekürzte normale Zellwerte zeigen ihren Volltext im Tooltip, ohne funktionale Tooltips oder anklickbare Links zu verdrängen.
|
||||
|
||||
- **DX-Cluster-Zeilenformat vereinheitlicht:** Lokale Spots verwenden jetzt eine feste, DXSpider-kompatible 75-Zeichen-Nutzzeile mit dem DX-Rufzeichen ab Spalte 27, einem 30 Zeichen breiten Kommentarfeld und der UTC-Zeit ab Spalte 71. Das Format bleibt auch bei Mikrowellenfrequenzen bis 24 GHz stabil. Überlange DX-Rufzeichen werden verworfen und protokolliert, statt still abgeschnitten zu werden; AirScout- und Testkommentare sind entsprechend kompakter.
|
||||
|
||||
- **Sessionbezogene ON4KST-Verbindungssteuerung:** Socket, Reader, Writer, Messagebus und Warteschlangen gehören jetzt zu einer eindeutig identifizierten Verbindungssession. Veraltete Threads einer abgelösten Verbindung können dadurch keine Daten mehr verarbeiten oder die neue Verbindung schließen. `ONLINE` wird erst nach bestätigtem Login und vollständig empfangenen Benutzerlisten gemeldet. Verbindungsaufbau, Login und Synchronisation besitzen feste Zeitlimits; Heartbeats, ausbleibende Eingangsdaten, EOF sowie Lese- und Schreibfehler werden überwacht und lösen bei Bedarf einen kontrollierten Neuaufbau mit Backoff aus.
|
||||
|
||||
- **ON4KST-Protokollbefehle abgesichert:** Ausgehende Befehle werden zentral aufgebaut und auf gültige Kategorien, Locatoren und unerlaubte Frame-Trennzeichen geprüft. Da ON4KST pro TCP-Session nur einen Locator verwaltet, wird für beide Chat-Kategorien der Hauptlocator verwendet und eine abweichende zweite Konfiguration protokolliert, statt widersprüchliche Befehle an den Server zu senden.
|
||||
|
||||
- **QRG-Erkennung präzisiert:** Vollständige Frequenzangaben werden auch ohne Dezimaltrenner erkannt; die letzten drei Ziffern bilden dabei den kHz-Anteil. Relative Frequenzen bleiben unverändert, und nackte dreistellige Zahlen gelten weiterhin nur bei erkennbarem Frequenzkontext als QRG. Signalrapporte, Bandangaben und andere Zahlen erzeugen dadurch seltener falsche Frequenzen.
|
||||
- **QRG-Erkennung präzisiert:** Vollständige und relative Frequenzangaben werden weiterhin erkannt. Nackte dreistellige Zahlen gelten nur noch bei erkennbarem Frequenzkontext als QRG. Signalrapporte, Bandangaben und andere Zahlen erzeugen dadurch seltener falsche Frequenzen.
|
||||
|
||||
- **Stationsbezogener Frequenzkontext:** Bei relativen QRGs verwendet KST4Contest zuerst einen höchstens 30 Minuten alten Bandkontext derselben Station. Erst wenn dieser fehlt, wird das global konfigurierte Fallback-Band verwendet.
|
||||
|
||||
@@ -86,10 +183,6 @@ v1.42 führt mehrere bisher getrennte Auswertungen zusammen. Bandinformationen,
|
||||
|
||||
- **DXLog-Gesamtlog übernommen:** Der UCXLog-kompatible UDP-Listener verarbeitet neben `contactinfo` auch `contactreplace`. Dadurch kann ein von DXLog.net als vollständiges Log ausgesendeter Datenbestand eingelesen werden.
|
||||
|
||||
- **Logger-Bandwerte vereinheitlicht:** Numerische sowie Meter- und Zentimeterangaben aus UCXLog-kompatiblen QSO-Paketen und die Band-IDs von Win-Test werden einmal normalisiert und danach einheitlich für Worked-Markierungen und Worked-Großfelder verwendet. Dadurch setzen insbesondere `2320`, `5760` und `10368` zuverlässig ihre vorhandenen Bandmarkierungen. Bei einem fehlenden oder unbekannten Band bleibt es beim globalen Worked-Status.
|
||||
|
||||
- **Simplelogfile-Verhalten präzisiert:** Die ausgewählte Textdatei wird einmal pro Minute mit einem festen Rufzeichenmuster ausgewertet. Treffer setzen den globalen Worked-Status aller aktiven Varianten des Basisrufzeichens, werden aber nicht in SQLite persistiert. Eine fehlende Datei wird angelegt; Lese- und Erstellungsfehler beenden die periodische Auswertung nicht. Ein Datenbank-Reset verändert die Datei nicht, sodass enthaltene Rufzeichen bei der nächsten Auswertung erneut als gearbeitet markiert werden.
|
||||
|
||||
- **Automatische QRG-Übernahme abgesichert:** `MYQRG` wird nur von einer aktivierten Schnittstelle aktualisiert, die tatsächlich gültige `RadioInfo`- beziehungsweise Win-Test-`STATUS`-Pakete liefert. Eine aktivierte, aber nicht liefernde Quelle ersetzt die notwendige Funktionsprüfung oder manuelle QRG-Pflege nicht.
|
||||
|
||||
- **Versionserkennung verbessert:** Versionsnummern werden semantisch verglichen, damit beispielsweise Patch-Versionen und Nightly-Stände nicht mehr durch eine einfache Fließkommazahl falsch eingeordnet werden.
|
||||
@@ -98,8 +191,6 @@ v1.42 führt mehrere bisher getrennte Auswertungen zusammen. Bandinformationen,
|
||||
|
||||
- **Zuverlässige Benutzerliste beim Login:** Ungültige oder unvollständige `UA0`-Teilnehmerdatensätze werden einzeln verworfen und protokolliert, ohne die Verarbeitung der alphabetisch folgenden Teilnehmer abzubrechen. Die gültigen Einträge werden zunächst pro Kategorie gesammelt und erst mit dem ersten zugehörigen `UE`-Abschlussframe vollständig veröffentlicht.
|
||||
|
||||
- **Persistierter Worked-Status beim Listenaufbau:** Beim Abschluss jeder initialen ON4KST-Benutzerliste wird der SQLite-Zustand einmal geladen und vor der Veröffentlichung auf die neuen Chatmember angewendet. Das gilt für beide Kategorien, erneute Verbindungen und alle aktiven Varianten eines Basisrufzeichens.
|
||||
|
||||
- **Benutzerliste verschwindet nach dem Login:** ON4KST kann nach Namens-, Status- oder anderen Live-Änderungen weitere `UE`-Frames für dieselbe Kategorie senden. Wiederholte Abschlussframes werden jetzt erkannt und ignoriert, damit eine bereits gefüllte Benutzerliste nicht durch eine leere Momentaufnahme ersetzt wird.
|
||||
|
||||
- **Fehlgeschlagener Erstaufbau und Verbindungsverlust:** Wenn beim Programmstart keine Verbindung zum Server hergestellt werden kann, läuft KST4Contest nicht mehr in eine Endlos- oder Busy-Wait-Schleife. Die Oberfläche bleibt bedienbar und weitere Versuche erfolgen mit begrenztem Backoff. Auch ein vom Server geschlossener oder über längere Zeit stummer Socket wird zuverlässig erkannt.
|
||||
|
||||
@@ -240,6 +240,24 @@ Prüfe zuerst, welche Frequenzen für die betreffende Station innerhalb der letz
|
||||
|
||||
Ist kein aktueller Stationskontext vorhanden, prüfe die Auswahl unter **Fallback band for relative QRG detection**. Das Fallback wird nur benötigt, wenn sich das Band weder aus einer vollständigen Frequenz noch aus dem aktuellen Kontext des Absenders ergibt.
|
||||
|
||||
### Das Logprogramm läuft in einer eigenen Sandbox
|
||||
|
||||
Ein Logprogramm, das als Flatpak oder über eine Wine-Umgebung wie Bottles gestartet wird, benutzt die Netzwerkrechte dieser Sandbox. Teilt die Sandbox das Netzwerk des Rechners nicht, ist `127.0.0.1` darin nicht das `127.0.0.1`, auf dem KST4Contest lauscht. Die Verbindung wird dann abgewiesen, obwohl KST4Contest den Port korrekt meldet.
|
||||
|
||||
Bei einem Flatpak-Logprogramm lassen sich die Rechte so prüfen:
|
||||
|
||||
```bash
|
||||
flatpak info --show-permissions <Anwendungs-ID>
|
||||
```
|
||||
|
||||
Im Abschnitt `[Context]` muss `shared=network` stehen. Nachträglich vergeben lässt es sich mit:
|
||||
|
||||
```bash
|
||||
flatpak override --user --share=network <Anwendungs-ID>
|
||||
```
|
||||
|
||||
Das Gleiche gilt, wenn KST4Contest selbst als Flatpak läuft. Dessen veröffentlichtes Manifest enthält `--share=network` bereits, ein lauschender Port ist daher vom Rechner selbst und von anderen Anwendungen darauf erreichbar.
|
||||
|
||||
### Der Spot wird vom Logger ausgeblendet
|
||||
|
||||
Verwende ein Spotter-Rufzeichen, das nicht mit dem eigenen Contest-Rufzeichen identisch ist. Abhängig vom Logger können eigene Spots gefiltert oder besonders behandelt werden.
|
||||
|
||||
@@ -878,6 +878,61 @@ Anzeige und Herleitung: [Gearbeitete Rufzeichen, neue Bänder und neue Großfeld
|
||||
|
||||
---
|
||||
|
||||
## Operator-Profile (ab v1.50)
|
||||
|
||||
Mehrere Operateure an einem Rechner brauchen unterschiedliche Rufzeichen, Locators und Layouts. Ein Operator-Profil bündelt genau das: **jedes Profil hat seine eigene `preferences.xml` und damit seine eigenen fachlichen Einstellungen und seinen eigenen Layoutstand.**
|
||||
|
||||
### Wo die Profile liegen
|
||||
|
||||
| Profil | Einstellungen | Gearbeitete Stationen |
|
||||
|---|---|---|
|
||||
| **Default** | `~/.praktiKST/preferences.xml` | `~/.praktiKST/praktiKST.db` |
|
||||
| weitere Profile | `~/.praktiKST/profiles/<Profil-ID>/preferences.xml` | je nach Einstellung gemeinsam oder `~/.praktiKST/profiles/<Profil-ID>/praktiKST.db` |
|
||||
|
||||
Unter Windows entsprechend unterhalb von `%USERPROFILE%\.praktiKST\`.
|
||||
|
||||
Alle übrigen Daten bleiben gemeinsam: Klangdateien, Farbschemata, DEM- und Terrainpakete, der Zwischenspeicher der Geländeprofile (`terrainprofilecache.db`), das Fehlerprotokoll und die Versionsinformationen.
|
||||
|
||||
Das Profil **Default** benutzt weiterhin genau die Dateien, die eine bestehende Installation schon hat. **Bei der Aktualisierung auf v1.50 wird keine Datei verschoben, kopiert oder umgeschrieben.** Wer eine ältere KST4Contest-Version wieder installiert, findet seine Konfiguration und seine gearbeiteten Stationen unverändert vor.
|
||||
|
||||
### Gemeinsame oder eigene gearbeitete Stationen
|
||||
|
||||
Beim Anlegen eines Profils wird entschieden, woher dessen Worked-, NOT-QRV- und Großfeld-Daten kommen:
|
||||
|
||||
- **Eigene gearbeitete Stationen** (Vorgabe): Das Profil bekommt eine eigene, zunächst leere Datenbank. Sinnvoll, wenn sich zwei OMs mit verschiedenen Rufzeichen einen Rechner teilen.
|
||||
- **Gemeinsame Stationsdatenbank**: Das Profil benutzt `~/.praktiKST/praktiKST.db`, also dieselbe Datenbank wie das Profil **Default**. Das ist der Fall der **Multi-OP-Station**: es gibt nur ein Stationslog, also soll auch der Worked-Status für alle Operateure derselbe sein.
|
||||
|
||||
Ein Wechsel zwischen beiden Einstellungen verschiebt keine Daten. Bereits gesammelte Worked-Daten bleiben dort liegen, wo sie entstanden sind. Der Drei-Tage-Ablauf und die Reset-Schaltfläche wirken jeweils auf die Datenbank des gerade aktiven Profils.
|
||||
|
||||
### Profile verwalten
|
||||
|
||||
Der Reiter **Profiles** im Einstellungsfenster zeigt alle Profile mit Name, Art der Worked-Daten und letzter Benutzung.
|
||||
|
||||
- **New profile...** legt ein Profil an. Es startet **ohne Rufzeichen und ohne Passwort**; beides wird anschließend im Reiter **Station** eingetragen.
|
||||
- **Duplicate...** übernimmt die komplette Konfiguration des gewählten Profils — Antenne, Locator, Layout, Beacon, Integrationen — **außer Rufzeichen und Passwort**. Gearbeitete Stationen werden nie mitkopiert.
|
||||
- **Rename...** ändert nur den angezeigten Namen. Verzeichnisse und Dateien bleiben unberührt.
|
||||
- **Delete...** entfernt das Profilverzeichnis endgültig. Das Profil **Default** und das gerade aktive Profil lassen sich nicht löschen. Bei einem Profil mit gemeinsamer Stationsdatenbank bleibt diese unangetastet.
|
||||
- **Change worked stations...** schaltet zwischen gemeinsamer und eigener Datenbank um.
|
||||
- **Switch to selected profile...** wechselt das Profil im laufenden Betrieb.
|
||||
|
||||
### Profilwahl beim Start
|
||||
|
||||
- Solange nur **ein** Profil existiert, fragt KST4Contest beim Start **nichts** und startet wie bisher. Es wird auch keine Profil-Registry angelegt. Erst das Anlegen des zweiten Profils erzeugt `~/.praktiKST/profiles.xml`.
|
||||
- Ab **zwei** Profilen erscheint beim Start eine kleine Auswahl. Das zuletzt benutzte Profil ist vorausgewählt, **Enter** oder ein Doppelklick starten sofort.
|
||||
- Der Aufrufparameter `--profile=<Name>` überspringt die Auswahl und startet direkt das genannte Profil. Erlaubt sind die Profil-ID und der angezeigte Name, Groß- und Kleinschreibung spielen keine Rolle. Ein unbekannter Name führt zu einem Hinweis und danach zur normalen Auswahl — der Start wird nie verweigert.
|
||||
|
||||
### Profil im laufenden Betrieb wechseln
|
||||
|
||||
**File → Switch operator profile...** oder die Schaltfläche im Reiter **Profiles** wechseln ohne Programmneustart. Nach einer Sicherheitsabfrage wird die ON4KST-Verbindung getrennt und die Oberfläche mit den Einstellungen und dem Layout des gewählten Profils neu aufgebaut. Der Layoutstand des bisherigen Profils wird vorher gesichert; noch nicht mit **Save Settings** bestätigte fachliche Änderungen gehen dabei verloren.
|
||||
|
||||
Sobald mehr als ein Profil existiert, zeigt die Titelzeile des Hauptfensters zusätzlich den Profilnamen.
|
||||
|
||||
### Hinweis zu Passwörtern
|
||||
|
||||
Das ON4KST-Passwort steht wie bisher im Klartext in der `preferences.xml` des jeweiligen Profils. Auf einem gemeinsam genutzten Rechner kann jeder, der Zugriff auf das Benutzerkonto hat, die Passwörter aller Profile lesen. Profile trennen die Konfiguration, sie sind **kein** Zugriffsschutz.
|
||||
|
||||
---
|
||||
|
||||
## Dark Mode (ab v1.26)
|
||||
|
||||
Der Dark Mode wird über **Windows → Use dark mode design** aktiviert. Mit **Windows → Use default mode design** wird wieder das normale helle Farbschema geladen.
|
||||
|
||||
@@ -102,6 +102,24 @@ Die Band-IDs für 50 und 70 MHz werden ebenso verarbeitet wie die VHF-, UHF- und
|
||||
|
||||
Die Daten werden in derselben internen Datenbank abgelegt wie Worked-Informationen aus den übrigen QSO-UDP-Schnittstellen und nach einem Neustart wiederhergestellt.
|
||||
|
||||
#### Bereits geloggte QSOs nachladen
|
||||
|
||||
Win-Test sendet jedes neue QSO als Broadcast. QSOs, die vor dem Start von KST4Contest geloggt wurden, sind darin nicht enthalten. KST4Contest fordert diese QSOs deshalb selbst an, sobald der Win-Test-Netzwerk-Listener eine Win-Test-Station im Netzwerk erkennt.
|
||||
|
||||
Der Abgleich benötigt keine eigene Einstellung und keinen Bedienschritt:
|
||||
|
||||
- Win-Test meldet mit `IHAVE`, welche QSO-Nummern welches Logs es führt.
|
||||
- KST4Contest fordert die fehlenden Bereiche mit `NEEDQSO` an, höchstens 50 QSOs pro Anfrage.
|
||||
- Win-Test beantwortet die Anfrage mit gewöhnlichen `ADDQSO`-Paketen. Sie werden genauso ausgewertet wie ein live geloggtes QSO.
|
||||
|
||||
Bereits gearbeitete Stationen erscheinen dadurch auch dann als gearbeitet, wenn KST4Contest erst während des Contests gestartet wird. Der Abgleich bleibt anschließend aktiv und holt auch einzelne Pakete nach, die im laufenden Betrieb verloren gegangen sind. Bereits bekannte QSOs werden erkannt und nicht erneut gespeichert.
|
||||
|
||||
Sind mehrere Win-Test-Stationen im Netzwerk aktiv, wird jedes Log abgeglichen. Damit sind die bandbezogenen Worked-Markierungen aller Bandstationen vollständig. Der Stationsnamensfilter wirkt weiterhin nur auf die QRG-Synchronisation und schränkt den Logabgleich nicht ein.
|
||||
|
||||
Meldet eine erkannte Station kein auswertbares `IHAVE`, etwa bei einer älteren Win-Test-Version, fordert KST4Contest die QSOs blockweise ab QSO-Nummer 1 an, bis ein Block unbeantwortet bleibt.
|
||||
|
||||
Voraussetzung ist ein aktiviertes Win-Test-Netzwerk. Ist das Win-Test-Netzwerk oder der Listener in KST4Contest deaktiviert, findet kein Abgleich statt.
|
||||
|
||||
#### Skeds an Win-Test übergeben
|
||||
|
||||
Mit **Create sked** wird zunächst ein interner KST4Contest-Sked angelegt. Ist der Win-Test-Netzwerk-Listener aktiviert, versucht KST4Contest anschließend automatisch, den Sked als `ADDSKED` an das Win-Test-Netzwerk zu übertragen.
|
||||
@@ -154,7 +172,11 @@ Im Reiter **TRX sync**:
|
||||
- `Use pass frequency from Win-Test STATUS`
|
||||
- `Win-Test station name filter`
|
||||
|
||||
Das Win-Test-Netzwerk muss in Win-Test aktiviert sein. Bei mehreren Computern muss die Broadcast-Adresse das betreffende lokale Netzwerk erreichen. Der Stationsname sollte die sendende KST4Contest-Instanz innerhalb des Win-Test-Netzwerks eindeutig erkennen lassen.
|
||||
Das Win-Test-Netzwerk muss in Win-Test aktiviert sein. Der Stationsname sollte die sendende KST4Contest-Instanz innerhalb des Win-Test-Netzwerks eindeutig erkennen lassen.
|
||||
|
||||
Die Broadcast-Adresse ermittelt KST4Contest selbst: Aus der Absenderadresse der empfangenen Win-Test-Pakete wird das passende lokale Netzwerk bestimmt und dessen Broadcast-Adresse verwendet. Die eingetragene Adresse dient als Rückfallebene, wenn kein lokales Netzwerk zur Win-Test-Station passt, etwa wenn Win-Test hinter einem Router liegt.
|
||||
|
||||
Das ist wichtig, weil Win-Test ausschließlich auf Broadcasts reagiert und eine Adresse in einem nicht vorhandenen Netzwerk keinen Fehler auslöst: Das Paket wird ohne Meldung weggeroutet. Eine veraltete Eintragung, etwa aus einem anderen Netzwerk, machte dadurch früher sowohl die Sked-Übergabe als auch den Logabgleich wirkungslos.
|
||||
|
||||
Ausführliche Beschreibung der Einstellungen: [Win-Test-Netzwerk-Listener](de-Konfiguration#win-test-netzwerk-listener-ab-v131)
|
||||
|
||||
|
||||
+103
-12
@@ -8,6 +8,107 @@ Published Stable versions and their application packages are available under [Gi
|
||||
|
||||
---
|
||||
|
||||
## v1.50 (in development)
|
||||
|
||||
**Operator profiles**
|
||||
|
||||
Several operators sharing one computer can now use their own callsigns, locators and layouts without overwriting each other's configuration. This implements [Issue #57](https://github.com/praktimarc/kst4contest/issues/57).
|
||||
|
||||
### New
|
||||
|
||||
- **Operator profiles:** every profile has its own `preferences.xml`, and therefore its own settings and its own window layout. Profiles are managed on the new **Profiles** tab of the settings window: create, duplicate, rename, delete and activate.
|
||||
|
||||
- **Shared or own worked stations:** each profile decides whether it gets its own worked database or uses the common station database. A multi operator station with a single station log shares the worked state; two operators with different callsigns on one computer keep it apart.
|
||||
|
||||
- **Choosing a profile at startup:** with only one profile, KST4Contest asks nothing at startup and behaves exactly as before. From two profiles on, a small selection appears with the last used profile preselected; Enter or a double click start immediately. The `--profile=<name>` argument skips the selection.
|
||||
|
||||
- **Switching profiles while running:** **File > Switch operator profile...** closes the connection and rebuilds the user interface with the settings of the selected profile, without restarting the program.
|
||||
|
||||
### Changed
|
||||
|
||||
- **The terrain profile cache is separate:** computed terrain profiles now live in their own shared file `terrainprofilecache.db` and are stored per owner. Previously the whole cache was dropped whenever the callsign or locator changed, which would have discarded every computed profile on each profile switch.
|
||||
|
||||
- **The default login callsign is empty:** if `preferences.xml` has no login callsign, the field now stays empty instead of falling back to a callsign compiled into the program. A newly created profile therefore deliberately starts without credentials.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Background resources are released:** the ON4KST supervisor thread, the sked reminder scheduler, the reachability executor, the PSTRotator retry scheduler and the map tile proxy are released when the chat controller is closed. They used to keep running until the program ended.
|
||||
|
||||
### Upgrade notes
|
||||
|
||||
- Existing installations are **not** modified: `preferences.xml` and `praktiKST.db` stay exactly where they are and become the **Default** profile. No file is moved or copied.
|
||||
- A profile registry only appears when the second profile is created. Anyone using a single profile will not notice the change.
|
||||
- Going back to an older KST4Contest release stays possible; it finds its files unchanged.
|
||||
- Passwords are still stored in clear text in each profile's `preferences.xml`. Profiles separate configuration; they are not an access control mechanism.
|
||||
|
||||
---
|
||||
|
||||
## v1.43.1 (2026-09-03)
|
||||
|
||||
**Corrected version metadata**
|
||||
|
||||
v1.43.1 contains the same functional changes as v1.43.0. It corrects the application and build metadata used for display, ON4KST identification and update comparison. Some metadata in the first v1.43.0 package set still identified the build as version 1.42.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Consistent semantic version:** The user-visible application version now uses the complete `1.43.1` form. The compact value `1.431` remains only in the deprecated numeric field required for compatibility with older update feeds.
|
||||
|
||||
- **Tagged-release update feed:** The website build, version-feed validation and artifact upload now run as actual workflow steps after the GitHub Release has been published. They were previously indented into the release action's artifact list and therefore skipped.
|
||||
|
||||
Users of v1.43.0 should install v1.43.1. The functionality is unchanged; the update only corrects the version metadata and release workflow.
|
||||
|
||||
The corrected version is available as [Release v1.43.1](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.1).
|
||||
|
||||
---
|
||||
|
||||
## v1.43.0 (2026-09-03)
|
||||
|
||||
**More reliable log synchronisation, persistent layouts and better DX Cluster compatibility**
|
||||
|
||||
v1.43 concentrates on reliability around external log data and long-running contest operation. It also adds practical control over table layouts and station grouping on the map.
|
||||
|
||||
### Added
|
||||
|
||||
- **Optional map clustering:** **Group nearby stations** immediately enables or disables spatial grouping at lower zoom levels. The stored setting changes neither the viewport nor the selected station; aggregation of active variants sharing one base callsign remains independent. This implements [Issue #79](https://github.com/praktimarc/kst4contest/issues/79).
|
||||
|
||||
- **Automatic table-layout persistence:** Tables receive useful widths when their first meaningful contents arrive. Manually changed column widths, window sizes and relevant dividers are written to `preferences.xml` after a short delay. The main and monitor windows keep separate DXCluster and QSO-of-the-other layouts.
|
||||
|
||||
- **Tooltips for truncated table values:** Normal table cells expose their complete text when the visible column is too narrow, without replacing functional tooltips or clickable links.
|
||||
|
||||
- **Simplelogfile creation notice:** When the selected file does not exist, KST4Contest creates it and displays a notice with the file path, a concrete test procedure and a link to the relevant manual section.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Robust Simplelogfile evaluation:** The selected file is evaluated once per minute and closed after every pass so that the logging application can replace or rotate it. Detected callsigns apply the global Worked state to every active suffix variant of the base callsign. Disabling the function prevents any file access, while read or creation errors no longer terminate the periodic task.
|
||||
|
||||
- **Consistent external logger bands:** UCXLog-compatible packets and Win-Test events use one shared band normalisation. Numeric values, metre and centimetre designators and the existing Win-Test IDs now set the same Worked flags and worked grid squares. Values including `2320`, `5760` and `10368` are handled reliably; a missing or unknown band sets only the global Worked state.
|
||||
|
||||
- **Compact full-frequency recognition:** Complete frequencies without a decimal separator are accepted across the supported bands, with the final three digits interpreted as the kHz part. Bare three-digit numbers still require recognisable frequency context so that signal reports and unrelated numbers are not treated as QRGs.
|
||||
|
||||
- **DXSpider-compatible spot format:** Local DX Cluster spots use a fixed 75-character payload line with the DX callsign in column 27, a 30-character comment field and UTC time in column 71. The format remains stable up to 24 GHz. Overlong DX callsigns are rejected and logged instead of being silently truncated. This resolves [Issue #86](https://github.com/praktimarc/kst4contest/issues/86).
|
||||
|
||||
- **Active ON4KST connection probe:** A quiet chat server is checked with an explicit session-wide probe before the connection is treated as dead. Heartbeats and probe frames retain the required CR/LF framing.
|
||||
|
||||
- **Reliable private-message age highlighting:** Incoming private messages use the defined green age levels for up to five minutes. Locally sent messages retain their separate style, and empty or reused table rows return to the normal design instead of keeping an obsolete highlight.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Worked state after login:** Persisted SQLite Worked information is loaded and applied before each initial ON4KST user list is published. Reconnects, both categories and all active variants of a base callsign therefore start with the correct state. This resolves [Issue #85](https://github.com/praktimarc/kst4contest/issues/85).
|
||||
|
||||
- **False disconnect during quiet periods:** A valid ON4KST connection is no longer closed merely because the server currently has no activity lines to send.
|
||||
|
||||
### Documentation and packaging
|
||||
|
||||
- The German and English manuals were revised against the implementation. A new contest-workflow chapter connects the individual functions into a practical operating sequence, while the sections on dual chat, private-message handling, QRG synchronisation, Simplelogfile evaluation and configuration were clarified.
|
||||
|
||||
- The website feature pages now describe band and direction opportunities, the station map, QRG handling, filters, global message views, private-message handling and logger synchronisation in more detail.
|
||||
|
||||
- The AUR package definitions were updated for v1.43.0.
|
||||
|
||||
The complete v1.43.0 functionality is available in [Release v1.43.0](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.0). Because its embedded version metadata is inconsistent, v1.43.1 is the recommended package set.
|
||||
|
||||
---
|
||||
|
||||
## v1.42.0 (2026-08-22)
|
||||
|
||||
**Shared band context, session-based ON4KST connection and signed macOS packages**
|
||||
@@ -38,21 +139,17 @@ v1.42 brings several previously separate calculations together. Band information
|
||||
|
||||
- **Filter reset:** A dedicated reset button reliably removes the active user-list filter predicates.
|
||||
|
||||
- **Optional map clustering:** **Group nearby stations** immediately enables or disables spatial grouping at lower zoom levels. The automatically stored setting changes neither the viewport nor the selected station; aggregation of active variants sharing one base callsign remains independent. This implements [Issue #79](https://github.com/praktimarc/kst4contest/issues/79).
|
||||
- **Map clustering:** Stations close to each other are grouped at lower zoom levels. The selected station and relevant direction opportunities remain individually visible.
|
||||
|
||||
- **Hideable path analysis:** The terrain profile and analysis section of the station map can be hidden completely. The selected state is stored and restored at the next application start.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Automatic table-layout persistence:** Tables receive useful widths when their first meaningful contents arrive. Manually changed column widths, window sizes and relevant dividers are written to `preferences.xml` after a short delay; the main and monitor windows keep separate DXCluster and QSO-of-the-other layouts. Truncated normal cell values expose their full text in a tooltip without replacing functional tooltips or clickable links.
|
||||
|
||||
- **Unified DX Cluster line format:** Local spots now use a fixed, DXSpider-compatible 75-character payload line with the DX callsign in column 27, a 30-character comment field and UTC time in column 71. The layout remains stable for microwave frequencies up to 24 GHz. Overlong DX callsigns are rejected and logged instead of being silently truncated; AirScout and test comments are correspondingly more compact.
|
||||
|
||||
- **Session-based ON4KST connection lifecycle:** Each socket, reader, writer, message bus and queue now belongs to an explicitly identified connection session. Delayed threads from an obsolete connection can therefore no longer process data or close its replacement. `ONLINE` is reported only after the login has been accepted and all requested user lists have been received. Connection setup, login and synchronisation use bounded timeouts, while heartbeats, missing inbound traffic, EOF and read or write failures trigger controlled reconnect attempts with backoff where appropriate.
|
||||
|
||||
- **Validated ON4KST protocol commands:** Outgoing frames are built centrally and checked for valid categories, locators and prohibited frame delimiters. Because ON4KST maintains one locator per TCP session, the main locator is used for both chat categories and a conflicting secondary configuration is logged instead of sending contradictory commands to the server.
|
||||
|
||||
- **More precise QRG recognition:** Complete frequencies are also recognised without a decimal separator, with the final three digits interpreted as the kHz part. Relative frequencies remain unchanged, and bare three-digit numbers still require recognisable frequency context. Signal reports, band designators and unrelated numbers therefore produce fewer false frequencies.
|
||||
- **More precise QRG recognition:** Complete and relative frequency references continue to be recognised. Bare three-digit numbers are treated as QRGs only when a frequency context is available. Signal reports, band designators and unrelated numbers therefore produce fewer false frequencies.
|
||||
|
||||
- **Station-specific frequency context:** For relative QRGs, KST4Contest first uses a band context for the same station which is no more than 30 minutes old. The globally configured fallback band is used only when this context is unavailable.
|
||||
|
||||
@@ -86,10 +183,6 @@ v1.42 brings several previously separate calculations together. Band information
|
||||
|
||||
- **DXLog full-log import:** In addition to `contactinfo`, the UCXLog-compatible UDP listener processes `contactreplace`. This allows a complete log broadcast by DXLog.net to be imported.
|
||||
|
||||
- **Consistent logger band values:** Numeric, metre and centimetre values from UCXLog-compatible QSO packets and Win-Test band IDs are normalised once and then used consistently for Worked marks and worked grid squares. In particular, `2320`, `5760` and `10368` now reliably set their existing band marks. A missing or unknown band continues to set only the global Worked status.
|
||||
|
||||
- **Defined Simplelogfile behaviour:** The selected text file is evaluated once per minute using a fixed callsign pattern. Matches set the global Worked status for all active variants of the base callsign but are not persisted in SQLite. A missing file is created, and read or creation errors do not terminate the periodic task. A database reset does not change the file, so callsigns contained in it are marked as worked again during the next evaluation.
|
||||
|
||||
- **Guarded automatic QRG updates:** `MYQRG` is updated only by an enabled interface which actually supplies valid `RadioInfo` or Win-Test `STATUS` packets. An enabled source which provides no data does not remove the need for a functional check or manual QRG maintenance.
|
||||
|
||||
- **Improved version comparison:** Versions are compared semantically so that patch releases and Nightly versions are not misclassified by conversion to a floating-point number.
|
||||
@@ -98,8 +191,6 @@ v1.42 brings several previously separate calculations together. Band information
|
||||
|
||||
- **Reliable initial user list:** Invalid or incomplete `UA0` member records are rejected and logged individually without preventing alphabetically following members from being processed. Valid entries are staged per category and published as one complete snapshot when the first corresponding `UE` end marker is received.
|
||||
|
||||
- **Persisted Worked state during initial-list setup:** At the end of each initial ON4KST user list, the SQLite state is loaded once and applied to the new chat members before publication. This covers both categories, reconnects and every active variant of a base callsign.
|
||||
|
||||
- **User list disappearing after login:** ON4KST may send additional `UE` frames for the same category after name, state or other live updates. Repeated end markers are now detected and ignored so that an already populated user list cannot be replaced by an empty snapshot.
|
||||
|
||||
- **Failed initial connection and lost sockets:** An unavailable server during startup no longer sends KST4Contest into an endless or busy-wait loop. The user interface remains responsive and further attempts use bounded reconnect backoff. Sockets closed by the server, or connections without inbound traffic for an excessive period, are also detected reliably.
|
||||
|
||||
@@ -935,6 +935,61 @@ Display and derivation: [Worked Callsigns, New Bands and New Grid Squares](en-Fe
|
||||
|
||||
---
|
||||
|
||||
## Operator Profiles (from v1.50)
|
||||
|
||||
Several operators sharing one computer need different callsigns, locators and layouts. An operator profile bundles exactly that: **every profile has its own `preferences.xml`, and therefore its own settings and its own window layout.**
|
||||
|
||||
### Where the profiles live
|
||||
|
||||
| Profile | Settings | Worked stations |
|
||||
|---|---|---|
|
||||
| **Default** | `~/.praktiKST/preferences.xml` | `~/.praktiKST/praktiKST.db` |
|
||||
| additional profiles | `~/.praktiKST/profiles/<profile ID>/preferences.xml` | shared, or `~/.praktiKST/profiles/<profile ID>/praktiKST.db` |
|
||||
|
||||
On Windows the same files live below `%USERPROFILE%\.praktiKST\`.
|
||||
|
||||
Everything else stays shared: audio files, colour schemes, DEM and terrain packages, the terrain profile cache (`terrainprofilecache.db`), the error log and the version information.
|
||||
|
||||
The **Default** profile keeps using exactly the files an existing installation already has. **Upgrading to v1.50 moves, copies and rewrites nothing.** Anyone reinstalling an older KST4Contest release finds their configuration and their worked stations unchanged.
|
||||
|
||||
### Shared or own worked stations
|
||||
|
||||
When a profile is created you decide where its worked, NOT-QRV and grid data come from:
|
||||
|
||||
- **Own worked stations** (default): the profile gets its own, initially empty database. This is what two operators with different callsigns sharing a private computer want.
|
||||
- **Common station database**: the profile uses `~/.praktiKST/praktiKST.db`, the same database as the **Default** profile. This is the **multi operator station** case: there is only one station log, so the worked state should be the same for every operator.
|
||||
|
||||
Switching between the two settings moves no data. Worked data already collected stays where it was created. The three day expiry and the reset button always act on the database of the currently active profile.
|
||||
|
||||
### Managing profiles
|
||||
|
||||
The **Profiles** tab in the settings window lists all profiles with their name, the kind of worked data they use and when they were last used.
|
||||
|
||||
- **New profile...** creates a profile. It starts **without callsign and password**; both are entered afterwards on the **Station** tab.
|
||||
- **Duplicate...** copies the complete configuration of the selected profile - antenna, locator, layout, beacon, integrations - **except callsign and password**. Worked stations are never copied.
|
||||
- **Rename...** changes the displayed name only. Folders and files are untouched.
|
||||
- **Delete...** removes the profile folder permanently. The **Default** profile and the currently active profile cannot be deleted. For a profile using the common station database, that database is left untouched.
|
||||
- **Change worked stations...** switches between the common and an own database.
|
||||
- **Switch to selected profile...** changes the profile while the application is running.
|
||||
|
||||
### Choosing a profile at startup
|
||||
|
||||
- As long as only **one** profile exists, KST4Contest asks **nothing** at startup and starts exactly as before. No profile registry is created either; only creating the second profile writes `~/.praktiKST/profiles.xml`.
|
||||
- From **two** profiles on, a small selection appears at startup. The last used profile is preselected, and **Enter** or a double click start immediately.
|
||||
- The `--profile=<name>` argument skips the selection and starts the named profile directly. Both the profile ID and the displayed name are accepted, case insensitively. An unknown name produces a note and then the normal selection - startup is never refused.
|
||||
|
||||
### Switching profiles while running
|
||||
|
||||
**File > Switch operator profile...**, or the button on the **Profiles** tab, switches without restarting the program. After a confirmation the ON4KST connection is closed and the user interface is rebuilt with the settings and layout of the selected profile. The layout of the previous profile is saved first; settings not yet confirmed with **Save Settings** are lost.
|
||||
|
||||
Once more than one profile exists, the main window title also shows the profile name.
|
||||
|
||||
### A note about passwords
|
||||
|
||||
As before, the ON4KST password is stored in clear text in the `preferences.xml` of each profile. On a shared computer, anyone with access to the user account can read the passwords of all profiles. Profiles separate configuration; they are **not** an access control mechanism.
|
||||
|
||||
---
|
||||
|
||||
## Dark Mode (from v1.26)
|
||||
|
||||
Enable Dark Mode through **Windows → Use dark mode design**. Use **Windows → Use default mode design** to restore the normal light colour scheme.
|
||||
|
||||
@@ -240,6 +240,24 @@ First check which frequencies were detected for the station during the previous
|
||||
|
||||
If no current station context exists, check **Fallback band for relative QRG detection**. The fallback is used only when the band cannot be determined from a complete frequency or the sender's current context.
|
||||
|
||||
### The Logger Runs in Its Own Sandbox
|
||||
|
||||
A logging programme started as a Flatpak, or through a Wine environment such as Bottles, uses the network permissions of that sandbox. If the sandbox does not share the host network, `127.0.0.1` inside it is not the `127.0.0.1` on which KST4Contest is listening, and the connection is refused even though KST4Contest reports the port correctly.
|
||||
|
||||
For a Flatpak logger, check its permission with:
|
||||
|
||||
```bash
|
||||
flatpak info --show-permissions <application id>
|
||||
```
|
||||
|
||||
The `[Context]` section has to contain `shared=network`. It can be granted with:
|
||||
|
||||
```bash
|
||||
flatpak override --user --share=network <application id>
|
||||
```
|
||||
|
||||
The same applies when KST4Contest itself runs as a Flatpak. Its published manifest already contains `--share=network`, so a listening port is reachable from the host and from other applications on the same computer.
|
||||
|
||||
### The Logger Hides the Spot
|
||||
|
||||
Try a spotter callsign which differs from the contest callsign. Depending on the logger, spots from the local callsign may be filtered or handled specially. KST4Contest itself does not require the two callsigns to differ.
|
||||
|
||||
@@ -102,6 +102,24 @@ Band IDs for 50 and 70 MHz are processed in the same way as the VHF, UHF and SHF
|
||||
|
||||
The information is written to the same internal database as Worked data received through the other QSO UDP interfaces and is restored after a restart.
|
||||
|
||||
#### Recovering QSOs logged earlier
|
||||
|
||||
Win-Test broadcasts every new QSO. QSOs logged before KST4Contest was started are not part of those broadcasts. KST4Contest therefore requests them itself as soon as the Win-Test network listener detects a Win-Test station on the network.
|
||||
|
||||
The recovery needs no dedicated setting and no operating step:
|
||||
|
||||
- Win-Test announces with `IHAVE` which QSO numbers of which log it holds.
|
||||
- KST4Contest requests the missing ranges with `NEEDQSO`, at most 50 QSOs per request.
|
||||
- Win-Test answers with ordinary `ADDQSO` packets. They are processed exactly like a QSO logged live.
|
||||
|
||||
Stations already worked therefore appear as worked even when KST4Contest is started during the contest. The recovery stays active afterwards and also picks up individual packets lost during operation. Known QSOs are recognised and not stored again.
|
||||
|
||||
When several Win-Test stations are active on the network, every log is recovered. The per-band Worked marks of all band stations are then complete. The station name filter still applies to the QRG synchronisation only and does not restrict the log recovery.
|
||||
|
||||
If a detected station sends no usable `IHAVE`, for example an older Win-Test version, KST4Contest requests the QSOs in blocks starting at QSO number 1 until a block remains unanswered.
|
||||
|
||||
The Win-Test network must be enabled. No recovery takes place while the Win-Test network or the listener in KST4Contest is disabled.
|
||||
|
||||
#### Handing skeds over to Win-Test
|
||||
|
||||
Pressing **Create sked** first creates an internal KST4Contest sked. If the Win-Test network listener is enabled, KST4Contest then automatically attempts to send the sked to the Win-Test network as an `ADDSKED` packet.
|
||||
@@ -154,7 +172,11 @@ In the **TRX sync** tab:
|
||||
- `Use pass frequency from Win-Test STATUS`
|
||||
- `Win-Test station name filter`
|
||||
|
||||
The Win-Test network must be enabled in Win-Test. When several computers are used, the broadcast address must reach the relevant local network. The station name should identify the sending KST4Contest instance unambiguously within the Win-Test network.
|
||||
The Win-Test network must be enabled in Win-Test. The station name should identify the sending KST4Contest instance unambiguously within the Win-Test network.
|
||||
|
||||
KST4Contest determines the broadcast address itself: the source address of the received Win-Test packets identifies the matching local network, and the broadcast address of that network is used. The configured address serves as the fallback when no local network matches the Win-Test station, for example when Win-Test is located behind a router.
|
||||
|
||||
This matters because Win-Test only reacts to broadcasts, and an address in a network that does not exist raises no error: the packet is routed away silently. An outdated entry, for instance from a different network, therefore used to disable both the sked handover and the log recovery.
|
||||
|
||||
Detailed settings: [Win-Test Network Listener](en-Configuration#win-test-network-listener-from-v131)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
pkgbase = kst4contest-bin
|
||||
pkgdesc = ON4KST Chat Client for VHF/UHF contest operation (pre-built)
|
||||
pkgver = 1.42.0
|
||||
pkgver = 1.44.0
|
||||
pkgrel = 1
|
||||
url = https://github.com/praktimarc/kst4contest
|
||||
arch = x86_64
|
||||
@@ -10,7 +10,7 @@ pkgbase = kst4contest-bin
|
||||
provides = kst4contest
|
||||
conflicts = kst4contest
|
||||
conflicts = kst4contest-git
|
||||
source = KST4Contest-v1.42.0-archlinux-x86_64.pkg.tar.zst::https://github.com/praktimarc/kst4contest/releases/download/v1.42.0/KST4Contest-v1.42.0-archlinux-x86_64.pkg.tar.zst
|
||||
sha256sums = 3d8ac19c9f9d3ab0bdaf0ea621de0aa18c64f442c8776d28bfad607522aaf02b
|
||||
source = KST4Contest-v1.44.0-archlinux-x86_64.pkg.tar.zst::https://github.com/praktimarc/kst4contest/releases/download/v1.44.0/KST4Contest-v1.44.0-archlinux-x86_64.pkg.tar.zst
|
||||
sha256sums = 62688fabc25be32ebe71588eb90f0334cfb7ddde14ba1be6df9956ff4415ddf0
|
||||
|
||||
pkgname = kst4contest-bin
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Philipp Wagner <philipp@wagnersnetz.de>
|
||||
pkgname=kst4contest-bin
|
||||
pkgver=1.42.0
|
||||
pkgver=1.44.0
|
||||
pkgrel=1
|
||||
pkgdesc="ON4KST Chat Client for VHF/UHF contest operation (pre-built)"
|
||||
arch=('x86_64')
|
||||
@@ -10,7 +10,7 @@ depends=('gst-plugins-base' 'gst-plugins-good')
|
||||
provides=('kst4contest')
|
||||
conflicts=('kst4contest' 'kst4contest-git')
|
||||
source=("KST4Contest-v${pkgver}-archlinux-${CARCH}.pkg.tar.zst::https://github.com/praktimarc/kst4contest/releases/download/v${pkgver}/KST4Contest-v${pkgver}-archlinux-${CARCH}.pkg.tar.zst")
|
||||
sha256sums=('3d8ac19c9f9d3ab0bdaf0ea621de0aa18c64f442c8776d28bfad607522aaf02b')
|
||||
sha256sums=('62688fabc25be32ebe71588eb90f0334cfb7ddde14ba1be6df9956ff4415ddf0')
|
||||
|
||||
package() {
|
||||
cp -a "${srcdir}/usr" "${pkgdir}/"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
pkgbase = kst4contest-git
|
||||
pkgdesc = ON4KST Chat Client for VHF/UHF contest operation (git)
|
||||
pkgver = 1.42.0.r256.g8aadbb9
|
||||
pkgver = 1.44.0.r299.g08d65a0e
|
||||
pkgrel = 1
|
||||
url = https://github.com/praktimarc/kst4contest
|
||||
arch = x86_64
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Philipp Wagner <philipp@wagnersnetz.de>
|
||||
pkgname=kst4contest-git
|
||||
pkgver=1.42.0.r256.g8aadbb9
|
||||
pkgver=1.44.0.r299.g08d65a0e
|
||||
pkgrel=1
|
||||
pkgdesc="ON4KST Chat Client for VHF/UHF contest operation (git)"
|
||||
arch=('x86_64')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
pkgbase = kst4contest
|
||||
pkgdesc = ON4KST Chat Client for VHF/UHF contest operation
|
||||
pkgver = 1.42.0
|
||||
pkgver = 1.44.0
|
||||
pkgrel = 1
|
||||
url = https://github.com/praktimarc/kst4contest
|
||||
arch = x86_64
|
||||
@@ -12,7 +12,7 @@ pkgbase = kst4contest
|
||||
provides = kst4contest
|
||||
conflicts = kst4contest-bin
|
||||
conflicts = kst4contest-git
|
||||
source = kst4contest-1.42.0.tar.gz::https://github.com/praktimarc/kst4contest/archive/refs/tags/v1.42.0.tar.gz
|
||||
sha256sums = bd396387b8de41aac706458d5ebf64140ab3e83b8a7c710b66aa802bd48e804e
|
||||
source = kst4contest-1.44.0.tar.gz::https://github.com/praktimarc/kst4contest/archive/refs/tags/v1.44.0.tar.gz
|
||||
sha256sums = e702df24a29e6f914a43934df0095bc4adbd00a9f02df3a632816c832272e914
|
||||
|
||||
pkgname = kst4contest
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Maintainer: Philipp Wagner <philipp@wagnersnetz.de>
|
||||
pkgname=kst4contest
|
||||
pkgver=1.42.0
|
||||
pkgver=1.44.0
|
||||
pkgrel=1
|
||||
pkgdesc="ON4KST Chat Client for VHF/UHF contest operation"
|
||||
arch=('x86_64')
|
||||
@@ -11,7 +11,7 @@ makedepends=('java-environment=21' 'maven')
|
||||
provides=('kst4contest')
|
||||
conflicts=('kst4contest-bin' 'kst4contest-git')
|
||||
source=("${pkgname}-${pkgver}.tar.gz::https://github.com/praktimarc/kst4contest/archive/refs/tags/v${pkgver}.tar.gz")
|
||||
sha256sums=('bd396387b8de41aac706458d5ebf64140ab3e83b8a7c710b66aa802bd48e804e')
|
||||
sha256sums=('e702df24a29e6f914a43934df0095bc4adbd00a9f02df3a632816c832272e914')
|
||||
|
||||
build() {
|
||||
cd "${srcdir}/kst4contest-${pkgver}"
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
<groupId>de.x08</groupId>
|
||||
<artifactId>praktiKST</artifactId>
|
||||
<version>1.42.0-nightly</version>
|
||||
<version>1.50.0-nightly</version>
|
||||
|
||||
<name>praktiKST</name>
|
||||
|
||||
|
||||
@@ -20,14 +20,14 @@ public class ApplicationConstants {
|
||||
/**
|
||||
* Version shown to the user and used for semantic version comparison.
|
||||
*/
|
||||
public static final String APPLICATION_CURRENT_VERSION = "1.43";
|
||||
public static final String APPLICATION_CURRENT_VERSION = "1.50.0";
|
||||
|
||||
/**
|
||||
* Legacy numeric representation used only while older update feeds and
|
||||
* application versions still exist.
|
||||
*/
|
||||
@Deprecated
|
||||
public static final double APPLICATION_CURRENTVERSIONNUMBER = 1.42;
|
||||
public static final double APPLICATION_CURRENTVERSIONNUMBER = 1.50;
|
||||
|
||||
public static final String VERSIONINFOURLFORUPDATES_KST4CONTEST = "https://kst4contest.hamradioonline.de/kst4ContestVersionInfo.xml";
|
||||
public static final String VERSIONINFDOWNLOADEDLOCALFILE = "kst4ContestVersionInfo.xml";
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
|
||||
/**
|
||||
* Holds the operator profile the current runtime works with.
|
||||
*
|
||||
* <p>The state is deliberately static, which is safe here for reasons that did not apply
|
||||
* to the former static database connection: the value is immutable, it holds no live
|
||||
* resource, and it is set on the JavaFX Application Thread before anything reads it -
|
||||
* during startup, and again during a profile switch after the previous runtime has been
|
||||
* shut down completely.</p>
|
||||
*/
|
||||
public final class ActiveOperatorProfile {
|
||||
|
||||
private static volatile OperatorProfileSelection currentSelection;
|
||||
|
||||
private ActiveOperatorProfile() {
|
||||
// Utility class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the active profile selection.
|
||||
*
|
||||
* @return the active selection, or null when startup has not resolved one yet
|
||||
*/
|
||||
public static OperatorProfileSelection get() {
|
||||
return currentSelection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the active profile selection.
|
||||
*
|
||||
* @param selection selection to activate
|
||||
*/
|
||||
public static void set(final OperatorProfileSelection selection) {
|
||||
currentSelection = selection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a profile has already been resolved for this runtime.
|
||||
*
|
||||
* @return true if a selection is present
|
||||
*/
|
||||
public static boolean isInitialized() {
|
||||
return currentSelection != null;
|
||||
}
|
||||
}
|
||||
@@ -1083,9 +1083,35 @@ public class ChatController implements ThreadStatusCallback, PstRotatorEventList
|
||||
rotatorClient.stop();
|
||||
rotatorClient = null;
|
||||
}
|
||||
|
||||
releaseBackgroundExecutors();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the background executors that live as long as this controller.
|
||||
*
|
||||
* <p>These are not bound to one ON4KST session, so disconnecting leaves them running
|
||||
* on purpose. When the controller itself is discarded they have to go, otherwise a
|
||||
* discarded controller stays reachable through its own threads.</p>
|
||||
*/
|
||||
private void releaseBackgroundExecutors() {
|
||||
|
||||
on4KstConnectionManager.shutdown();
|
||||
skedReminderService.shutdown();
|
||||
|
||||
if (reachabilityService != null) {
|
||||
reachabilityService.shutdown();
|
||||
}
|
||||
|
||||
if (pendingRotatorRetry != null) {
|
||||
pendingRotatorRetry.cancel(false);
|
||||
pendingRotatorRetry = null;
|
||||
}
|
||||
|
||||
rotatorCommandScheduler.shutdownNow();
|
||||
}
|
||||
|
||||
private void cancelTimer(Timer timer) {
|
||||
if (timer != null) {
|
||||
timer.cancel();
|
||||
@@ -1204,10 +1230,11 @@ public class ChatController implements ThreadStatusCallback, PstRotatorEventList
|
||||
return;
|
||||
}
|
||||
|
||||
InetAddress broadcastAddress = InetAddress.getByName(
|
||||
chatPreferences
|
||||
.getLogsynch_wintestNetworkBroadcastAddress()
|
||||
);
|
||||
InetAddress broadcastAddress =
|
||||
winTestAddressResolver.resolveBroadcastAddress(
|
||||
chatPreferences
|
||||
.getLogsynch_wintestNetworkBroadcastAddress()
|
||||
);
|
||||
|
||||
int port =
|
||||
chatPreferences.getLogsynch_wintestNetworkPort();
|
||||
@@ -1642,11 +1669,26 @@ public class ChatController implements ThreadStatusCallback, PstRotatorEventList
|
||||
// private String hostname = "109.90.0.130";
|
||||
private String hostname;
|
||||
// private String praktiKSTVersion = "praktiKST 1.0";
|
||||
private String praktiKSTVersionInfo = "2022-10 - 2022-12\ndeveloped by DO5AMF, Marc\nContact: praktimarc@gmail.com\nDonations via paypal are welcome";
|
||||
private String praktiKSTVersionInfo = "2022-10 - 2022-12\ndeveloped by DO5AMF, Marc and DN9APW, Philipp Wagner\nContact: praktimarc@gmail.com\nDonations via paypal are welcome";
|
||||
|
||||
private int port = 23001; // kst4contest.test 4 23001 //TODO: auslagern in Chatprefs
|
||||
private ReadUDPbyUCXMessageThread readUDPbyUCXThread;
|
||||
private ReadUDPByWintestThread readUDPByWintestThread;
|
||||
|
||||
/**
|
||||
* Shared resolver for the Win-Test broadcast address. Win-Test only reacts
|
||||
* to broadcasts, so both the log synchronization and the SKED handover have
|
||||
* to reach the network the station was actually heard on.
|
||||
*/
|
||||
private final WinTestNetworkAddressResolver winTestAddressResolver =
|
||||
new WinTestNetworkAddressResolver();
|
||||
|
||||
/**
|
||||
* @return resolver for outgoing Win-Test packets
|
||||
*/
|
||||
public WinTestNetworkAddressResolver getWinTestAddressResolver() {
|
||||
return winTestAddressResolver;
|
||||
}
|
||||
private WriteThread writeThread;
|
||||
private ReadThread readThread;
|
||||
private InputReaderThread consoleReader;
|
||||
@@ -2850,9 +2892,35 @@ private ObservableList<String>
|
||||
* @param setOwnChatMemberObject
|
||||
*/
|
||||
public ChatController(ChatMember setOwnChatMemberObject,StatusUpdateListener listener) {
|
||||
this(setOwnChatMemberObject,
|
||||
listener,
|
||||
ChatPreferences.PREFERENCES_FILE,
|
||||
DBController.DATABASE_FILE,
|
||||
true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a chat controller bound to the files of one operator profile.
|
||||
*
|
||||
* <p>Both file names are resolved below the application directory. This is the only
|
||||
* place where the active operator profile enters the controller; everything below
|
||||
* works on the resulting {@link ChatPreferences} and {@link DBController} instances
|
||||
* without knowing about profiles at all.</p>
|
||||
*
|
||||
* @param setOwnChatMemberObject chat member object representing the local station
|
||||
* @param listener callback for thread status updates
|
||||
* @param preferencesRelativeFileName preferences file name relative to the application directory
|
||||
* @param workedDatabaseRelativeFileName worked-station database file name relative to the application directory
|
||||
* @param seedWorkedDatabaseFromResource true to seed a missing database from the bundled template
|
||||
*/
|
||||
public ChatController(ChatMember setOwnChatMemberObject,
|
||||
StatusUpdateListener listener,
|
||||
String preferencesRelativeFileName,
|
||||
String workedDatabaseRelativeFileName,
|
||||
boolean seedWorkedDatabaseFromResource) {
|
||||
super();
|
||||
|
||||
chatPreferences = new ChatPreferences();
|
||||
chatPreferences = new ChatPreferences(preferencesRelativeFileName);
|
||||
chatPreferences.readPreferencesFromXmlFile();
|
||||
// this.statusListener = listener;
|
||||
lstNotify_QSOSniffer_sniffedCallSignList =
|
||||
@@ -2914,7 +2982,7 @@ private ObservableList<String>
|
||||
}
|
||||
});
|
||||
|
||||
dbHandler = new DBController();
|
||||
dbHandler = new DBController(workedDatabaseRelativeFileName, seedWorkedDatabaseFromResource);
|
||||
reachabilityService = new ReachabilityService(this);
|
||||
rebuildWorkedGrossFieldCacheFromDatabase();
|
||||
|
||||
|
||||
@@ -6,9 +6,13 @@ import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import kst4contest.ApplicationConstants;
|
||||
import kst4contest.model.ChatMember;
|
||||
@@ -52,34 +56,128 @@ public class DBController {
|
||||
*/
|
||||
private static final long EXPIRATION_CLEANUP_MIN_INTERVAL_IN_MILLISECONDS = 60L * 1000L;
|
||||
|
||||
private static final DBController dbcontroller = new DBController();
|
||||
private static Connection connection;
|
||||
private static String DB_PATH = ApplicationFileUtils.getFilePath(ApplicationConstants.APPLICATION_NAME, DATABASE_FILE);
|
||||
/**
|
||||
* Lazily created controller for the root installation database. It is created on
|
||||
* first use only, because an eagerly created instance would open a database file
|
||||
* before the application knows which operator profile is active.
|
||||
*/
|
||||
private static volatile DBController defaultInstance;
|
||||
|
||||
private Connection connection;
|
||||
|
||||
/**
|
||||
* File name of this database relative to the application directory, for example
|
||||
* "praktiKST.db" or "profiles/OP2/praktiKST.db".
|
||||
*/
|
||||
private final String databaseRelativeFileName;
|
||||
|
||||
/**
|
||||
* Absolute path of the database file, resolved once during construction.
|
||||
*/
|
||||
private final String databaseFilePath;
|
||||
|
||||
/**
|
||||
* True if a missing database file should be seeded from the shipped template.
|
||||
*/
|
||||
private final boolean seedFromResource;
|
||||
|
||||
/**
|
||||
* Shutdown hook of this instance. It is remembered so it can be deregistered when
|
||||
* the connection is closed. Without that, every operator profile switch would leave
|
||||
* another hook behind that keeps a dead connection alive until the process ends.
|
||||
*/
|
||||
private Thread databaseShutdownHook;
|
||||
|
||||
/**
|
||||
* Remembers the last timestamp at which the expiration cleanup had been executed.
|
||||
*/
|
||||
private long lastExpirationCleanupExecutionEpochMs = 0L;
|
||||
|
||||
/**
|
||||
* Creates a controller for the worked-station database of the root installation.
|
||||
*/
|
||||
public DBController() {
|
||||
initDBConnection();
|
||||
}
|
||||
|
||||
public static DBController getInstance() {
|
||||
return dbcontroller;
|
||||
this(DATABASE_FILE, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the database connection if it is still open.
|
||||
* Creates a controller for the worked-station database of one operator profile.
|
||||
*
|
||||
* @param databaseRelativeFileName file name relative to the application directory
|
||||
* @param seedFromResource true to copy the shipped template database when the file
|
||||
* does not exist yet, false to create an empty database and
|
||||
* let the schema creation build all required tables
|
||||
*/
|
||||
public DBController(final String databaseRelativeFileName, final boolean seedFromResource) {
|
||||
this.databaseRelativeFileName =
|
||||
Objects.requireNonNull(databaseRelativeFileName, "databaseRelativeFileName");
|
||||
this.seedFromResource = seedFromResource;
|
||||
this.databaseFilePath = ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
databaseRelativeFileName
|
||||
);
|
||||
|
||||
initDBConnection();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a controller for the root installation database, creating it on first use.
|
||||
*
|
||||
* @return the shared controller for the root installation database
|
||||
*/
|
||||
public static synchronized DBController getInstance() {
|
||||
|
||||
if (defaultInstance == null) {
|
||||
defaultInstance = new DBController();
|
||||
}
|
||||
|
||||
return defaultInstance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute path of the database file this controller works on.
|
||||
*
|
||||
* @return absolute database file path
|
||||
*/
|
||||
public String getDatabaseFilePath() {
|
||||
return databaseFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the database connection if it is still open and deregisters the shutdown
|
||||
* hook of this instance.
|
||||
*/
|
||||
public synchronized void closeDBConnection() {
|
||||
|
||||
closeConnectionQuietly();
|
||||
|
||||
if (databaseShutdownHook != null) {
|
||||
try {
|
||||
Runtime.getRuntime().removeShutdownHook(databaseShutdownHook);
|
||||
} catch (IllegalStateException shutdownAlreadyInProgress) {
|
||||
// Expected while the JVM is shutting down; the hook is running anyway.
|
||||
}
|
||||
|
||||
databaseShutdownHook = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the connection without touching the shutdown hook. This is also the body of
|
||||
* the shutdown hook itself.
|
||||
*/
|
||||
private synchronized void closeConnectionQuietly() {
|
||||
|
||||
try {
|
||||
if (connection != null && !connection.isClosed()) {
|
||||
connection.close();
|
||||
System.out.println("Connection to Database closed: " + databaseFilePath);
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
connection = null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,22 +189,17 @@ public class DBController {
|
||||
System.out.println("DBH: initiate new db connection");
|
||||
|
||||
try {
|
||||
ApplicationFileUtils.copyResourceIfRequired(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
DATABASE_RESOURCE,
|
||||
DATABASE_FILE
|
||||
);
|
||||
|
||||
if (connection != null && !connection.isClosed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
prepareDatabaseFile();
|
||||
|
||||
System.out.println("Creating Connection to Database...");
|
||||
|
||||
DB_PATH = ApplicationFileUtils.getFilePath(ApplicationConstants.APPLICATION_NAME, DATABASE_FILE);
|
||||
connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
|
||||
connection = DriverManager.getConnection("jdbc:sqlite:" + databaseFilePath);
|
||||
|
||||
System.out.println("[DBH, Info]: Path = " + DB_PATH);
|
||||
System.out.println("[DBH, Info]: Path = " + databaseFilePath);
|
||||
|
||||
if (!connection.isClosed()) {
|
||||
System.out.println("...Connection established");
|
||||
@@ -115,25 +208,50 @@ public class DBController {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
Runtime.getRuntime().addShutdownHook(new Thread() {
|
||||
public void run() {
|
||||
try {
|
||||
if (connection != null && !connection.isClosed()) {
|
||||
connection.close();
|
||||
|
||||
if (connection.isClosed()) {
|
||||
System.out.println("Connection to Database closed");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
});
|
||||
databaseShutdownHook = new Thread(this::closeConnectionQuietly,
|
||||
"DBController-shutdown-" + databaseRelativeFileName);
|
||||
Runtime.getRuntime().addShutdownHook(databaseShutdownHook);
|
||||
|
||||
ensureChatMemberTableCompatibility();
|
||||
}
|
||||
|
||||
/**
|
||||
* Makes sure the database file can be opened.
|
||||
*
|
||||
* <p>The database of the root installation is seeded from the shipped template so
|
||||
* existing installations keep their historic content. A database that belongs to an
|
||||
* additional operator profile is created empty on purpose: the shipped template
|
||||
* carries several thousand foreign callsigns and an outdated schema version, which
|
||||
* would present a new operator with foreign data and trigger the full callsign
|
||||
* normalization rebuild. The required tables are created by
|
||||
* {@link #ensureChatMemberTableCompatibility()} in both cases.</p>
|
||||
*/
|
||||
private synchronized void prepareDatabaseFile() {
|
||||
|
||||
if (seedFromResource) {
|
||||
ApplicationFileUtils.copyResourceIfRequired(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
DATABASE_RESOURCE,
|
||||
databaseRelativeFileName
|
||||
);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
Path parentDirectory = Path.of(databaseFilePath).getParent();
|
||||
|
||||
if (parentDirectory == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Files.createDirectories(parentDirectory);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(
|
||||
"[DBH, ERROR:] Could not create database directory " + parentDirectory, e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures that the ChatMember table exists, that all required columns are
|
||||
* available for newer software versions, that existing old callsign keys are
|
||||
|
||||
@@ -139,6 +139,20 @@ final class On4KstConnectionManager {
|
||||
scheduler.execute(() -> openConnection(token));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the supervisor thread of this manager for good.
|
||||
*
|
||||
* <p>{@link #stopByUser()} only ends the current ON4KST session; the periodic
|
||||
* session monitor keeps running. That is correct while the application lives, but a
|
||||
* manager belonging to a discarded runtime must release its thread, otherwise every
|
||||
* operator profile switch would leave another supervisor behind holding the dead
|
||||
* controller.</p>
|
||||
*/
|
||||
void shutdown() {
|
||||
scheduler.shutdownNow();
|
||||
LOGGER.fine("ON4KST connection supervisor shut down");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the current session and invalidates every scheduled callback or reconnect
|
||||
* belonging to it.
|
||||
|
||||
@@ -0,0 +1,312 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.ApplicationConstants;
|
||||
import kst4contest.model.ChatPreferences;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.utils.ApplicationFileUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Creates, renames, duplicates and removes operator profiles.
|
||||
*
|
||||
* <p>Kept free of user interface code so the behaviour can be tested without a JavaFX
|
||||
* runtime. All methods work on the registry and on the files below the application
|
||||
* directory.</p>
|
||||
*/
|
||||
public class OperatorProfileManagementService {
|
||||
|
||||
private static final Logger LOGGER =
|
||||
Logger.getLogger(OperatorProfileManagementService.class.getName());
|
||||
|
||||
private final OperatorProfileStore profileStore;
|
||||
|
||||
public OperatorProfileManagementService() {
|
||||
this(new OperatorProfileStore());
|
||||
}
|
||||
|
||||
public OperatorProfileManagementService(final OperatorProfileStore profileStore) {
|
||||
this.profileStore = profileStore;
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists all profiles, including the implicit root profile of a plain installation.
|
||||
*
|
||||
* @return the known profiles, never empty
|
||||
*/
|
||||
public List<OperatorProfile> listProfiles() {
|
||||
|
||||
List<OperatorProfile> knownProfiles = profileStore.loadProfiles();
|
||||
|
||||
if (knownProfiles.isEmpty()) {
|
||||
knownProfiles = new ArrayList<>();
|
||||
knownProfiles.add(profileStore.buildImplicitRootProfile());
|
||||
}
|
||||
|
||||
return knownProfiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new operator profile with its own preferences file.
|
||||
*
|
||||
* <p>Creating the first additional profile is also the moment the registry appears:
|
||||
* the root profile is written alongside, so both are selectable afterwards.</p>
|
||||
*
|
||||
* @param displayName name entered by the operator
|
||||
* @param sharedWorkedDatabase true to use the common station worked database
|
||||
* @return the created profile, or null when it could not be stored
|
||||
*/
|
||||
public OperatorProfile createProfile(final String displayName, final boolean sharedWorkedDatabase) {
|
||||
|
||||
List<OperatorProfile> knownProfiles = listProfiles();
|
||||
Set<String> takenProfileIds = new LinkedHashSet<>();
|
||||
|
||||
for (OperatorProfile existingProfile : knownProfiles) {
|
||||
takenProfileIds.add(existingProfile.getProfileId());
|
||||
}
|
||||
|
||||
OperatorProfile createdProfile = new OperatorProfile(
|
||||
OperatorProfilePaths.toProfileId(displayName, takenProfileIds),
|
||||
displayName == null || displayName.isBlank() ? "New profile" : displayName.trim(),
|
||||
false,
|
||||
sharedWorkedDatabase);
|
||||
|
||||
knownProfiles.add(createdProfile);
|
||||
|
||||
if (!profileStore.saveProfiles(knownProfiles, createdProfile.getProfileId())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
createPreferencesFile(createdProfile, null);
|
||||
|
||||
return createdProfile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a copy of an existing profile.
|
||||
*
|
||||
* <p>The preferences are taken over completely except for the login credentials:
|
||||
* callsign and password are cleared on purpose, because a duplicate is meant for
|
||||
* another operator. Antenna, locator, layout and integration settings are exactly
|
||||
* what the operator does not want to enter twice.</p>
|
||||
*
|
||||
* <p>The worked-station database is never copied.</p>
|
||||
*
|
||||
* @param sourceProfile profile to copy
|
||||
* @param displayName name of the new profile
|
||||
* @return the created profile, or null when it could not be stored
|
||||
*/
|
||||
public OperatorProfile duplicateProfile(final OperatorProfile sourceProfile, final String displayName) {
|
||||
|
||||
if (sourceProfile == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<OperatorProfile> knownProfiles = listProfiles();
|
||||
Set<String> takenProfileIds = new LinkedHashSet<>();
|
||||
|
||||
for (OperatorProfile existingProfile : knownProfiles) {
|
||||
takenProfileIds.add(existingProfile.getProfileId());
|
||||
}
|
||||
|
||||
OperatorProfile createdProfile = new OperatorProfile(
|
||||
OperatorProfilePaths.toProfileId(displayName, takenProfileIds),
|
||||
displayName == null || displayName.isBlank() ? "Copy" : displayName.trim(),
|
||||
false,
|
||||
sourceProfile.isSharedWorkedDatabase());
|
||||
|
||||
knownProfiles.add(createdProfile);
|
||||
|
||||
if (!profileStore.saveProfiles(knownProfiles, createdProfile.getProfileId())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
createPreferencesFile(createdProfile, sourceProfile);
|
||||
|
||||
return createdProfile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the visible name of a profile. The identifier and all paths stay as they are.
|
||||
*
|
||||
* @param profile profile to rename
|
||||
* @param newDisplayName new name
|
||||
* @return true if the registry was updated
|
||||
*/
|
||||
public boolean renameProfile(final OperatorProfile profile, final String newDisplayName) {
|
||||
|
||||
if (profile == null || newDisplayName == null || newDisplayName.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<OperatorProfile> knownProfiles = listProfiles();
|
||||
|
||||
for (OperatorProfile currentProfile : knownProfiles) {
|
||||
if (currentProfile.getProfileId().equals(profile.getProfileId())) {
|
||||
currentProfile.setDisplayName(newDisplayName.trim());
|
||||
}
|
||||
}
|
||||
|
||||
return profileStore.saveProfiles(knownProfiles, profileStore.loadLastUsedProfileId().orElse(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Switches a profile between the common station database and its own one.
|
||||
*
|
||||
* @param profile profile to change
|
||||
* @param sharedWorkedDatabase true to use the common station worked database
|
||||
* @return true if the registry was updated
|
||||
*/
|
||||
public boolean setSharedWorkedDatabase(final OperatorProfile profile, final boolean sharedWorkedDatabase) {
|
||||
|
||||
if (profile == null || profile.isRootProfile()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<OperatorProfile> knownProfiles = listProfiles();
|
||||
|
||||
for (OperatorProfile currentProfile : knownProfiles) {
|
||||
if (currentProfile.getProfileId().equals(profile.getProfileId())) {
|
||||
currentProfile.setSharedWorkedDatabase(sharedWorkedDatabase);
|
||||
}
|
||||
}
|
||||
|
||||
return profileStore.saveProfiles(knownProfiles, profileStore.loadLastUsedProfileId().orElse(null));
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a profile and its directory.
|
||||
*
|
||||
* <p>The root profile can never be removed, because its files are the installation
|
||||
* itself. A profile using the common station database keeps that database untouched;
|
||||
* only its own directory is deleted.</p>
|
||||
*
|
||||
* @param profile profile to remove
|
||||
* @return true if the profile was removed
|
||||
*/
|
||||
public boolean deleteProfile(final OperatorProfile profile) {
|
||||
|
||||
if (profile == null || profile.isRootProfile()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<OperatorProfile> remainingProfiles = new ArrayList<>();
|
||||
|
||||
for (OperatorProfile currentProfile : listProfiles()) {
|
||||
if (!currentProfile.getProfileId().equals(profile.getProfileId())) {
|
||||
remainingProfiles.add(currentProfile);
|
||||
}
|
||||
}
|
||||
|
||||
if (!profileStore.saveProfiles(remainingProfiles,
|
||||
profileStore.loadLastUsedProfileId().orElse(null))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
deleteProfileDirectory(profile);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute directory of a profile.
|
||||
*
|
||||
* @param profile profile to resolve
|
||||
* @return absolute profile directory
|
||||
*/
|
||||
public String getProfileDirectory(final OperatorProfile profile) {
|
||||
return ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
OperatorProfilePaths.profileRelativeDirectory(profile));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the preferences file of a new profile.
|
||||
*
|
||||
* <p>The file is either seeded from the bundled template or copied from the source
|
||||
* profile. In both cases the login credentials are cleared, so a new profile never
|
||||
* carries another operator's callsign or password.</p>
|
||||
*
|
||||
* @param createdProfile profile that needs a preferences file
|
||||
* @param sourceProfile profile to copy the preferences from, or null for the template
|
||||
*/
|
||||
private void createPreferencesFile(final OperatorProfile createdProfile,
|
||||
final OperatorProfile sourceProfile) {
|
||||
|
||||
String createdRelativeFileName = OperatorProfilePaths.preferencesRelativeFileName(createdProfile);
|
||||
|
||||
if (sourceProfile != null) {
|
||||
copyPreferencesFile(
|
||||
OperatorProfilePaths.preferencesRelativeFileName(sourceProfile),
|
||||
createdRelativeFileName);
|
||||
}
|
||||
|
||||
// Seeds from the bundled template when nothing was copied, and always resolves
|
||||
// the preferences of the new profile.
|
||||
ChatPreferences createdPreferences = new ChatPreferences(createdRelativeFileName);
|
||||
createdPreferences.readPreferencesFromXmlFile();
|
||||
|
||||
createdPreferences.setStn_loginCallSign("");
|
||||
createdPreferences.setStn_loginPassword("");
|
||||
|
||||
createdPreferences.writePreferencesToXmlFile();
|
||||
}
|
||||
|
||||
private void copyPreferencesFile(final String sourceRelativeFileName,
|
||||
final String targetRelativeFileName) {
|
||||
|
||||
Path sourcePath = Path.of(ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME, sourceRelativeFileName));
|
||||
Path targetPath = Path.of(ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME, targetRelativeFileName));
|
||||
|
||||
if (!Files.isRegularFile(sourcePath)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
Path targetDirectory = targetPath.getParent();
|
||||
|
||||
if (targetDirectory != null) {
|
||||
Files.createDirectories(targetDirectory);
|
||||
}
|
||||
|
||||
Files.copy(sourcePath, targetPath);
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Could not copy the preferences of the source profile, using the defaults instead", e);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteProfileDirectory(final OperatorProfile profile) {
|
||||
|
||||
Path profileDirectory = Path.of(getProfileDirectory(profile));
|
||||
|
||||
if (!Files.isDirectory(profileDirectory)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try (Stream<Path> containedPaths = Files.walk(profileDirectory)) {
|
||||
List<Path> deepestFirst = containedPaths
|
||||
.sorted(Comparator.reverseOrder())
|
||||
.toList();
|
||||
|
||||
for (Path currentPath : deepestFirst) {
|
||||
Files.deleteIfExists(currentPath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Could not remove the directory of the deleted operator profile", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.ChatPreferences;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Locale;
|
||||
|
||||
/**
|
||||
* Derives the file names of an operator profile.
|
||||
*
|
||||
* <p>This is the single place that knows how a profile maps onto files. The registry
|
||||
* stores only the shared/own flag, never a path, so the two can never drift apart.</p>
|
||||
*/
|
||||
public final class OperatorProfilePaths {
|
||||
|
||||
/**
|
||||
* Directory below the application directory that holds the additional profiles.
|
||||
*/
|
||||
public static final String PROFILES_DIRECTORY = "profiles";
|
||||
|
||||
/**
|
||||
* Identifier of the profile that uses the historic flat installation layout.
|
||||
*/
|
||||
public static final String ROOT_PROFILE_ID = "default";
|
||||
|
||||
/**
|
||||
* Maximum length of a generated profile identifier.
|
||||
*/
|
||||
private static final int MAX_PROFILE_ID_LENGTH = 32;
|
||||
|
||||
private OperatorProfilePaths() {
|
||||
// Utility class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the profile descriptor of the historic flat installation.
|
||||
*
|
||||
* @param displayName name to show for the root profile
|
||||
* @return the root profile descriptor
|
||||
*/
|
||||
public static OperatorProfile buildRootProfile(final String displayName) {
|
||||
return new OperatorProfile(ROOT_PROFILE_ID, displayName, true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the profile directory relative to the application directory.
|
||||
*
|
||||
* @param profile profile to resolve
|
||||
* @return relative directory name
|
||||
*/
|
||||
public static String profileRelativeDirectory(final OperatorProfile profile) {
|
||||
return PROFILES_DIRECTORY + "/" + profile.getProfileId();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the preferences file name relative to the application directory.
|
||||
*
|
||||
* @param profile profile to resolve
|
||||
* @return relative preferences file name
|
||||
*/
|
||||
public static String preferencesRelativeFileName(final OperatorProfile profile) {
|
||||
|
||||
if (profile.isRootProfile()) {
|
||||
return ChatPreferences.PREFERENCES_FILE;
|
||||
}
|
||||
|
||||
return profileRelativeDirectory(profile) + "/" + ChatPreferences.PREFERENCES_FILE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the worked-station database file name relative to the application directory.
|
||||
*
|
||||
* <p>A profile using the common station database always resolves to the historic flat
|
||||
* file, which is what a multi operator station wants: the existing contest state stays
|
||||
* the shared one.</p>
|
||||
*
|
||||
* @param profile profile to resolve
|
||||
* @return relative database file name
|
||||
*/
|
||||
public static String workedDatabaseRelativeFileName(final OperatorProfile profile) {
|
||||
|
||||
if (profile.isRootProfile() || profile.isSharedWorkedDatabase()) {
|
||||
return DBController.DATABASE_FILE;
|
||||
}
|
||||
|
||||
return profileRelativeDirectory(profile) + "/" + DBController.DATABASE_FILE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves a profile descriptor into the runtime selection used during startup.
|
||||
*
|
||||
* @param profile profile to resolve
|
||||
* @return resolved selection
|
||||
*/
|
||||
public static OperatorProfileSelection resolve(final OperatorProfile profile) {
|
||||
|
||||
boolean usesSharedStationDatabase = profile.isRootProfile() || profile.isSharedWorkedDatabase();
|
||||
|
||||
return new OperatorProfileSelection(
|
||||
profile,
|
||||
preferencesRelativeFileName(profile),
|
||||
workedDatabaseRelativeFileName(profile),
|
||||
usesSharedStationDatabase
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derives a stable, file system safe identifier from a display name.
|
||||
*
|
||||
* <p>The identifier becomes a directory name and is never changed afterwards, so a
|
||||
* later rename of the profile does not move any file.</p>
|
||||
*
|
||||
* @param displayName name entered by the operator
|
||||
* @param takenProfileIds identifiers that are already in use
|
||||
* @return an identifier that is not yet taken
|
||||
*/
|
||||
public static String toProfileId(final String displayName, final Collection<String> takenProfileIds) {
|
||||
|
||||
StringBuilder sanitized = new StringBuilder();
|
||||
|
||||
if (displayName != null) {
|
||||
String foldedDisplayName = foldGermanUmlauts(displayName.toUpperCase(Locale.ROOT));
|
||||
|
||||
for (char currentCharacter : foldedDisplayName.toCharArray()) {
|
||||
boolean isAcceptable = (currentCharacter >= 'A' && currentCharacter <= 'Z')
|
||||
|| (currentCharacter >= '0' && currentCharacter <= '9')
|
||||
|| currentCharacter == '-';
|
||||
|
||||
if (isAcceptable) {
|
||||
sanitized.append(currentCharacter);
|
||||
} else if (sanitized.length() > 0 && sanitized.charAt(sanitized.length() - 1) != '_') {
|
||||
sanitized.append('_');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
while (sanitized.length() > 0 && sanitized.charAt(sanitized.length() - 1) == '_') {
|
||||
sanitized.setLength(sanitized.length() - 1);
|
||||
}
|
||||
|
||||
if (sanitized.length() > MAX_PROFILE_ID_LENGTH) {
|
||||
sanitized.setLength(MAX_PROFILE_ID_LENGTH);
|
||||
}
|
||||
|
||||
String candidate = sanitized.toString();
|
||||
|
||||
if (candidate.isEmpty() || ROOT_PROFILE_ID.equalsIgnoreCase(candidate)) {
|
||||
candidate = "OP";
|
||||
}
|
||||
|
||||
if (!isProfileIdTaken(candidate, takenProfileIds)) {
|
||||
return candidate;
|
||||
}
|
||||
|
||||
int suffix = 2;
|
||||
|
||||
while (isProfileIdTaken(candidate + "_" + suffix, takenProfileIds)) {
|
||||
suffix++;
|
||||
}
|
||||
|
||||
return candidate + "_" + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds German umlauts so a name like "Muller" written with an umlaut still produces a
|
||||
* readable identifier instead of a placeholder character.
|
||||
*
|
||||
* @param upperCaseText already upper-cased text
|
||||
* @return text with umlauts replaced by their base letters
|
||||
*/
|
||||
private static String foldGermanUmlauts(final String upperCaseText) {
|
||||
return upperCaseText
|
||||
.replace("\u00C4", "A")
|
||||
.replace("\u00D6", "O")
|
||||
.replace("\u00DC", "U")
|
||||
.replace("\u00DF", "SS");
|
||||
}
|
||||
|
||||
private static boolean isProfileIdTaken(final String candidate, final Collection<String> takenProfileIds) {
|
||||
|
||||
if (ROOT_PROFILE_ID.equalsIgnoreCase(candidate)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (takenProfileIds == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String takenProfileId : takenProfileIds) {
|
||||
if (candidate.equalsIgnoreCase(takenProfileId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.ApplicationConstants;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.utils.ApplicationFileUtils;
|
||||
|
||||
import org.w3c.dom.Document;
|
||||
import org.w3c.dom.Element;
|
||||
import org.w3c.dom.Node;
|
||||
import org.w3c.dom.NodeList;
|
||||
|
||||
import javax.xml.XMLConstants;
|
||||
import javax.xml.parsers.DocumentBuilder;
|
||||
import javax.xml.parsers.DocumentBuilderFactory;
|
||||
import javax.xml.transform.OutputKeys;
|
||||
import javax.xml.transform.Transformer;
|
||||
import javax.xml.transform.TransformerFactory;
|
||||
import javax.xml.transform.dom.DOMSource;
|
||||
import javax.xml.transform.stream.StreamResult;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.AtomicMoveNotSupportedException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Reads and writes the operator profile registry.
|
||||
*
|
||||
* <p>The registry file is created lazily. As long as an installation has only the
|
||||
* historic flat layout, no registry exists and none is written, so a single operator
|
||||
* installation behaves exactly as before. The file appears when the second profile is
|
||||
* created; at that moment the root profile is materialised as well.</p>
|
||||
*
|
||||
* <p>A missing, unreadable or malformed registry is never fatal. It is logged and
|
||||
* treated like an installation without additional profiles.</p>
|
||||
*/
|
||||
public class OperatorProfileStore {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(OperatorProfileStore.class.getName());
|
||||
|
||||
/**
|
||||
* Name of the registry file inside the application directory.
|
||||
*/
|
||||
public static final String PROFILES_REGISTRY_FILE = "profiles.xml";
|
||||
|
||||
private static final String TAG_ROOT = "praktiKSTProfiles";
|
||||
private static final String TAG_REGISTRY_VERSION = "registryVersion";
|
||||
private static final String TAG_LAST_USED_PROFILE_ID = "lastUsedProfileId";
|
||||
private static final String TAG_PROFILE = "profile";
|
||||
private static final String TAG_PROFILE_ID = "profileId";
|
||||
private static final String TAG_DISPLAY_NAME = "displayName";
|
||||
private static final String TAG_ROOT_PROFILE = "rootProfile";
|
||||
private static final String TAG_SHARED_WORKED_DATABASE = "sharedWorkedDatabase";
|
||||
private static final String TAG_LAST_USED_EPOCH_MS = "lastUsedEpochMs";
|
||||
|
||||
private static final int REGISTRY_VERSION = 1;
|
||||
|
||||
private final String registryFilePath;
|
||||
|
||||
/**
|
||||
* Creates a store working on the registry of the current installation.
|
||||
*/
|
||||
public OperatorProfileStore() {
|
||||
this(ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME, PROFILES_REGISTRY_FILE));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a store working on an explicit registry file.
|
||||
*
|
||||
* @param registryFilePath absolute path of the registry file
|
||||
*/
|
||||
public OperatorProfileStore(final String registryFilePath) {
|
||||
this.registryFilePath = registryFilePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether a registry file exists at all.
|
||||
*
|
||||
* @return true if the installation already has more than the historic flat layout
|
||||
*/
|
||||
public boolean isRegistryPresent() {
|
||||
return new File(registryFilePath).isFile();
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the in-memory descriptor of the historic flat installation.
|
||||
*
|
||||
* <p>Nothing is written. This keeps a single operator installation untouched.</p>
|
||||
*
|
||||
* @return the implicit root profile
|
||||
*/
|
||||
public OperatorProfile buildImplicitRootProfile() {
|
||||
return OperatorProfilePaths.buildRootProfile("Default");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads all stored profiles.
|
||||
*
|
||||
* @return the stored profiles, or an empty list when no usable registry exists
|
||||
*/
|
||||
public List<OperatorProfile> loadProfiles() {
|
||||
|
||||
List<OperatorProfile> loadedProfiles = new ArrayList<>();
|
||||
Document document = readRegistryDocument();
|
||||
|
||||
if (document == null) {
|
||||
return loadedProfiles;
|
||||
}
|
||||
|
||||
NodeList profileNodes = document.getElementsByTagName(TAG_PROFILE);
|
||||
|
||||
for (int profileIndex = 0; profileIndex < profileNodes.getLength(); profileIndex++) {
|
||||
Node currentNode = profileNodes.item(profileIndex);
|
||||
|
||||
if (currentNode.getNodeType() != Node.ELEMENT_NODE) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Element profileElement = (Element) currentNode;
|
||||
String profileId = readText(profileElement, TAG_PROFILE_ID);
|
||||
|
||||
if (profileId == null || profileId.isBlank()) {
|
||||
LOGGER.log(Level.WARNING, "Skipping operator profile entry without an identifier");
|
||||
continue;
|
||||
}
|
||||
|
||||
OperatorProfile loadedProfile = new OperatorProfile();
|
||||
loadedProfile.setProfileId(profileId.trim());
|
||||
loadedProfile.setDisplayName(readText(profileElement, TAG_DISPLAY_NAME));
|
||||
loadedProfile.setRootProfile(readBoolean(profileElement, TAG_ROOT_PROFILE, false));
|
||||
loadedProfile.setSharedWorkedDatabase(
|
||||
readBoolean(profileElement, TAG_SHARED_WORKED_DATABASE, true));
|
||||
loadedProfile.setLastUsedEpochMs(readLong(profileElement, TAG_LAST_USED_EPOCH_MS));
|
||||
|
||||
if (loadedProfile.getDisplayName() == null || loadedProfile.getDisplayName().isBlank()) {
|
||||
loadedProfile.setDisplayName(loadedProfile.getProfileId());
|
||||
}
|
||||
|
||||
// The root profile always uses the common station database, because its
|
||||
// database is the historic flat file itself.
|
||||
if (loadedProfile.isRootProfile()) {
|
||||
loadedProfile.setSharedWorkedDatabase(true);
|
||||
}
|
||||
|
||||
loadedProfiles.add(loadedProfile);
|
||||
}
|
||||
|
||||
return loadedProfiles;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the identifier of the profile that was activated last.
|
||||
*
|
||||
* @return the identifier, or empty when unknown
|
||||
*/
|
||||
public Optional<String> loadLastUsedProfileId() {
|
||||
|
||||
Document document = readRegistryDocument();
|
||||
|
||||
if (document == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Element rootElement = document.getDocumentElement();
|
||||
|
||||
if (rootElement == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String lastUsedProfileId = readText(rootElement, TAG_LAST_USED_PROFILE_ID);
|
||||
|
||||
if (lastUsedProfileId == null || lastUsedProfileId.isBlank()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(lastUsedProfileId.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the complete registry.
|
||||
*
|
||||
* @param profiles profiles to store
|
||||
* @param lastUsedProfileId identifier of the profile that was activated last, may be null
|
||||
* @return true if the registry was written
|
||||
*/
|
||||
public boolean saveProfiles(final List<OperatorProfile> profiles, final String lastUsedProfileId) {
|
||||
|
||||
try {
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
|
||||
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
|
||||
Document document = documentBuilder.newDocument();
|
||||
|
||||
Element rootElement = document.createElement(TAG_ROOT);
|
||||
document.appendChild(rootElement);
|
||||
|
||||
appendTextElement(document, rootElement, TAG_REGISTRY_VERSION, String.valueOf(REGISTRY_VERSION));
|
||||
|
||||
if (lastUsedProfileId != null && !lastUsedProfileId.isBlank()) {
|
||||
appendTextElement(document, rootElement, TAG_LAST_USED_PROFILE_ID, lastUsedProfileId);
|
||||
}
|
||||
|
||||
for (OperatorProfile currentProfile : profiles) {
|
||||
Element profileElement = document.createElement(TAG_PROFILE);
|
||||
rootElement.appendChild(profileElement);
|
||||
|
||||
appendTextElement(document, profileElement, TAG_PROFILE_ID, currentProfile.getProfileId());
|
||||
appendTextElement(document, profileElement, TAG_DISPLAY_NAME, currentProfile.getDisplayName());
|
||||
appendTextElement(document, profileElement, TAG_ROOT_PROFILE,
|
||||
String.valueOf(currentProfile.isRootProfile()));
|
||||
appendTextElement(document, profileElement, TAG_SHARED_WORKED_DATABASE,
|
||||
String.valueOf(currentProfile.isRootProfile() || currentProfile.isSharedWorkedDatabase()));
|
||||
appendTextElement(document, profileElement, TAG_LAST_USED_EPOCH_MS,
|
||||
String.valueOf(currentProfile.getLastUsedEpochMs()));
|
||||
}
|
||||
|
||||
return writeDocumentAtomically(document);
|
||||
} catch (Exception e) {
|
||||
LOGGER.log(Level.SEVERE, "Could not write the operator profile registry", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that a profile has been activated.
|
||||
*
|
||||
* <p>Does nothing when no registry exists, so a single operator installation is not
|
||||
* turned into a multi profile installation by merely starting the application.</p>
|
||||
*
|
||||
* @param profileId identifier of the activated profile
|
||||
* @return true if the registry was updated
|
||||
*/
|
||||
public boolean recordLastUsed(final String profileId) {
|
||||
|
||||
if (!isRegistryPresent()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<OperatorProfile> storedProfiles = loadProfiles();
|
||||
|
||||
if (storedProfiles.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (OperatorProfile currentProfile : storedProfiles) {
|
||||
if (currentProfile.getProfileId().equalsIgnoreCase(profileId)) {
|
||||
currentProfile.setLastUsedEpochMs(System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
|
||||
return saveProfiles(storedProfiles, profileId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute path of the registry file.
|
||||
*
|
||||
* @return absolute registry path
|
||||
*/
|
||||
public String getRegistryFilePath() {
|
||||
return registryFilePath;
|
||||
}
|
||||
|
||||
private Document readRegistryDocument() {
|
||||
|
||||
File registryFile = new File(registryFilePath);
|
||||
|
||||
if (!registryFile.isFile()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
|
||||
documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
|
||||
|
||||
return documentBuilderFactory.newDocumentBuilder().parse(registryFile);
|
||||
} catch (Exception e) {
|
||||
LOGGER.log(Level.WARNING,
|
||||
"Could not read the operator profile registry, continuing without additional profiles", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static String readText(final Element parentElement, final String tagName) {
|
||||
|
||||
NodeList matchingNodes = parentElement.getElementsByTagName(tagName);
|
||||
|
||||
if (matchingNodes.getLength() == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return matchingNodes.item(0).getTextContent();
|
||||
}
|
||||
|
||||
private static boolean readBoolean(final Element parentElement,
|
||||
final String tagName,
|
||||
final boolean defaultValue) {
|
||||
|
||||
String rawValue = readText(parentElement, tagName);
|
||||
|
||||
if (rawValue == null || rawValue.isBlank()) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
return Boolean.parseBoolean(rawValue.trim());
|
||||
}
|
||||
|
||||
private static long readLong(final Element parentElement, final String tagName) {
|
||||
|
||||
String rawValue = readText(parentElement, tagName);
|
||||
|
||||
if (rawValue == null || rawValue.isBlank()) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
try {
|
||||
return Long.parseLong(rawValue.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
private static void appendTextElement(final Document document,
|
||||
final Element parentElement,
|
||||
final String tagName,
|
||||
final String textContent) {
|
||||
|
||||
Element createdElement = document.createElement(tagName);
|
||||
createdElement.setTextContent(textContent == null ? "" : textContent);
|
||||
parentElement.appendChild(createdElement);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the registry through a temporary file so a crash can never leave a
|
||||
* half-written registry behind. This mirrors the established preferences writer.
|
||||
*
|
||||
* @param document document to write
|
||||
* @return true if the registry file was replaced
|
||||
*/
|
||||
private boolean writeDocumentAtomically(final Document document) {
|
||||
|
||||
Path targetPath = Path.of(registryFilePath).toAbsolutePath();
|
||||
Path parentDirectory = targetPath.getParent();
|
||||
|
||||
if (parentDirectory == null) {
|
||||
LOGGER.log(Level.SEVERE,
|
||||
"The operator profile registry path has no directory: {0}", registryFilePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
Files.createDirectories(parentDirectory);
|
||||
|
||||
// The temporary file has to live next to the target so the final move can be
|
||||
// atomic; both must be on the same file system.
|
||||
Path temporaryPath = Files.createTempFile(
|
||||
parentDirectory, PROFILES_REGISTRY_FILE, ".tmp");
|
||||
|
||||
Transformer transformer = TransformerFactory.newInstance().newTransformer();
|
||||
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
|
||||
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
|
||||
|
||||
try (OutputStream outputStream = Files.newOutputStream(temporaryPath)) {
|
||||
transformer.transform(new DOMSource(document), new StreamResult(outputStream));
|
||||
}
|
||||
|
||||
try {
|
||||
Files.move(temporaryPath, targetPath,
|
||||
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
} catch (AtomicMoveNotSupportedException atomicMoveUnsupported) {
|
||||
Files.move(temporaryPath, targetPath, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
LOGGER.log(Level.SEVERE, "Could not store the operator profile registry", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,8 +13,9 @@ import java.net.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@@ -31,18 +32,40 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
|
||||
private static final int BUFFER_SIZE = 4096;
|
||||
|
||||
private final Map<Integer, String> receivedQsos = new ConcurrentHashMap<>();
|
||||
private long lastPacketTime = 0;
|
||||
|
||||
private String myStation = "DO5AMF";
|
||||
|
||||
private String targetStation = "";
|
||||
private String stationID = "";
|
||||
private int lastKnownQso = 0;
|
||||
|
||||
private ThreadStatusCallback callBackToController;
|
||||
private String ThreadNickName = "Wintest-msg";
|
||||
|
||||
/**
|
||||
* Number of fields of a complete ADDQSO packet, including message type,
|
||||
* source and destination.
|
||||
*/
|
||||
private static final int ADDQSO_FIELD_COUNT = 24;
|
||||
|
||||
/** Field position of the Win-Test QSO number inside an ADDQSO packet. */
|
||||
private static final int ADDQSO_QSO_NUMBER_INDEX = 11;
|
||||
|
||||
/** Field position of the logging station name inside an ADDQSO packet. */
|
||||
private static final int ADDQSO_STATION_NAME_INDEX = 3;
|
||||
|
||||
private final WinTestLogSyncService logSyncService;
|
||||
|
||||
private WinTestLogSyncService.SyncState lastReportedSyncState;
|
||||
|
||||
/**
|
||||
* Last IHAVE payload seen per station. Win-Test repeats the inventory
|
||||
* periodically, so tracing only the changes keeps the output readable.
|
||||
*/
|
||||
private final Map<String, String> lastTracedIhaveByStation = new HashMap<>();
|
||||
|
||||
private final WinTestNetworkAddressResolver addressResolver;
|
||||
|
||||
|
||||
public ReadUDPByWintestThread(ChatController client, ThreadStatusCallback callback) {
|
||||
|
||||
@@ -51,6 +74,21 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
this.myStation = client.getChatPreferences().getStn_loginCallSignRaw(); //callsign of the logging stn
|
||||
this.PORT = client.getChatPreferences().getLogsynch_wintestNetworkPort();
|
||||
|
||||
WinTestNetworkAddressResolver sharedAddressResolver =
|
||||
client.getWinTestAddressResolver();
|
||||
this.addressResolver = sharedAddressResolver != null
|
||||
? sharedAddressResolver
|
||||
: new WinTestNetworkAddressResolver();
|
||||
|
||||
/*
|
||||
* Preferences are read late on purpose: station name, port and broadcast
|
||||
* address can be changed while the listener is running.
|
||||
*/
|
||||
this.logSyncService = new WinTestLogSyncService(
|
||||
this::sendNeedQso,
|
||||
this::resolveOwnWinTestStationName
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -85,35 +123,113 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
|
||||
while (running) {
|
||||
try {
|
||||
/*
|
||||
* DatagramPacket keeps the length of the previous datagram, so
|
||||
* without resetting it a long packet would be truncated after a
|
||||
* short one. A truncated packet loses its trailing fields and
|
||||
* its checksum.
|
||||
*/
|
||||
packet.setLength(buffer.length);
|
||||
socket.receive(packet);
|
||||
String msg = new String(packet.getData(), 0, packet.getLength(), StandardCharsets.US_ASCII).trim();
|
||||
processWinTestMessage(msg);
|
||||
processWinTestDatagram(
|
||||
packet.getData(), packet.getLength(), packet.getAddress());
|
||||
} catch (SocketTimeoutException e) {
|
||||
// checkForMissingQsos();
|
||||
logSyncService.tick();
|
||||
reportSyncStateIfChanged();
|
||||
} catch (IOException e) {
|
||||
//TODO: here is something to catch
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the Win-Test framing of a received datagram and processes it.
|
||||
*
|
||||
* <p>The checksum byte and the NUL terminator are removed on the raw bytes
|
||||
* before any text parsing, so the trailing fields of the packet stay
|
||||
* readable. Afterwards the log synchronization gets its chance to request
|
||||
* QSOs that were logged before this listener was started.</p>
|
||||
*
|
||||
* @param datagram raw datagram buffer
|
||||
* @param length number of valid bytes in the buffer
|
||||
*/
|
||||
void processWinTestDatagram(byte[] datagram, int length, InetAddress source) {
|
||||
if (datagram == null || length <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
WinTestPacket packet = WinTestPacket.fromDatagram(datagram, length);
|
||||
|
||||
if (packet != null && isWinTestStationMessage(packet.getMessageType())) {
|
||||
/*
|
||||
* Win-Test only answers broadcasts. Remembering where its packets
|
||||
* come from keeps outgoing requests on the network the station
|
||||
* actually lives in, even when the configured broadcast address
|
||||
* belongs to a different or no longer existing network.
|
||||
*/
|
||||
addressResolver.rememberStationAddress(source);
|
||||
}
|
||||
|
||||
if (packet == null) {
|
||||
/*
|
||||
* The datagram does not follow the Win-Test framing. It still
|
||||
* reaches the established text handling, which also recognizes the
|
||||
* poison pill that stops this listener.
|
||||
*/
|
||||
processWinTestPacket(
|
||||
null,
|
||||
new String(datagram, 0, length, StandardCharsets.US_ASCII).trim()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
processWinTestPacket(packet, packet.getMessageText());
|
||||
|
||||
logSyncService.tick();
|
||||
reportSyncStateIfChanged();
|
||||
}
|
||||
|
||||
void processWinTestMessage(String msg) {
|
||||
processWinTestPacket(WinTestPacket.fromMessageText(msg), msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes one Win-Test message.
|
||||
*
|
||||
* @param packet parsed packet, or {@code null} when the message does not
|
||||
* follow the Win-Test framing
|
||||
* @param msg complete message text
|
||||
*/
|
||||
private void processWinTestPacket(WinTestPacket packet, String msg) {
|
||||
// System.out.println("Wintest-Message received: " + msg);
|
||||
|
||||
if (msg == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastPacketTime = System.currentTimeMillis();
|
||||
|
||||
if (msg.startsWith("HELLO:")) { //Client Signon of wintest
|
||||
parseHello(msg);
|
||||
try {
|
||||
// send_needqso();
|
||||
}catch (Exception e) {
|
||||
System.out.println("Error: ");
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (packet != null) {
|
||||
System.out.println("[WinTest RX] HELLO from " + packet.getSource());
|
||||
logSyncService.onStationSeen(packet.getSource());
|
||||
}
|
||||
|
||||
} else if (msg.startsWith("ADDQSO:")) { //adding qso to wintest log
|
||||
try {
|
||||
|
||||
if (packet != null && !packet.getDestination().isEmpty()) {
|
||||
/*
|
||||
* A directed ADDQSO is the answer to one of our NEEDQSO
|
||||
* requests. Tracing it separates a missing answer from a
|
||||
* failing evaluation of the answer.
|
||||
*/
|
||||
System.out.println("[WinTest RX] ADDQSO answer from "
|
||||
+ packet.getSource() + " to " + packet.getDestination());
|
||||
}
|
||||
|
||||
parseAddQso(msg);
|
||||
} catch (Exception e) {
|
||||
ThreadStateMessage threadStateMessage = new ThreadStateMessage(this.ThreadNickName, true, "Parsing ERROR: " + Arrays.toString(e.getStackTrace()), true);
|
||||
@@ -123,8 +239,19 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
} else if (msg.startsWith("STATUS")) {
|
||||
parseStatus(msg);
|
||||
|
||||
/*
|
||||
* HELLO is only sent when a log is opened, so a listener that was
|
||||
* started later learns about a station from its periodic STATUS.
|
||||
* The configured station-name filter stays a QRG-sync setting: in a
|
||||
* multi-station setup every band station keeps its own log, and all
|
||||
* of them contribute Worked state.
|
||||
*/
|
||||
if (packet != null) {
|
||||
logSyncService.onStationSeen(packet.getSource());
|
||||
}
|
||||
|
||||
} else if (msg.startsWith("IHAVE:")) { //periodical message of wintest, which qsos are in the log
|
||||
// parseIHave(msg); //TODO
|
||||
parseIHave(packet);
|
||||
}
|
||||
|
||||
else if (msg.contains(ApplicationConstants.DISCONNECT_RDR_POISONPILL)) {
|
||||
@@ -138,6 +265,130 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
callBackToController.onThreadStatus(ThreadNickName,threadStateMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands the periodic Win-Test log inventory to the log synchronization.
|
||||
*
|
||||
* <p>A packet with a broken checksum is discarded here. The run-length
|
||||
* inventory is the last field of an IHAVE packet, so a corrupted packet
|
||||
* would announce QSO ranges that do not exist. The established handling of
|
||||
* the other message types is deliberately left unchanged, because it never
|
||||
* verified the checksum.</p>
|
||||
*
|
||||
* @param packet received IHAVE packet
|
||||
*/
|
||||
private void parseIHave(WinTestPacket packet) {
|
||||
if (packet == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (packet.isChecksumPresent() && !packet.isChecksumValid()) {
|
||||
System.out.println("[WinTest] IHAVE with invalid checksum ignored");
|
||||
return;
|
||||
}
|
||||
|
||||
String tracedPayload = String.join(" ", packet.getDataTokens());
|
||||
if (!tracedPayload.equals(lastTracedIhaveByStation.put(packet.getSource(), tracedPayload))) {
|
||||
System.out.println("[WinTest RX] IHAVE from " + packet.getSource()
|
||||
+ " to '" + packet.getDestination() + "': " + tracedPayload
|
||||
+ (WinTestIhaveInventory.fromPacket(packet).isEmpty()
|
||||
? " <-- not usable as inventory" : ""));
|
||||
}
|
||||
|
||||
logSyncService.onIhaveReceived(packet);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports a change of the log-synchronization progress to the controller.
|
||||
*/
|
||||
private void reportSyncStateIfChanged() {
|
||||
WinTestLogSyncService.SyncState currentSyncState = logSyncService.getState();
|
||||
|
||||
if (currentSyncState == lastReportedSyncState) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastReportedSyncState = currentSyncState;
|
||||
|
||||
ThreadStateMessage threadStateMessage = new ThreadStateMessage(
|
||||
this.ThreadNickName, true, "log sync: " + currentSyncState, false);
|
||||
callBackToController.onThreadStatus(ThreadNickName, threadStateMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a NEEDQSO request as a UDP broadcast.
|
||||
*
|
||||
* <p>The framing follows the wtKST implementation exactly, including the
|
||||
* leading blank of the data part:</p>
|
||||
*
|
||||
* <pre>
|
||||
* NEEDQSO: "KST4Contest" "STN1" "STN1@44510" 1 50{checksum}\0
|
||||
* </pre>
|
||||
*
|
||||
* @param targetStation Win-Test station the request is addressed to
|
||||
* @param logId log identity in the form {@code StationName@LogUniqueID}
|
||||
* @param countFrom first requested QSO number
|
||||
* @param countTo last requested QSO number
|
||||
*/
|
||||
private void sendNeedQso(String targetStation, String logId, long countFrom, long countTo) {
|
||||
String data = " \"" + logId + "\" " + countFrom + " " + countTo;
|
||||
|
||||
WinTestMessage needQsoMessage = new WinTestMessage(
|
||||
WinTestMessage.MessageType.NEEDQSO,
|
||||
resolveOwnWinTestStationName(),
|
||||
targetStation,
|
||||
data
|
||||
);
|
||||
|
||||
try (DatagramSocket sendSocket = new DatagramSocket()) {
|
||||
sendSocket.setBroadcast(true);
|
||||
sendSocket.setReuseAddress(true);
|
||||
|
||||
byte[] messageBytes = needQsoMessage.toBytes();
|
||||
InetAddress broadcastAddress = addressResolver.resolveBroadcastAddress(
|
||||
client.getChatPreferences().getLogsynch_wintestNetworkBroadcastAddress());
|
||||
int targetPort = client.getChatPreferences().getLogsynch_wintestNetworkPort();
|
||||
|
||||
sendSocket.send(new DatagramPacket(
|
||||
messageBytes, messageBytes.length, broadcastAddress, targetPort));
|
||||
|
||||
System.out.println("[WinTest LogSync] NEEDQSO to " + targetStation
|
||||
+ " for " + logId + " " + countFrom + "-" + countTo);
|
||||
} catch (IOException | RuntimeException exception) {
|
||||
System.out.println("[WinTest LogSync] NEEDQSO could not be sent: "
|
||||
+ exception.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return own station name in the Win-Test network, never blank
|
||||
*/
|
||||
private String resolveOwnWinTestStationName() {
|
||||
String configuredStationName =
|
||||
client.getChatPreferences().getLogsynch_wintestNetworkStationNameOfKST();
|
||||
|
||||
if (configuredStationName == null || configuredStationName.isBlank()) {
|
||||
return "KST4Contest";
|
||||
}
|
||||
|
||||
return configuredStationName.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether a message type identifies a genuine Win-Test station.
|
||||
*
|
||||
* <p>Internal control messages such as the poison pill must not influence
|
||||
* the address of outgoing Win-Test packets.</p>
|
||||
*
|
||||
* @param messageType message type of a received packet
|
||||
* @return {@code true} for a Win-Test station message
|
||||
*/
|
||||
private static boolean isWinTestStationMessage(String messageType) {
|
||||
return "HELLO".equals(messageType)
|
||||
|| "STATUS".equals(messageType)
|
||||
|| "IHAVE".equals(messageType)
|
||||
|| "ADDQSO".equals(messageType);
|
||||
}
|
||||
|
||||
/**
|
||||
* parsing of the hello message of wintest:
|
||||
* "HELLO: "STN1" "" 6667 130 "SLAVE" 1 0 1762201985"
|
||||
@@ -346,15 +597,6 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
}
|
||||
}
|
||||
|
||||
// private void send_needqso() throws IOException {
|
||||
// String payload = String.format("NEEDQSO:\"%s\" \"%s\" \"%s\" %d %d?\0",
|
||||
// "DO5AMF", "STN1", stationID, 1, 9999);
|
||||
// InetAddress broadcast = InetAddress.getByName("255.255.255.255");
|
||||
// byte[] bytes = payload.getBytes(StandardCharsets.US_ASCII);
|
||||
// bytes[bytes.length - 2] = util_calculateChecksum((bytes));
|
||||
// socket.send(new DatagramPacket(bytes, bytes.length, broadcast, 9871));
|
||||
// }
|
||||
|
||||
// private void send_hello() throws IOException {
|
||||
// String payload = String.format("HELLO:\"%s\" \"%s\" \"%s\" %d %d?\0",
|
||||
// "DO5AMF", "", stationID, "SLAVE", 1, 14);
|
||||
@@ -390,6 +632,61 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
return packetFields.length > 3 ? packetFields[3] : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the log identity of an ADDQSO packet.
|
||||
*
|
||||
* <p>Win-Test numbers the QSOs of every log continuously, so a QSO is only
|
||||
* identified by the combination of the logging station, the unique log ID
|
||||
* and the QSO number. The log ID is the last field of the packet.</p>
|
||||
*
|
||||
* @param packetFields fields of the ADDQSO packet
|
||||
* @return identity in the form {@code StationName@LogUniqueID}, or
|
||||
* {@code null} when the packet does not carry both values
|
||||
*/
|
||||
static String extractLogIdFromWinTestAddQso(List<String> packetFields) {
|
||||
if (packetFields == null || packetFields.size() < ADDQSO_FIELD_COUNT) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String stationName = packetFields.get(ADDQSO_STATION_NAME_INDEX);
|
||||
String logUniqueId = packetFields.get(packetFields.size() - 1);
|
||||
|
||||
if (stationName == null || stationName.isBlank()
|
||||
|| logUniqueId == null || logUniqueId.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return stationName.trim() + "@" + logUniqueId.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the Win-Test QSO number of an ADDQSO packet.
|
||||
*
|
||||
* <p>Win-Test sends {@code 0} instead of {@code 1} for the first QSO of a
|
||||
* log in some situations. wtKST corrects that the same way.</p>
|
||||
*
|
||||
* @param packetFields fields of the ADDQSO packet
|
||||
* @return QSO number, or {@code 0} when the packet carries no usable value
|
||||
*/
|
||||
static long extractQsoNumberFromWinTestAddQso(List<String> packetFields) {
|
||||
if (packetFields == null || packetFields.size() < ADDQSO_FIELD_COUNT) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
String rawQsoNumber = packetFields.get(ADDQSO_QSO_NUMBER_INDEX);
|
||||
|
||||
if (rawQsoNumber == null) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
try {
|
||||
long qsoNumber = Long.parseLong(rawQsoNumber.trim());
|
||||
return qsoNumber <= 0L ? 1L : qsoNumber;
|
||||
} catch (NumberFormatException exception) {
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the locator from a Win-Test ADDQSO packet.
|
||||
*
|
||||
@@ -443,6 +740,17 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
*/
|
||||
private void parseAddQso(String msg) {
|
||||
try {
|
||||
List<String> packetFields = WinTestPacket.tokenize(msg);
|
||||
String logId = extractLogIdFromWinTestAddQso(packetFields);
|
||||
long qsoNumber = extractQsoNumberFromWinTestAddQso(packetFields);
|
||||
|
||||
/*
|
||||
* The QSO number is registered before any validation. Otherwise the
|
||||
* log synchronization would request a QSO with unusable content
|
||||
* over and over again.
|
||||
*/
|
||||
boolean isUnknownQso = logSyncService.registerReceivedQso(logId, qsoNumber);
|
||||
|
||||
String[] quotedParts = msg == null ? new String[0] : msg.split("\"");
|
||||
String callSign = quotedParts.length > 7 ? quotedParts[7] : "";
|
||||
String rawBandId = extractBandIdFromWinTestAddQso(msg);
|
||||
@@ -455,6 +763,16 @@ public class ReadUDPByWintestThread extends Thread {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isUnknownQso) {
|
||||
/*
|
||||
* Win-Test resends known QSOs when a NEEDQSO request overlaps
|
||||
* with QSOs that already arrived as a broadcast. Worked state
|
||||
* and database entry exist in that case, so repeating the write
|
||||
* would only cost time during the initial log recovery.
|
||||
*/
|
||||
return;
|
||||
}
|
||||
|
||||
if (loggedBand == null && !rawBandId.isEmpty()) {
|
||||
System.out.println("[WinTestUDPRcvr: warning] Unknown band ID: " + rawBandId);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,24 @@ public final class SkedReminderService {
|
||||
this.controller = controller;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancels every armed reminder and stops the scheduler thread.
|
||||
*
|
||||
* <p>Called when the runtime that owns this service is torn down, so a discarded
|
||||
* runtime does not keep a thread and pending reminders alive.</p>
|
||||
*/
|
||||
public void shutdown() {
|
||||
|
||||
for (List<ScheduledFuture<?>> remindersOfOneCall : scheduledByCallRaw.values()) {
|
||||
for (ScheduledFuture<?> armedReminder : remindersOfOneCall) {
|
||||
armedReminder.cancel(false);
|
||||
}
|
||||
}
|
||||
|
||||
scheduledByCallRaw.clear();
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
|
||||
/**
|
||||
* Arms reminders for one sked. Existing reminders for this call are cancelled.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Inventory of one Win-Test log, transported in an {@code IHAVE} packet.
|
||||
*
|
||||
* <p>Win-Test announces which QSO numbers of a log a station currently holds.
|
||||
* To keep the packet short the inventory is run-length encoded:</p>
|
||||
*
|
||||
* <pre>
|
||||
* IHAVE: "Shack" "" "Shack@9" E 1 1 911-1-117
|
||||
* ^logId ^ ^ ^ ^run lengths
|
||||
* origin | initial state
|
||||
* first row
|
||||
* </pre>
|
||||
*
|
||||
* <p>The run lengths alternate between present and missing QSOs, starting with
|
||||
* the state given by {@code InitialState} at QSO number {@code FirstRow}. The
|
||||
* example above therefore means: QSOs 1 to 911 are present, QSO 912 is missing
|
||||
* and QSOs 913 to 1029 are present again.</p>
|
||||
*
|
||||
* <p>Unlike the wtKST implementation this parser honours {@code FirstRow}
|
||||
* instead of assuming that every inventory starts at QSO number one. Win-Test
|
||||
* splits long inventories into several packets, and a split inventory starts at
|
||||
* a higher first row.</p>
|
||||
*/
|
||||
public final class WinTestIhaveInventory {
|
||||
|
||||
/** Where the sending station got the log from. */
|
||||
public enum Origin {
|
||||
/** The station owns the log or the operator is logged on there. */
|
||||
OWNER,
|
||||
/** The station only mirrors a log owned by somebody else. */
|
||||
LOGGED_ELSE
|
||||
}
|
||||
|
||||
/** Protects against endless loops caused by a corrupted run-length chain. */
|
||||
private static final int MAX_SEGMENTS = 512;
|
||||
|
||||
private static final int EXPECTED_FIELD_COUNT = 5;
|
||||
|
||||
private final String logId;
|
||||
private final Origin origin;
|
||||
private final List<WinTestLogSegment> segments;
|
||||
|
||||
private WinTestIhaveInventory(String logId, Origin origin, List<WinTestLogSegment> segments) {
|
||||
this.logId = logId;
|
||||
this.origin = origin;
|
||||
this.segments = segments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses an {@code IHAVE} packet.
|
||||
*
|
||||
* @param packet received packet
|
||||
* @return inventory, or an empty value when the packet is not a usable
|
||||
* {@code IHAVE} announcement
|
||||
*/
|
||||
public static Optional<WinTestIhaveInventory> fromPacket(WinTestPacket packet) {
|
||||
if (packet == null || !"IHAVE".equals(packet.getMessageType())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<String> fields = packet.getDataTokens();
|
||||
if (fields.size() != EXPECTED_FIELD_COUNT) {
|
||||
/*
|
||||
* Win-Test versions before 1.29 use a shorter IHAVE format without
|
||||
* run-length encoding. It carries no usable range information, so
|
||||
* the blind fallback of the sync service has to take over.
|
||||
*/
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
String parsedLogId = fields.get(0) == null ? "" : fields.get(0).trim();
|
||||
if (parsedLogId.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Origin parsedOrigin = parseOrigin(fields.get(1));
|
||||
|
||||
long firstRow = parseUnsignedValue(fields.get(2));
|
||||
long initialState = parseUnsignedValue(fields.get(3));
|
||||
|
||||
if (firstRow < 1L || initialState < 0L || initialState > 1L) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
List<WinTestLogSegment> parsedSegments =
|
||||
parseRunLengths(fields.get(4), firstRow, initialState == 1L);
|
||||
|
||||
if (parsedSegments == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(new WinTestIhaveInventory(parsedLogId, parsedOrigin, parsedSegments));
|
||||
}
|
||||
|
||||
private static Origin parseOrigin(String rawOrigin) {
|
||||
if (rawOrigin == null) {
|
||||
return Origin.OWNER;
|
||||
}
|
||||
|
||||
String normalizedOrigin = rawOrigin.trim().toUpperCase(java.util.Locale.ROOT);
|
||||
if ("E".equals(normalizedOrigin) || "LOGGEDELSE".equals(normalizedOrigin)) {
|
||||
return Origin.LOGGED_ELSE;
|
||||
}
|
||||
return Origin.OWNER;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expands the hyphen-separated run lengths into ranges.
|
||||
*
|
||||
* @param rawRunLengths run-length chain such as {@code 911-1-117}
|
||||
* @param firstRow QSO number the first run starts at
|
||||
* @param startsPresent {@code true} when the first run describes present QSOs
|
||||
* @return ranges of present QSOs, or {@code null} for an unusable chain
|
||||
*/
|
||||
private static List<WinTestLogSegment> parseRunLengths(
|
||||
String rawRunLengths,
|
||||
long firstRow,
|
||||
boolean startsPresent
|
||||
) {
|
||||
if (rawRunLengths == null || rawRunLengths.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String[] runLengths = rawRunLengths.trim().split("-");
|
||||
|
||||
/*
|
||||
* A chain that starts with present QSOs has to end with a present run,
|
||||
* so its length is odd. A chain that starts with missing QSOs needs an
|
||||
* even length for the same reason.
|
||||
*/
|
||||
if (startsPresent) {
|
||||
if (runLengths.length % 2 == 0) {
|
||||
return null;
|
||||
}
|
||||
} else if (runLengths.length % 2 == 1 || runLengths.length < 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<WinTestLogSegment> parsedSegments = new ArrayList<>();
|
||||
long cursor = firstRow;
|
||||
boolean present = startsPresent;
|
||||
|
||||
for (String runLength : runLengths) {
|
||||
long count = parseUnsignedValue(runLength);
|
||||
if (count < 0L) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (present && count > 0L) {
|
||||
if (parsedSegments.size() >= MAX_SEGMENTS) {
|
||||
return null;
|
||||
}
|
||||
parsedSegments.add(new WinTestLogSegment(cursor, cursor + count - 1L));
|
||||
}
|
||||
|
||||
cursor += count;
|
||||
present = !present;
|
||||
}
|
||||
|
||||
return parsedSegments;
|
||||
}
|
||||
|
||||
private static long parseUnsignedValue(String rawValue) {
|
||||
if (rawValue == null) {
|
||||
return -1L;
|
||||
}
|
||||
|
||||
try {
|
||||
return Long.parseLong(rawValue.trim());
|
||||
} catch (NumberFormatException exception) {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return log identity in the form {@code StationName@LogUniqueID}
|
||||
*/
|
||||
public String getLogId() {
|
||||
return logId;
|
||||
}
|
||||
|
||||
public Origin getOrigin() {
|
||||
return origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return ranges of QSO numbers the announcing station holds
|
||||
*/
|
||||
public List<WinTestLogSegment> getSegments() {
|
||||
return Collections.unmodifiableList(segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return highest announced QSO number, or {@code 0} for an empty inventory
|
||||
*/
|
||||
public long getHighestQsoNumber() {
|
||||
long highestQsoNumber = 0L;
|
||||
for (WinTestLogSegment segment : segments) {
|
||||
if (segment.getCountTo() > highestQsoNumber) {
|
||||
highestQsoNumber = segment.getCountTo();
|
||||
}
|
||||
}
|
||||
return highestQsoNumber;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return logId + " " + origin + " " + segments;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
/**
|
||||
* Consecutive range of Win-Test QSO numbers inside one log.
|
||||
*
|
||||
* <p>Win-Test numbers the QSOs of every log continuously. The {@code IHAVE}
|
||||
* inventory of a log is therefore expressed as a list of ranges that are
|
||||
* present in that log. A range is inclusive on both ends.</p>
|
||||
*/
|
||||
public final class WinTestLogSegment {
|
||||
|
||||
private final long countFrom;
|
||||
private final long countTo;
|
||||
|
||||
/**
|
||||
* @param countFrom first QSO number of the range
|
||||
* @param countTo last QSO number of the range
|
||||
*/
|
||||
public WinTestLogSegment(long countFrom, long countTo) {
|
||||
this.countFrom = countFrom;
|
||||
this.countTo = countTo;
|
||||
}
|
||||
|
||||
public long getCountFrom() {
|
||||
return countFrom;
|
||||
}
|
||||
|
||||
public long getCountTo() {
|
||||
return countTo;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of QSOs covered by this range, never negative
|
||||
*/
|
||||
public long getCount() {
|
||||
return countTo < countFrom ? 0L : countTo - countFrom + 1L;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (!(other instanceof WinTestLogSegment)) {
|
||||
return false;
|
||||
}
|
||||
WinTestLogSegment otherSegment = (WinTestLogSegment) other;
|
||||
return countFrom == otherSegment.countFrom && countTo == otherSegment.countTo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Long.hashCode(countFrom) * 31 + Long.hashCode(countTo);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return countFrom + "-" + countTo;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NavigableSet;
|
||||
import java.util.Optional;
|
||||
import java.util.TreeSet;
|
||||
import java.util.function.LongSupplier;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* Recovers the part of a Win-Test log that was written before KST4Contest was
|
||||
* started.
|
||||
*
|
||||
* <p>Win-Test broadcasts every new QSO as an {@code ADDQSO} packet. A client
|
||||
* that joins the network later never sees the QSOs logged before it started, so
|
||||
* stations already worked would still be shown as not worked. Win-Test also
|
||||
* offers a pull mechanism for exactly this situation, and this service is the
|
||||
* port of the wtKST {@code WtLogSync} implementation of it:</p>
|
||||
*
|
||||
* <ol>
|
||||
* <li>a Win-Test station announces itself with {@code HELLO} or, if its log
|
||||
* was opened before we started listening, with its periodic
|
||||
* {@code STATUS};</li>
|
||||
* <li>its periodic {@code IHAVE} packets announce which QSO numbers of
|
||||
* which log it holds;</li>
|
||||
* <li>missing ranges are requested with {@code NEEDQSO}, at most
|
||||
* {@value #MAX_QSOS_PER_REQUEST} QSOs per request;</li>
|
||||
* <li>Win-Test answers with ordinary {@code ADDQSO} packets that are
|
||||
* addressed to us instead of being broadcast.</li>
|
||||
* </ol>
|
||||
*
|
||||
* <p>Because the answers are ordinary {@code ADDQSO} packets, the recovered
|
||||
* QSOs run through the same Worked handling as live QSOs. This service only
|
||||
* decides what still has to be requested; it neither touches the database nor
|
||||
* the user interface.</p>
|
||||
*
|
||||
* <p>If a station is known but no usable {@code IHAVE} inventory arrives within
|
||||
* {@value #INVENTORY_GRACE_PERIOD_MS} ms, a blind fallback requests fixed
|
||||
* blocks starting at QSO number one until a block stays unanswered. That covers
|
||||
* Win-Test versions whose {@code IHAVE} format carries no run lengths.</p>
|
||||
*
|
||||
* <p>Deviation from wtKST: wtKST discards its whole QSO table whenever a
|
||||
* {@code HELLO} arrives, because it displays that table. KST4Contest only
|
||||
* accumulates Worked state, where a stale entry is harmless while a discarded
|
||||
* one would cause the complete log to be requested and written again. The log
|
||||
* identity {@code StationName@LogUniqueID} already changes when Win-Test opens
|
||||
* a different log, so nothing is cleared here.</p>
|
||||
*/
|
||||
public class WinTestLogSyncService {
|
||||
|
||||
/** Win-Test answers at most this many QSOs for one NEEDQSO request. */
|
||||
static final int MAX_QSOS_PER_REQUEST = 50;
|
||||
|
||||
/** Time after which an unanswered request is retried elsewhere. */
|
||||
static final long REQUEST_TIMEOUT_MS = 5000L;
|
||||
|
||||
/** Shortest distance between two evaluations without a pending trigger. */
|
||||
static final long TICK_INTERVAL_MS = 2000L;
|
||||
|
||||
/** Waiting time for a usable IHAVE before the blind fallback starts. */
|
||||
static final long INVENTORY_GRACE_PERIOD_MS = 15000L;
|
||||
|
||||
/** Upper bound for the blind fallback, equals 10000 QSOs. */
|
||||
static final int MAX_BLIND_BLOCKS = 200;
|
||||
|
||||
/** Guards the gap search against a corrupted inventory. */
|
||||
private static final long MAX_SCANNED_QSO_NUMBERS = 200000L;
|
||||
|
||||
/**
|
||||
* Sends a NEEDQSO request to a Win-Test station.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface NeedQsoSender {
|
||||
|
||||
/**
|
||||
* @param targetStation Win-Test station name the request is sent to
|
||||
* @param logId log identity in the form {@code StationName@LogUniqueID}
|
||||
* @param countFrom first requested QSO number
|
||||
* @param countTo last requested QSO number
|
||||
*/
|
||||
void sendNeedQso(String targetStation, String logId, long countFrom, long countTo);
|
||||
}
|
||||
|
||||
/** Progress of the log recovery, used for status reporting. */
|
||||
public enum SyncState {
|
||||
/** No Win-Test station seen yet. */
|
||||
IDLE,
|
||||
/** A station is known, but nothing has been requested yet. */
|
||||
STATION_DETECTED,
|
||||
/** QSOs are being requested. */
|
||||
SYNCING,
|
||||
/** Everything announced by the known stations has been received. */
|
||||
IN_SYNC
|
||||
}
|
||||
|
||||
private final NeedQsoSender needQsoSender;
|
||||
private final Supplier<String> ownStationNameSupplier;
|
||||
private final LongSupplier clock;
|
||||
|
||||
/** Inventories per Win-Test station, keyed by log identity. */
|
||||
private final Map<String, Map<String, WinTestIhaveInventory>> inventoriesByStation =
|
||||
new LinkedHashMap<>();
|
||||
|
||||
/** QSO numbers already received, keyed by log identity. */
|
||||
private final Map<String, NavigableSet<Long>> receivedQsoNumbersByLogId = new HashMap<>();
|
||||
|
||||
/** State of the blind fallback, keyed by log identity. */
|
||||
private final Map<String, BlindScan> blindScansByLogId = new LinkedHashMap<>();
|
||||
|
||||
private PendingRequest pendingRequest;
|
||||
private long firstStationSeenAtMs;
|
||||
private boolean usableInventorySeen;
|
||||
private long lastTickMs;
|
||||
private boolean tickDueImmediately;
|
||||
private SyncState state = SyncState.IDLE;
|
||||
|
||||
/**
|
||||
* @param needQsoSender transport used for NEEDQSO requests
|
||||
* @param ownStationNameSupplier own Win-Test station name, read late because
|
||||
* it can be changed in the settings at runtime
|
||||
*/
|
||||
public WinTestLogSyncService(
|
||||
NeedQsoSender needQsoSender,
|
||||
Supplier<String> ownStationNameSupplier
|
||||
) {
|
||||
this(needQsoSender, ownStationNameSupplier, System::currentTimeMillis);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param needQsoSender transport used for NEEDQSO requests
|
||||
* @param ownStationNameSupplier own Win-Test station name
|
||||
* @param clock time source in milliseconds
|
||||
*/
|
||||
WinTestLogSyncService(
|
||||
NeedQsoSender needQsoSender,
|
||||
Supplier<String> ownStationNameSupplier,
|
||||
LongSupplier clock
|
||||
) {
|
||||
this.needQsoSender = needQsoSender;
|
||||
this.ownStationNameSupplier = ownStationNameSupplier;
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a Win-Test station seen in a HELLO or STATUS packet.
|
||||
*
|
||||
* @param stationName Win-Test station name
|
||||
*/
|
||||
public synchronized void onStationSeen(String stationName) {
|
||||
if (stationName == null || stationName.isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
String normalizedStationName = stationName.trim();
|
||||
if (normalizedStationName.equalsIgnoreCase(resolveOwnStationName())) {
|
||||
// our own packets, nothing to synchronize from
|
||||
return;
|
||||
}
|
||||
|
||||
if (inventoriesByStation.putIfAbsent(normalizedStationName, new LinkedHashMap<>()) == null) {
|
||||
tickDueImmediately = true;
|
||||
}
|
||||
|
||||
if (firstStationSeenAtMs == 0L) {
|
||||
firstStationSeenAtMs = clock.getAsLong();
|
||||
}
|
||||
|
||||
if (state == SyncState.IDLE) {
|
||||
state = SyncState.STATION_DETECTED;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes over the inventory of an IHAVE packet.
|
||||
*
|
||||
* @param packet received IHAVE packet
|
||||
*/
|
||||
public synchronized void onIhaveReceived(WinTestPacket packet) {
|
||||
if (packet == null || !packet.isAddressedTo(resolveOwnStationName())) {
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<WinTestIhaveInventory> parsedInventory = WinTestIhaveInventory.fromPacket(packet);
|
||||
if (parsedInventory.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
WinTestIhaveInventory inventory = parsedInventory.get();
|
||||
onStationSeen(packet.getSource());
|
||||
|
||||
Map<String, WinTestIhaveInventory> stationInventories =
|
||||
inventoriesByStation.get(packet.getSource() == null ? "" : packet.getSource().trim());
|
||||
|
||||
if (stationInventories == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
WinTestIhaveInventory previousInventory =
|
||||
stationInventories.put(inventory.getLogId(), inventory);
|
||||
|
||||
if (previousInventory == null
|
||||
|| !previousInventory.getSegments().equals(inventory.getSegments())) {
|
||||
System.out.println("[WinTest LogSync] inventory of " + inventory.getLogId()
|
||||
+ " from " + packet.getSource()
|
||||
+ " (" + inventory.getOrigin() + "): " + inventory.getSegments());
|
||||
}
|
||||
|
||||
usableInventorySeen = true;
|
||||
blindScansByLogId.remove(inventory.getLogId());
|
||||
tickDueImmediately = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a QSO received in an ADDQSO packet.
|
||||
*
|
||||
* @param logId log identity in the form {@code StationName@LogUniqueID}
|
||||
* @param qsoNumber Win-Test QSO number inside that log
|
||||
* @return {@code true} when this QSO was not known before, and therefore
|
||||
* still has to be applied to Worked state and database
|
||||
*/
|
||||
public synchronized boolean registerReceivedQso(String logId, long qsoNumber) {
|
||||
if (logId == null || logId.isBlank() || qsoNumber <= 0L) {
|
||||
// without a usable identity the QSO cannot be deduplicated
|
||||
return true;
|
||||
}
|
||||
|
||||
NavigableSet<Long> receivedQsoNumbers =
|
||||
receivedQsoNumbersByLogId.computeIfAbsent(logId.trim(), key -> new TreeSet<>());
|
||||
boolean isNewQso = receivedQsoNumbers.add(qsoNumber);
|
||||
|
||||
if (pendingRequest != null
|
||||
&& pendingRequest.logId.equals(logId.trim())
|
||||
&& qsoNumber >= pendingRequest.countFrom
|
||||
&& qsoNumber <= pendingRequest.countTo) {
|
||||
|
||||
pendingRequest.answeredQsoCount++;
|
||||
|
||||
if (qsoNumber == pendingRequest.countTo
|
||||
|| pendingRequest.answeredQsoCount >= pendingRequest.getRequestedQsoCount()) {
|
||||
PendingRequest completedRequest = pendingRequest;
|
||||
pendingRequest = null;
|
||||
if (completedRequest.blind) {
|
||||
finishBlindBlock(completedRequest);
|
||||
}
|
||||
tickDueImmediately = true;
|
||||
}
|
||||
}
|
||||
|
||||
return isNewQso;
|
||||
}
|
||||
|
||||
/**
|
||||
* Advances the recovery. Called after every received packet and on every
|
||||
* receive timeout of the listener; an internal interval keeps the actual
|
||||
* work rare while a satisfied request triggers the next one immediately.
|
||||
*/
|
||||
public synchronized void tick() {
|
||||
long now = clock.getAsLong();
|
||||
|
||||
if (!tickDueImmediately && now - lastTickMs < TICK_INTERVAL_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastTickMs = now;
|
||||
tickDueImmediately = false;
|
||||
|
||||
if (pendingRequest != null) {
|
||||
if (now - pendingRequest.sentAtMs < REQUEST_TIMEOUT_MS) {
|
||||
return;
|
||||
}
|
||||
handlePendingTimeout();
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestNextMissingRange(now)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (requestNextBlindBlock(now)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state == SyncState.SYNCING) {
|
||||
state = SyncState.IN_SYNC;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return current progress of the recovery
|
||||
*/
|
||||
public synchronized SyncState getState() {
|
||||
return state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return number of QSO numbers known for the given log
|
||||
*/
|
||||
synchronized int getKnownQsoCount(String logId) {
|
||||
NavigableSet<Long> receivedQsoNumbers = receivedQsoNumbersByLogId.get(logId);
|
||||
return receivedQsoNumbers == null ? 0 : receivedQsoNumbers.size();
|
||||
}
|
||||
|
||||
private void handlePendingTimeout() {
|
||||
PendingRequest timedOutRequest = pendingRequest;
|
||||
pendingRequest = null;
|
||||
|
||||
if (timedOutRequest.blind) {
|
||||
finishBlindBlock(timedOutRequest);
|
||||
return;
|
||||
}
|
||||
|
||||
String alternativeStation =
|
||||
findAlternativeStation(timedOutRequest.logId, timedOutRequest.targetStation);
|
||||
|
||||
System.out.println("[WinTest LogSync] no answer from " + timedOutRequest.targetStation
|
||||
+ " for " + timedOutRequest.logId + " "
|
||||
+ timedOutRequest.countFrom + "-" + timedOutRequest.countTo);
|
||||
|
||||
if (alternativeStation != null) {
|
||||
sendRequest(
|
||||
alternativeStation,
|
||||
timedOutRequest.logId,
|
||||
timedOutRequest.countFrom,
|
||||
timedOutRequest.countTo,
|
||||
false,
|
||||
clock.getAsLong()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* Nobody else holds this log. The silent station is dropped and returns
|
||||
* with its next STATUS or IHAVE packet.
|
||||
*/
|
||||
System.out.println("[WinTest LogSync] dropping silent station "
|
||||
+ timedOutRequest.targetStation + ", waiting for its next STATUS or IHAVE");
|
||||
inventoriesByStation.remove(timedOutRequest.targetStation);
|
||||
tickDueImmediately = true;
|
||||
}
|
||||
|
||||
private String findAlternativeStation(String logId, String excludedStation) {
|
||||
for (Map.Entry<String, Map<String, WinTestIhaveInventory>> station
|
||||
: inventoriesByStation.entrySet()) {
|
||||
|
||||
if (station.getKey().equals(excludedStation)) {
|
||||
continue;
|
||||
}
|
||||
if (station.getValue().containsKey(logId)) {
|
||||
return station.getKey();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Looks for the first announced QSO range that is still missing and
|
||||
* requests it. Stations that own a log are preferred over stations that
|
||||
* only mirror it.
|
||||
*
|
||||
* @param now current time in milliseconds
|
||||
* @return {@code true} when a request was sent
|
||||
*/
|
||||
private boolean requestNextMissingRange(long now) {
|
||||
for (int pass = 0; pass < 2; pass++) {
|
||||
boolean preferOwner = pass == 0;
|
||||
|
||||
for (Map.Entry<String, Map<String, WinTestIhaveInventory>> station
|
||||
: new ArrayList<>(inventoriesByStation.entrySet())) {
|
||||
|
||||
for (WinTestIhaveInventory inventory : new ArrayList<>(station.getValue().values())) {
|
||||
boolean isOwner = inventory.getOrigin() == WinTestIhaveInventory.Origin.OWNER;
|
||||
if (preferOwner != isOwner) {
|
||||
continue;
|
||||
}
|
||||
|
||||
long[] missingRange = findMissingRange(
|
||||
inventory.getSegments(),
|
||||
receivedQsoNumbersByLogId.get(inventory.getLogId())
|
||||
);
|
||||
|
||||
if (missingRange == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sendRequest(
|
||||
station.getKey(),
|
||||
inventory.getLogId(),
|
||||
missingRange[0],
|
||||
missingRange[1],
|
||||
false,
|
||||
now
|
||||
);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the next missing QSO range of one log.
|
||||
*
|
||||
* <p>wtKST compares its own segment list against the announced one and
|
||||
* derives the request bounds from the segment indices. Searching the gap
|
||||
* directly produces the same ranges for the ordinary cases, cannot run past
|
||||
* the end of either list, and never asks for QSO numbers that are already
|
||||
* known.</p>
|
||||
*
|
||||
* @param segments ranges announced by the station
|
||||
* @param receivedQsoNumbers QSO numbers already received for this log
|
||||
* @return first missing range as {@code {countFrom, countTo}}, or
|
||||
* {@code null} when nothing is missing
|
||||
*/
|
||||
static long[] findMissingRange(
|
||||
List<WinTestLogSegment> segments,
|
||||
NavigableSet<Long> receivedQsoNumbers
|
||||
) {
|
||||
if (segments == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
long remainingScanBudget = MAX_SCANNED_QSO_NUMBERS;
|
||||
|
||||
for (WinTestLogSegment segment : segments) {
|
||||
for (long qsoNumber = segment.getCountFrom();
|
||||
qsoNumber <= segment.getCountTo();
|
||||
qsoNumber++) {
|
||||
|
||||
remainingScanBudget--;
|
||||
if (remainingScanBudget < 0L) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (receivedQsoNumbers != null && receivedQsoNumbers.contains(qsoNumber)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
long countFrom = qsoNumber;
|
||||
long countTo = countFrom;
|
||||
|
||||
while (countTo < segment.getCountTo()
|
||||
&& countTo - countFrom + 1L < MAX_QSOS_PER_REQUEST
|
||||
&& (receivedQsoNumbers == null || !receivedQsoNumbers.contains(countTo + 1L))) {
|
||||
countTo++;
|
||||
}
|
||||
|
||||
return new long[] { countFrom, countTo };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests the next fixed block of a log whose station never sent a usable
|
||||
* inventory.
|
||||
*
|
||||
* @param now current time in milliseconds
|
||||
* @return {@code true} when a request was sent
|
||||
*/
|
||||
private boolean requestNextBlindBlock(long now) {
|
||||
if (usableInventorySeen || firstStationSeenAtMs == 0L) {
|
||||
return false;
|
||||
}
|
||||
if (now - firstStationSeenAtMs < INVENTORY_GRACE_PERIOD_MS) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (String logId : new ArrayList<>(receivedQsoNumbersByLogId.keySet())) {
|
||||
BlindScan blindScan = blindScansByLogId.computeIfAbsent(logId, key -> new BlindScan());
|
||||
|
||||
if (blindScan.completed || blindScan.requestedBlockCount >= MAX_BLIND_BLOCKS) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String targetStation = resolveStationForLogId(logId);
|
||||
if (targetStation == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
blindScan.requestedBlockCount++;
|
||||
sendRequest(
|
||||
targetStation,
|
||||
logId,
|
||||
blindScan.nextCountFrom,
|
||||
blindScan.nextCountFrom + MAX_QSOS_PER_REQUEST - 1L,
|
||||
true,
|
||||
now
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private void finishBlindBlock(PendingRequest finishedRequest) {
|
||||
BlindScan blindScan = blindScansByLogId.get(finishedRequest.logId);
|
||||
if (blindScan == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("[WinTest LogSync] blind block " + finishedRequest.countFrom
|
||||
+ "-" + finishedRequest.countTo + " of " + finishedRequest.logId
|
||||
+ " answered with " + finishedRequest.answeredQsoCount + " QSOs");
|
||||
|
||||
if (finishedRequest.answeredQsoCount == 0) {
|
||||
// the log ends before this block, nothing left to fetch
|
||||
blindScan.completed = true;
|
||||
} else {
|
||||
blindScan.nextCountFrom = finishedRequest.countTo + 1L;
|
||||
}
|
||||
|
||||
tickDueImmediately = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the Win-Test station a log belongs to. The log identity carries
|
||||
* the owning station name in front of the {@code @} separator.
|
||||
*
|
||||
* @param logId log identity
|
||||
* @return station name to ask, or {@code null} when none is known
|
||||
*/
|
||||
private String resolveStationForLogId(String logId) {
|
||||
int separatorIndex = logId.indexOf('@');
|
||||
String ownerStationName = separatorIndex > 0 ? logId.substring(0, separatorIndex) : logId;
|
||||
|
||||
for (String stationName : inventoriesByStation.keySet()) {
|
||||
if (stationName.equalsIgnoreCase(ownerStationName)) {
|
||||
return stationName;
|
||||
}
|
||||
}
|
||||
|
||||
return ownerStationName.isBlank() ? null : ownerStationName;
|
||||
}
|
||||
|
||||
private void sendRequest(
|
||||
String targetStation,
|
||||
String logId,
|
||||
long countFrom,
|
||||
long countTo,
|
||||
boolean blind,
|
||||
long now
|
||||
) {
|
||||
pendingRequest = new PendingRequest(targetStation, logId, countFrom, countTo, blind, now);
|
||||
state = SyncState.SYNCING;
|
||||
|
||||
try {
|
||||
needQsoSender.sendNeedQso(targetStation, logId, countFrom, countTo);
|
||||
} catch (RuntimeException exception) {
|
||||
/*
|
||||
* A failed transmission must not stop the receive loop. The pending
|
||||
* request runs into its timeout and is retried from there.
|
||||
*/
|
||||
System.out.println(
|
||||
"[WinTest LogSync] NEEDQSO could not be sent: " + exception.getMessage()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private String resolveOwnStationName() {
|
||||
if (ownStationNameSupplier == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String ownStationName = ownStationNameSupplier.get();
|
||||
return ownStationName == null ? "" : ownStationName.trim();
|
||||
}
|
||||
|
||||
/** Request that is waiting for its answer. */
|
||||
private static final class PendingRequest {
|
||||
|
||||
private final String targetStation;
|
||||
private final String logId;
|
||||
private final long countFrom;
|
||||
private final long countTo;
|
||||
private final boolean blind;
|
||||
private final long sentAtMs;
|
||||
private int answeredQsoCount;
|
||||
|
||||
private PendingRequest(
|
||||
String targetStation,
|
||||
String logId,
|
||||
long countFrom,
|
||||
long countTo,
|
||||
boolean blind,
|
||||
long sentAtMs
|
||||
) {
|
||||
this.targetStation = targetStation;
|
||||
this.logId = logId;
|
||||
this.countFrom = countFrom;
|
||||
this.countTo = countTo;
|
||||
this.blind = blind;
|
||||
this.sentAtMs = sentAtMs;
|
||||
}
|
||||
|
||||
private long getRequestedQsoCount() {
|
||||
return countTo - countFrom + 1L;
|
||||
}
|
||||
}
|
||||
|
||||
/** Progress of the blind fallback for one log. */
|
||||
private static final class BlindScan {
|
||||
private long nextCountFrom = 1L;
|
||||
private int requestedBlockCount;
|
||||
private boolean completed;
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ import java.nio.charset.StandardCharsets;
|
||||
*/
|
||||
public class WinTestMessage {
|
||||
|
||||
/** Win-Test message types relevant for SKED management. */
|
||||
/** Win-Test message types sent by KST4Contest. */
|
||||
public enum MessageType {
|
||||
/** Requests a range of QSOs of one Win-Test log for log synchronization. */
|
||||
NEEDQSO,
|
||||
LOCKSKED,
|
||||
UNLOCKSKED,
|
||||
ADDSKED,
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InterfaceAddress;
|
||||
import java.net.NetworkInterface;
|
||||
import java.net.SocketException;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Enumeration;
|
||||
|
||||
/**
|
||||
* Determines the broadcast address used to talk to the Win-Test network.
|
||||
*
|
||||
* <p>Win-Test only reacts to broadcast packets; a unicast request to the same
|
||||
* station stays unanswered. The configured broadcast address is therefore the
|
||||
* one setting that silently disables every outgoing Win-Test feature when it is
|
||||
* wrong: sending to an address outside the local networks succeeds without an
|
||||
* error and the packet is routed away.</p>
|
||||
*
|
||||
* <p>Incoming Win-Test packets carry the information that is actually needed.
|
||||
* The source address of a received packet identifies the network the station
|
||||
* lives in, so the broadcast address of the matching local interface reaches it
|
||||
* reliably. The configured address remains the fallback and keeps working for a
|
||||
* station behind a router, where no local interface matches.</p>
|
||||
*/
|
||||
public class WinTestNetworkAddressResolver {
|
||||
|
||||
/** Last resort when neither a station nor a usable setting is available. */
|
||||
private static final String LIMITED_BROADCAST_ADDRESS = "255.255.255.255";
|
||||
|
||||
/**
|
||||
* Resolves the local broadcast address for a remote address.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface LocalBroadcastLookup {
|
||||
|
||||
/**
|
||||
* @param remoteAddress address a Win-Test packet was received from
|
||||
* @return broadcast address of the matching local interface, or
|
||||
* {@code null} when no local interface serves that network
|
||||
*/
|
||||
InetAddress findBroadcastFor(InetAddress remoteAddress);
|
||||
}
|
||||
|
||||
private final LocalBroadcastLookup localBroadcastLookup;
|
||||
|
||||
private volatile InetAddress lastStationAddress;
|
||||
|
||||
private volatile String lastReportedBroadcastAddress;
|
||||
|
||||
public WinTestNetworkAddressResolver() {
|
||||
this(WinTestNetworkAddressResolver::findLocalBroadcastAddress);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param localBroadcastLookup interface lookup, replaceable for tests
|
||||
*/
|
||||
WinTestNetworkAddressResolver(LocalBroadcastLookup localBroadcastLookup) {
|
||||
this.localBroadcastLookup = localBroadcastLookup;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remembers where Win-Test packets come from.
|
||||
*
|
||||
* <p>Only addresses of real Win-Test stations may be passed in. Loopback and
|
||||
* wildcard addresses are ignored, so an internal control packet cannot
|
||||
* redirect outgoing Win-Test traffic.</p>
|
||||
*
|
||||
* @param stationAddress source address of a received Win-Test packet
|
||||
*/
|
||||
public void rememberStationAddress(InetAddress stationAddress) {
|
||||
if (stationAddress == null
|
||||
|| stationAddress.isLoopbackAddress()
|
||||
|| stationAddress.isAnyLocalAddress()
|
||||
|| !(stationAddress instanceof Inet4Address)) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.lastStationAddress = stationAddress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines the broadcast address for outgoing Win-Test packets.
|
||||
*
|
||||
* <p>Order of preference: the broadcast address of the local interface that
|
||||
* serves the last seen Win-Test station, then the configured address, then
|
||||
* the limited broadcast address.</p>
|
||||
*
|
||||
* @param configuredBroadcastAddress address from the settings, may be blank
|
||||
* @return address to send Win-Test packets to
|
||||
* @throws UnknownHostException if the configured address cannot be resolved
|
||||
* and the limited broadcast address fails too
|
||||
*/
|
||||
public InetAddress resolveBroadcastAddress(String configuredBroadcastAddress)
|
||||
throws UnknownHostException {
|
||||
|
||||
InetAddress stationAddress = this.lastStationAddress;
|
||||
|
||||
if (stationAddress != null) {
|
||||
InetAddress derivedBroadcastAddress =
|
||||
localBroadcastLookup.findBroadcastFor(stationAddress);
|
||||
|
||||
if (derivedBroadcastAddress != null) {
|
||||
reportDerivedAddress(derivedBroadcastAddress, configuredBroadcastAddress);
|
||||
return derivedBroadcastAddress;
|
||||
}
|
||||
}
|
||||
|
||||
if (configuredBroadcastAddress != null && !configuredBroadcastAddress.isBlank()) {
|
||||
return InetAddress.getByName(configuredBroadcastAddress.trim());
|
||||
}
|
||||
|
||||
return InetAddress.getByName(LIMITED_BROADCAST_ADDRESS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a derived address once as long as it stays the same, and points out
|
||||
* a configured address that does not match the Win-Test network.
|
||||
*/
|
||||
private void reportDerivedAddress(
|
||||
InetAddress derivedBroadcastAddress,
|
||||
String configuredBroadcastAddress
|
||||
) {
|
||||
String derivedHostAddress = derivedBroadcastAddress.getHostAddress();
|
||||
|
||||
if (derivedHostAddress.equals(lastReportedBroadcastAddress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastReportedBroadcastAddress = derivedHostAddress;
|
||||
|
||||
String configuredHostAddress = configuredBroadcastAddress == null
|
||||
? "" : configuredBroadcastAddress.trim();
|
||||
|
||||
if (derivedHostAddress.equals(configuredHostAddress)) {
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("[WinTest] using broadcast address " + derivedHostAddress
|
||||
+ " of the network Win-Test was heard on, configured is '"
|
||||
+ configuredHostAddress + "'");
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches the local interfaces for the network a remote address belongs to.
|
||||
*
|
||||
* @param remoteAddress address of a Win-Test station
|
||||
* @return broadcast address of the matching interface, or {@code null}
|
||||
*/
|
||||
static InetAddress findLocalBroadcastAddress(InetAddress remoteAddress) {
|
||||
if (!(remoteAddress instanceof Inet4Address)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
Enumeration<NetworkInterface> networkInterfaces =
|
||||
NetworkInterface.getNetworkInterfaces();
|
||||
|
||||
while (networkInterfaces != null && networkInterfaces.hasMoreElements()) {
|
||||
NetworkInterface networkInterface = networkInterfaces.nextElement();
|
||||
|
||||
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
|
||||
InetAddress broadcastAddress = interfaceAddress.getBroadcast();
|
||||
|
||||
if (broadcastAddress == null
|
||||
|| !(interfaceAddress.getAddress() instanceof Inet4Address)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (isInSameSubnet(
|
||||
interfaceAddress.getAddress(),
|
||||
remoteAddress,
|
||||
interfaceAddress.getNetworkPrefixLength())) {
|
||||
return broadcastAddress;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (SocketException exception) {
|
||||
System.out.println("[WinTest] could not inspect local interfaces: "
|
||||
+ exception.getMessage());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two IPv4 addresses up to the given network prefix length.
|
||||
*
|
||||
* @param localAddress address of a local interface
|
||||
* @param remoteAddress address of the Win-Test station
|
||||
* @param networkPrefixLength prefix length of the local interface
|
||||
* @return {@code true} when both addresses share the same network
|
||||
*/
|
||||
static boolean isInSameSubnet(
|
||||
InetAddress localAddress,
|
||||
InetAddress remoteAddress,
|
||||
int networkPrefixLength
|
||||
) {
|
||||
if (localAddress == null || remoteAddress == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
byte[] localBytes = localAddress.getAddress();
|
||||
byte[] remoteBytes = remoteAddress.getAddress();
|
||||
|
||||
if (localBytes.length != remoteBytes.length
|
||||
|| networkPrefixLength < 0
|
||||
|| networkPrefixLength > localBytes.length * 8) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int remainingPrefixBits = networkPrefixLength;
|
||||
|
||||
for (int byteIndex = 0; byteIndex < localBytes.length && remainingPrefixBits > 0; byteIndex++) {
|
||||
int comparedBits = Math.min(8, remainingPrefixBits);
|
||||
int mask = (0xFF << (8 - comparedBits)) & 0xFF;
|
||||
|
||||
if ((localBytes[byteIndex] & mask) != (remoteBytes[byteIndex] & mask)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
remainingPrefixBits -= comparedBits;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Win-Test network packet received over UDP.
|
||||
*
|
||||
* <p>This is the receiving counterpart of {@link WinTestMessage} and follows the
|
||||
* same framing:</p>
|
||||
*
|
||||
* <pre>
|
||||
* MESSAGETYPE: "src" "dst" data{checksum}\0
|
||||
* </pre>
|
||||
*
|
||||
* <p>The checksum byte always has bit 7 set and is therefore not valid ASCII.
|
||||
* Decoding the datagram as text before removing it turns the byte into a
|
||||
* replacement character that sticks to the last data field. That is harmless
|
||||
* for fields KST4Contest never reads, but the log synchronization needs exactly
|
||||
* those trailing fields: the log ID of an {@code ADDQSO} packet and the
|
||||
* run-length inventory of an {@code IHAVE} packet. The framing is therefore
|
||||
* resolved on the raw bytes here, once, before any text parsing.</p>
|
||||
*/
|
||||
public final class WinTestPacket {
|
||||
|
||||
/** Quoted values stay one token, unquoted values are split at whitespace. */
|
||||
private static final Pattern TOKEN_PATTERN = Pattern.compile("\"([^\"]*)\"|(\\S+)");
|
||||
|
||||
private final String messageType;
|
||||
private final String source;
|
||||
private final String destination;
|
||||
private final String messageText;
|
||||
private final List<String> dataTokens;
|
||||
private final boolean checksumPresent;
|
||||
private final boolean checksumValid;
|
||||
|
||||
private WinTestPacket(
|
||||
String messageType,
|
||||
String source,
|
||||
String destination,
|
||||
String messageText,
|
||||
List<String> dataTokens,
|
||||
boolean checksumPresent,
|
||||
boolean checksumValid
|
||||
) {
|
||||
this.messageType = messageType;
|
||||
this.source = source;
|
||||
this.destination = destination;
|
||||
this.messageText = messageText;
|
||||
this.dataTokens = dataTokens;
|
||||
this.checksumPresent = checksumPresent;
|
||||
this.checksumValid = checksumValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a packet from a received datagram.
|
||||
*
|
||||
* <p>Trailing NUL bytes are removed first. If the resulting last byte has
|
||||
* bit 7 set it is the Win-Test checksum: it is verified against the sum of
|
||||
* all preceding bytes and removed before the message text is decoded.</p>
|
||||
*
|
||||
* @param datagram raw datagram buffer
|
||||
* @param length number of valid bytes in the buffer
|
||||
* @return parsed packet, or {@code null} when the datagram carries no message
|
||||
*/
|
||||
public static WinTestPacket fromDatagram(byte[] datagram, int length) {
|
||||
if (datagram == null || length <= 0 || length > datagram.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
int endIndex = length;
|
||||
while (endIndex > 0 && datagram[endIndex - 1] == 0) {
|
||||
endIndex--;
|
||||
}
|
||||
|
||||
if (endIndex == 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
boolean hasChecksum = (datagram[endIndex - 1] & 0x80) != 0;
|
||||
boolean isChecksumValid = false;
|
||||
int textEndIndex = endIndex;
|
||||
|
||||
if (hasChecksum) {
|
||||
int sum = 0;
|
||||
for (int index = 0; index < endIndex - 1; index++) {
|
||||
sum += datagram[index] & 0xFF;
|
||||
}
|
||||
byte expectedChecksum = (byte) ((sum | 0x80) & 0xFF);
|
||||
isChecksumValid = expectedChecksum == datagram[endIndex - 1];
|
||||
textEndIndex = endIndex - 1;
|
||||
}
|
||||
|
||||
String text = new String(datagram, 0, textEndIndex, StandardCharsets.US_ASCII);
|
||||
return fromMessageText(text, hasChecksum, isChecksumValid);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a packet from an already decoded message text without checksum
|
||||
* information. Used for messages that reach the listener as text.
|
||||
*
|
||||
* @param messageText complete message text
|
||||
* @return parsed packet, or {@code null} for an unusable message
|
||||
*/
|
||||
public static WinTestPacket fromMessageText(String messageText) {
|
||||
return fromMessageText(messageText, false, false);
|
||||
}
|
||||
|
||||
private static WinTestPacket fromMessageText(
|
||||
String rawMessageText,
|
||||
boolean checksumPresent,
|
||||
boolean checksumValid
|
||||
) {
|
||||
if (rawMessageText == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String text = rawMessageText.trim();
|
||||
int typeEndIndex = text.indexOf(": ");
|
||||
if (typeEndIndex <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
String type = text.substring(0, typeEndIndex);
|
||||
List<String> tokens = tokenize(text.substring(typeEndIndex + 2));
|
||||
|
||||
String packetSource = tokens.isEmpty() ? "" : tokens.get(0);
|
||||
String packetDestination = tokens.size() > 1 ? tokens.get(1) : "";
|
||||
List<String> data = tokens.size() > 2
|
||||
? new ArrayList<>(tokens.subList(2, tokens.size()))
|
||||
: new ArrayList<>();
|
||||
|
||||
return new WinTestPacket(
|
||||
type,
|
||||
packetSource,
|
||||
packetDestination,
|
||||
text,
|
||||
data,
|
||||
checksumPresent,
|
||||
checksumValid
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits Win-Test payload text into fields. Quoted values are kept together
|
||||
* and empty quoted values are preserved, so field positions stay stable.
|
||||
*
|
||||
* @param text payload text
|
||||
* @return field values without their surrounding quotes
|
||||
*/
|
||||
static List<String> tokenize(String text) {
|
||||
List<String> tokens = new ArrayList<>();
|
||||
if (text == null) {
|
||||
return tokens;
|
||||
}
|
||||
|
||||
Matcher matcher = TOKEN_PATTERN.matcher(text);
|
||||
while (matcher.find()) {
|
||||
tokens.add(matcher.group(1) != null ? matcher.group(1) : matcher.group(2));
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return message type such as {@code ADDQSO}, never {@code null}
|
||||
*/
|
||||
public String getMessageType() {
|
||||
return messageType;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Win-Test station that sent the packet
|
||||
*/
|
||||
public String getSource() {
|
||||
return source;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return addressed Win-Test station, empty for a broadcast
|
||||
*/
|
||||
public String getDestination() {
|
||||
return destination;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return complete message text without checksum byte and NUL terminator
|
||||
*/
|
||||
public String getMessageText() {
|
||||
return messageText;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return payload fields following source and destination
|
||||
*/
|
||||
public List<String> getDataTokens() {
|
||||
return Collections.unmodifiableList(dataTokens);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param index payload field position
|
||||
* @return field value, or {@code null} when the field is missing
|
||||
*/
|
||||
public String getDataToken(int index) {
|
||||
return index >= 0 && index < dataTokens.size() ? dataTokens.get(index) : null;
|
||||
}
|
||||
|
||||
public boolean isChecksumPresent() {
|
||||
return checksumPresent;
|
||||
}
|
||||
|
||||
public boolean isChecksumValid() {
|
||||
return checksumValid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether this packet is meant for us.
|
||||
*
|
||||
* @param ownStationName own Win-Test station name
|
||||
* @return {@code true} for a broadcast or for a packet addressed to us
|
||||
*/
|
||||
public boolean isAddressedTo(String ownStationName) {
|
||||
if (destination == null || destination.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
return ownStationName != null && destination.equalsIgnoreCase(ownStationName.trim());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return messageType + ": src=" + source + " dst=" + destination
|
||||
+ " fields=" + dataTokens.size()
|
||||
+ (checksumPresent ? (checksumValid ? " checksum=ok" : " checksum=bad") : " checksum=none");
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,26 @@ public class ChatPreferences {
|
||||
* TODO: delete this from the kst4contest.view/Main.java!
|
||||
*/
|
||||
public ChatPreferences() {
|
||||
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, PREFERENCE_RESOURCE, PREFERENCES_FILE);
|
||||
this(PREFERENCES_FILE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates preferences bound to one operator profile.
|
||||
*
|
||||
* <p>The file name is resolved below the application directory, so both
|
||||
* "preferences.xml" for the root installation and "profiles/OP2/preferences.xml"
|
||||
* for an additional operator profile are valid. A missing file is seeded from the
|
||||
* bundled template, which gives a new profile the same clean defaults a first-ever
|
||||
* installation gets.</p>
|
||||
*
|
||||
* @param applicationRelativeFileName preferences file name relative to the application directory
|
||||
*/
|
||||
public ChatPreferences(final String applicationRelativeFileName) {
|
||||
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, PREFERENCE_RESOURCE, applicationRelativeFileName);
|
||||
this.storeAndRestorePreferencesFileName = ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
applicationRelativeFileName
|
||||
);
|
||||
|
||||
// lstNotify_QSOSniffer_sniffedCallSignList.add("DF0GEB");
|
||||
|
||||
@@ -148,7 +167,7 @@ public class ChatPreferences {
|
||||
*
|
||||
*/
|
||||
|
||||
String programVersion = "Chat is powered by ON4KST \n\nUsage is free. You are welcome to support: \n\n- my project (donations, bugreports, good ideas are welcome), \n- ON4KST Servers, \n- AirScout developers and \n- OV3T (best AS-data provider of the world). \n\n73 de DO5AMF, Marc (DM5M / DARC X08)";
|
||||
String programVersion = "Chat is powered by ON4KST \n\nUsage is free. You are welcome to support: \n\n- my project (donations, bugreports, good ideas are welcome), \n- ON4KST Servers, \n- AirScout developers and \n- OV3T (best AS-data provider of the world). \n\n73 de DO5AMF, Marc (DM5M / DARC X08)\nand DN9APW, Philipp Wagner";
|
||||
String logsynch_storeWorkedCallSignsFileNameUDPMessageBackup = "udpReaderBackup.txt";
|
||||
String storeAndRestorePreferencesFileName = ApplicationFileUtils.getFilePath(ApplicationConstants.APPLICATION_NAME, PREFERENCES_FILE);
|
||||
String chatState; // working variable only for use by primarystage (title bar)
|
||||
@@ -168,8 +187,14 @@ public class ChatPreferences {
|
||||
int stn_pstRotatorPort = 12000;
|
||||
|
||||
boolean stn_loginAFKState = false; //always start as here
|
||||
String stn_loginCallSign = "do5amf";
|
||||
String stn_loginCallSignRaw = "do5amf"; //for example: do5amf instead of logincallsign do5amf-2
|
||||
/*
|
||||
* The login credentials default to empty on purpose. A missing or empty value in
|
||||
* preferences.xml means "not configured yet", and falling back to a real callsign
|
||||
* would let an operator transmit under someone else's call. This matters for every
|
||||
* additional operator profile, whose preferences are created without credentials.
|
||||
*/
|
||||
String stn_loginCallSign = "";
|
||||
String stn_loginCallSignRaw = ""; //for example: do5amf instead of logincallsign do5amf-2
|
||||
String stn_loginPassword = "";
|
||||
String stn_loginNameMainCat = "KST4Contest";
|
||||
String stn_loginNameSecondCat = "KST4ContestSHF";
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package kst4contest.model;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Descriptor of one operator profile.
|
||||
*
|
||||
* <p>A profile always owns its own preferences file. Whether it also owns its own
|
||||
* worked-station database is decided by {@link #isSharedWorkedDatabase()}: a multi
|
||||
* operator contest station keeps one common log and therefore shares the database,
|
||||
* while two operators sharing a private computer usually want their worked data kept
|
||||
* apart.</p>
|
||||
*
|
||||
* <p>The descriptor deliberately carries no file paths. They are derived in exactly one
|
||||
* place, {@link kst4contest.controller.OperatorProfilePaths}, so a stored path can never
|
||||
* drift apart from the flag that produced it.</p>
|
||||
*/
|
||||
public class OperatorProfile {
|
||||
|
||||
/**
|
||||
* Stable identifier of the profile. It is assigned once and never changes, so
|
||||
* renaming a profile never moves a directory.
|
||||
*/
|
||||
private String profileId;
|
||||
|
||||
/**
|
||||
* Name shown in the profile picker and in the settings window.
|
||||
*/
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* True for the profile that uses the historic flat installation layout directly.
|
||||
*/
|
||||
private boolean rootProfile;
|
||||
|
||||
/**
|
||||
* True if this profile uses the common station worked-station database.
|
||||
*/
|
||||
private boolean sharedWorkedDatabase;
|
||||
|
||||
/**
|
||||
* Timestamp of the last activation, used to preselect an entry in the picker.
|
||||
*/
|
||||
private long lastUsedEpochMs;
|
||||
|
||||
public OperatorProfile() {
|
||||
// Default constructor for stepwise construction while reading the registry.
|
||||
}
|
||||
|
||||
public OperatorProfile(final String profileId,
|
||||
final String displayName,
|
||||
final boolean rootProfile,
|
||||
final boolean sharedWorkedDatabase) {
|
||||
this.profileId = profileId;
|
||||
this.displayName = displayName;
|
||||
this.rootProfile = rootProfile;
|
||||
this.sharedWorkedDatabase = sharedWorkedDatabase;
|
||||
}
|
||||
|
||||
public String getProfileId() {
|
||||
return profileId;
|
||||
}
|
||||
|
||||
public void setProfileId(final String profileId) {
|
||||
this.profileId = profileId;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(final String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public boolean isRootProfile() {
|
||||
return rootProfile;
|
||||
}
|
||||
|
||||
public void setRootProfile(final boolean rootProfile) {
|
||||
this.rootProfile = rootProfile;
|
||||
}
|
||||
|
||||
public boolean isSharedWorkedDatabase() {
|
||||
return sharedWorkedDatabase;
|
||||
}
|
||||
|
||||
public void setSharedWorkedDatabase(final boolean sharedWorkedDatabase) {
|
||||
this.sharedWorkedDatabase = sharedWorkedDatabase;
|
||||
}
|
||||
|
||||
public long getLastUsedEpochMs() {
|
||||
return lastUsedEpochMs;
|
||||
}
|
||||
|
||||
public void setLastUsedEpochMs(final long lastUsedEpochMs) {
|
||||
this.lastUsedEpochMs = lastUsedEpochMs;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(final Object other) {
|
||||
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(other instanceof OperatorProfile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return Objects.equals(profileId, ((OperatorProfile) other).profileId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hashCode(profileId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the display name so the descriptor can be shown in a list control directly.
|
||||
*
|
||||
* @return the display name, or the profile id when no name was set
|
||||
*/
|
||||
@Override
|
||||
public String toString() {
|
||||
|
||||
if (displayName == null || displayName.isBlank()) {
|
||||
return String.valueOf(profileId);
|
||||
}
|
||||
|
||||
return displayName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package kst4contest.model;
|
||||
|
||||
import kst4contest.ApplicationConstants;
|
||||
import kst4contest.utils.ApplicationFileUtils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Resolved runtime view of the active operator profile.
|
||||
*
|
||||
* <p>This is the only profile information the rest of the application needs: two file
|
||||
* names relative to the application directory plus the flag whether a missing
|
||||
* worked-station database may be seeded from the bundled template. Everything else is
|
||||
* derived from the descriptor.</p>
|
||||
*/
|
||||
public class OperatorProfileSelection {
|
||||
|
||||
private final OperatorProfile profile;
|
||||
private final String preferencesRelativeFileName;
|
||||
private final String workedDatabaseRelativeFileName;
|
||||
private final boolean seedWorkedDatabaseFromResource;
|
||||
|
||||
public OperatorProfileSelection(final OperatorProfile profile,
|
||||
final String preferencesRelativeFileName,
|
||||
final String workedDatabaseRelativeFileName,
|
||||
final boolean seedWorkedDatabaseFromResource) {
|
||||
this.profile = Objects.requireNonNull(profile, "profile");
|
||||
this.preferencesRelativeFileName =
|
||||
Objects.requireNonNull(preferencesRelativeFileName, "preferencesRelativeFileName");
|
||||
this.workedDatabaseRelativeFileName =
|
||||
Objects.requireNonNull(workedDatabaseRelativeFileName, "workedDatabaseRelativeFileName");
|
||||
this.seedWorkedDatabaseFromResource = seedWorkedDatabaseFromResource;
|
||||
}
|
||||
|
||||
public OperatorProfile getProfile() {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public String getPreferencesRelativeFileName() {
|
||||
return preferencesRelativeFileName;
|
||||
}
|
||||
|
||||
public String getWorkedDatabaseRelativeFileName() {
|
||||
return workedDatabaseRelativeFileName;
|
||||
}
|
||||
|
||||
public boolean isSeedWorkedDatabaseFromResource() {
|
||||
return seedWorkedDatabaseFromResource;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute preferences path, for display in the settings window.
|
||||
*
|
||||
* @return absolute path of the preferences file
|
||||
*/
|
||||
public String getPreferencesAbsolutePath() {
|
||||
return ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME, preferencesRelativeFileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the absolute worked-station database path, for display in the settings window.
|
||||
*
|
||||
* @return absolute path of the worked-station database
|
||||
*/
|
||||
public String getWorkedDatabaseAbsolutePath() {
|
||||
return ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME, workedDatabaseRelativeFileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.controller.ActiveOperatorProfile;
|
||||
import kst4contest.controller.OperatorProfilePaths;
|
||||
import kst4contest.controller.OperatorProfileStore;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
|
||||
import javafx.application.Platform;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.util.logging.Level;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
/**
|
||||
* Owns the lifecycle of the running application.
|
||||
*
|
||||
* <p>Switching the operator profile tears the current runtime down completely and builds
|
||||
* a fresh one in the same process. Rebinding the existing windows is not an option: the
|
||||
* user interface is built from the chat controller outwards, with several hundred
|
||||
* references to the active preferences, and many controls are instance fields created
|
||||
* once. A new {@link Kst4ContestApplication} instance gets fresh controls, which is safe
|
||||
* here because the class keeps no mutable static state.</p>
|
||||
*/
|
||||
public final class ApplicationRuntimeLauncher {
|
||||
|
||||
private static final Logger LOGGER = Logger.getLogger(ApplicationRuntimeLauncher.class.getName());
|
||||
|
||||
private static Kst4ContestApplication currentRuntime;
|
||||
|
||||
private ApplicationRuntimeLauncher() {
|
||||
// Utility class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the runtime that is currently live.
|
||||
*
|
||||
* @param runtime the running application instance
|
||||
*/
|
||||
public static void setCurrent(final Kst4ContestApplication runtime) {
|
||||
currentRuntime = runtime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the runtime that is currently live.
|
||||
*
|
||||
* @return the running application instance, or null before the first startup
|
||||
*/
|
||||
public static Kst4ContestApplication getCurrent() {
|
||||
return currentRuntime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuts the application down.
|
||||
*
|
||||
* <p>JavaFX only calls {@code stop()} on the instance it launched itself, so an exit
|
||||
* after a profile switch has to release the resources explicitly.</p>
|
||||
*/
|
||||
public static void exitApplication() {
|
||||
|
||||
if (currentRuntime != null) {
|
||||
currentRuntime.shutdownRuntime();
|
||||
}
|
||||
|
||||
Platform.exit();
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the running runtime with one bound to another operator profile.
|
||||
*
|
||||
* @param targetProfile profile to activate
|
||||
* @return true if the new runtime was built
|
||||
*/
|
||||
public static boolean switchProfile(final OperatorProfile targetProfile) {
|
||||
|
||||
if (targetProfile == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
new OperatorProfileStore().recordLastUsed(targetProfile.getProfileId());
|
||||
|
||||
if (currentRuntime != null) {
|
||||
currentRuntime.shutdownRuntime();
|
||||
}
|
||||
|
||||
ActiveOperatorProfile.set(OperatorProfilePaths.resolve(targetProfile));
|
||||
|
||||
Kst4ContestApplication nextRuntime = new Kst4ContestApplication();
|
||||
|
||||
try {
|
||||
nextRuntime.start(new Stage());
|
||||
} catch (Exception e) {
|
||||
// The previous runtime is already gone, so there is nothing left to return to.
|
||||
LOGGER.log(Level.SEVERE, "Could not start the selected operator profile", e);
|
||||
Kst4ContestApplication.alertWindowEvent(
|
||||
"The operator profile could not be started: " + e.getMessage()
|
||||
+ "\n\nKST4Contest has to be closed.");
|
||||
Platform.exit();
|
||||
System.exit(1);
|
||||
return false;
|
||||
}
|
||||
|
||||
setCurrent(nextRuntime);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Command line options of the application.
|
||||
*
|
||||
* <p>The parsed value is additionally kept in a process wide holder. JavaFX only knows
|
||||
* the parameters of the {@code Application} instance it launched itself, so an instance
|
||||
* created during a profile switch would see no parameters at all. Parsing once at
|
||||
* startup and remembering the result avoids that entirely.</p>
|
||||
*/
|
||||
public class CommandLineOptions {
|
||||
|
||||
/**
|
||||
* Command line switch selecting the operator profile to start with.
|
||||
*/
|
||||
public static final String PROFILE_ARGUMENT = "--profile";
|
||||
|
||||
/**
|
||||
* System property used as an alternative to the command line switch.
|
||||
*/
|
||||
public static final String PROFILE_SYSTEM_PROPERTY = "kst4contest.profile";
|
||||
|
||||
private static volatile CommandLineOptions rememberedOptions = new CommandLineOptions(null);
|
||||
|
||||
private final String requestedProfileName;
|
||||
|
||||
public CommandLineOptions(final String requestedProfileName) {
|
||||
this.requestedProfileName = requestedProfileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses the raw application arguments.
|
||||
*
|
||||
* <p>Unknown arguments are ignored on purpose. A typo in a command line must never
|
||||
* keep an operator out of the application shortly before a contest.</p>
|
||||
*
|
||||
* @param rawArguments raw arguments, may be null
|
||||
* @return the parsed options
|
||||
*/
|
||||
public static CommandLineOptions parse(final List<String> rawArguments) {
|
||||
|
||||
String requestedProfileName = null;
|
||||
|
||||
if (rawArguments != null) {
|
||||
for (int argumentIndex = 0; argumentIndex < rawArguments.size(); argumentIndex++) {
|
||||
String currentArgument = rawArguments.get(argumentIndex);
|
||||
|
||||
if (currentArgument == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (currentArgument.startsWith(PROFILE_ARGUMENT + "=")) {
|
||||
requestedProfileName = currentArgument.substring(PROFILE_ARGUMENT.length() + 1);
|
||||
} else if (PROFILE_ARGUMENT.equals(currentArgument)
|
||||
&& argumentIndex + 1 < rawArguments.size()) {
|
||||
requestedProfileName = rawArguments.get(argumentIndex + 1);
|
||||
argumentIndex++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (requestedProfileName == null || requestedProfileName.isBlank()) {
|
||||
requestedProfileName = System.getProperty(PROFILE_SYSTEM_PROPERTY);
|
||||
}
|
||||
|
||||
if (requestedProfileName != null && requestedProfileName.isBlank()) {
|
||||
requestedProfileName = null;
|
||||
}
|
||||
|
||||
return new CommandLineOptions(
|
||||
requestedProfileName == null ? null : requestedProfileName.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores the parsed options for the lifetime of the process.
|
||||
*
|
||||
* @param options options to remember
|
||||
*/
|
||||
public static void remember(final CommandLineOptions options) {
|
||||
rememberedOptions = options == null ? new CommandLineOptions(null) : options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the options parsed at application startup.
|
||||
*
|
||||
* @return the remembered options, never null
|
||||
*/
|
||||
public static CommandLineOptions remembered() {
|
||||
return rememberedOptions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the operator profile requested on the command line.
|
||||
*
|
||||
* @return the requested profile name, or null when none was given
|
||||
*/
|
||||
public String getRequestedProfileName() {
|
||||
return requestedProfileName;
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import java.util.logging.SimpleFormatter;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import javafx.animation.Animation;
|
||||
import javafx.animation.KeyFrame;
|
||||
import javafx.animation.Timeline;
|
||||
import javafx.collections.FXCollections;
|
||||
@@ -70,6 +71,12 @@ import javafx.stage.Screen;
|
||||
import kst4contest.logic.BandOpportunityResolver;
|
||||
import kst4contest.utils.ApplicationFileUtils;
|
||||
import kst4contest.view.map.StationMapBridge;
|
||||
import kst4contest.controller.ActiveOperatorProfile;
|
||||
import kst4contest.controller.OperatorProfileStore;
|
||||
import kst4contest.controller.OperatorProfileManagementService;
|
||||
import kst4contest.controller.OperatorProfilePaths;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
import kst4contest.view.map.StationMapView;
|
||||
import kst4contest.view.map.OfflineDemImportService;
|
||||
import kst4contest.controller.WorkedGrossFieldCache;
|
||||
@@ -5500,6 +5507,9 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
});
|
||||
|
||||
|
||||
MenuItem menuItemFileSwitchProfile = new MenuItem("Switch operator profile...");
|
||||
menuItemFileSwitchProfile.setOnAction(event -> showOperatorProfileSwitchDialog());
|
||||
|
||||
MenuItem m10 = new MenuItem("Exit + disconnect");
|
||||
m10.setOnAction(new EventHandler<ActionEvent>() {
|
||||
public void handle(ActionEvent event) {
|
||||
@@ -5510,6 +5520,7 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
// add menu items to menu
|
||||
fileMenu.getItems().add(menuItemFileConnect);
|
||||
fileMenu.getItems().add(menuItemFileDisconnect);
|
||||
fileMenu.getItems().add(menuItemFileSwitchProfile);
|
||||
fileMenu.getItems().add(m10);
|
||||
|
||||
Menu optionsMenu = new Menu("Options");
|
||||
@@ -5753,7 +5764,8 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
Alert a = new Alert(AlertType.INFORMATION);
|
||||
|
||||
a.setTitle("About kst4contest");
|
||||
a.setHeaderText("kst4Contest " + ApplicationConstants.APPLICATION_CURRENT_VERSION + ": ON4KST Chatclient by DO5AMF");
|
||||
a.setHeaderText("kst4Contest " + ApplicationConstants.APPLICATION_CURRENT_VERSION
|
||||
+ ": ON4KST Chatclient by DO5AMF and DN9APW");
|
||||
a.setContentText(chatcontroller.getChatPreferences().getProgramVersion());
|
||||
a.show();
|
||||
}
|
||||
@@ -6095,6 +6107,17 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
FlowPane flwPane_textSnippets;
|
||||
FlowPane flwpne_StatusBar;
|
||||
|
||||
/**
|
||||
* True once this runtime released its resources. Shutdown must stay idempotent
|
||||
* because it is reached both through the JavaFX stop() callback and explicitly.
|
||||
*/
|
||||
private boolean runtimeShutdownDone;
|
||||
|
||||
/**
|
||||
* The primary stage of this runtime, remembered so shutdown can close it.
|
||||
*/
|
||||
private Stage ownPrimaryStage;
|
||||
|
||||
Stage clusterAndQSOMonStage;
|
||||
// Stage stage_selectedCallSignInfoStage;
|
||||
ChatMember selectedCallSignInfoStageChatMember;
|
||||
@@ -6226,29 +6249,264 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
return txMessageButtons;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the operator profile this runtime works with.
|
||||
*
|
||||
* <p>Only executed on the very first launch. A profile switch sets the profile before
|
||||
* building the new runtime, so the resolution is skipped there.</p>
|
||||
*
|
||||
* <p>An installation with no or exactly one profile is resolved without asking
|
||||
* anything, which keeps the single operator startup exactly as it was.</p>
|
||||
*
|
||||
* @return true if the application may continue starting up
|
||||
*/
|
||||
private boolean resolveOperatorProfileIfRequired() {
|
||||
|
||||
if (ActiveOperatorProfile.isInitialized()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
OperatorProfileBootstrap bootstrap = new OperatorProfileBootstrap();
|
||||
OperatorProfileSelection resolvedProfile = bootstrap.resolveAtStartup(
|
||||
new OperatorProfileStore(),
|
||||
CommandLineOptions.remembered(),
|
||||
OperatorProfilePickerDialog::showAndSelect);
|
||||
|
||||
if (bootstrap.getStartupWarning() != null) {
|
||||
Alert startupWarning = new Alert(AlertType.WARNING);
|
||||
startupWarning.setTitle("Operator profile");
|
||||
startupWarning.setHeaderText("The requested operator profile was not found.");
|
||||
startupWarning.setContentText(bootstrap.getStartupWarning());
|
||||
startupWarning.showAndWait();
|
||||
}
|
||||
|
||||
if (resolvedProfile == null) {
|
||||
Platform.exit();
|
||||
System.exit(0);
|
||||
return false;
|
||||
}
|
||||
|
||||
ActiveOperatorProfile.set(resolvedProfile);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the window title suffix naming the active operator profile.
|
||||
*
|
||||
* <p>Empty for the historic single profile installation, so nothing changes visually
|
||||
* for operators who never create a second profile.</p>
|
||||
*
|
||||
* @return the suffix to append to a window title, never null
|
||||
*/
|
||||
private String buildOperatorProfileTitleSuffix() {
|
||||
|
||||
OperatorProfileSelection activeProfile = ActiveOperatorProfile.get();
|
||||
|
||||
if (activeProfile == null || activeProfile.getProfile().isRootProfile()) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return " - " + activeProfile.getProfile().getDisplayName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets the operator pick another profile and rebuilds the runtime for it.
|
||||
*
|
||||
* <p>Offers to create a second profile when only one exists, because the menu entry
|
||||
* is the discoverable place to find the feature at all.</p>
|
||||
*/
|
||||
private void showOperatorProfileSwitchDialog() {
|
||||
|
||||
OperatorProfileStore profileStore = new OperatorProfileStore();
|
||||
List<OperatorProfile> selectableProfiles = profileStore.loadProfiles();
|
||||
|
||||
if (selectableProfiles.size() < 2) {
|
||||
Alert noProfilesYet = new Alert(AlertType.INFORMATION);
|
||||
noProfilesYet.setTitle("Operator profiles");
|
||||
noProfilesYet.setHeaderText("Only one operator profile is configured.");
|
||||
noProfilesYet.setContentText(
|
||||
"Additional profiles are created in the settings window on the "
|
||||
+ "\"Profiles\" tab. Each profile keeps its own settings and layout, "
|
||||
+ "and can either share the station worked database or use its own.");
|
||||
noProfilesYet.showAndWait();
|
||||
return;
|
||||
}
|
||||
|
||||
OperatorProfileSelection activeProfile = ActiveOperatorProfile.get();
|
||||
String activeProfileId = activeProfile == null ? null : activeProfile.getProfile().getProfileId();
|
||||
|
||||
Optional<OperatorProfile> chosenProfile =
|
||||
OperatorProfilePickerDialog.showAndSelect(selectableProfiles, activeProfileId);
|
||||
|
||||
if (chosenProfile.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (chosenProfile.get().getProfileId().equalsIgnoreCase(activeProfileId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
requestOperatorProfileSwitch(chosenProfile.get());
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirms and performs a switch to another operator profile.
|
||||
*
|
||||
* <p>Shared by the File menu and the profile settings tab, so both ask the same
|
||||
* question before giving up the running session.</p>
|
||||
*
|
||||
* @param targetProfile profile to activate
|
||||
*/
|
||||
private void requestOperatorProfileSwitch(OperatorProfile targetProfile) {
|
||||
|
||||
if (targetProfile == null || !confirmOperatorProfileSwitch(targetProfile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ApplicationRuntimeLauncher.switchProfile(targetProfile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks whether the running session may be given up for a profile switch.
|
||||
*
|
||||
* @param targetProfile profile the operator selected
|
||||
* @return true if the switch may proceed
|
||||
*/
|
||||
private boolean confirmOperatorProfileSwitch(OperatorProfile targetProfile) {
|
||||
|
||||
Alert confirmation = new Alert(AlertType.CONFIRMATION);
|
||||
confirmation.setTitle("Switch operator profile");
|
||||
confirmation.setHeaderText("Switch to \"" + targetProfile.getDisplayName() + "\"?");
|
||||
confirmation.setContentText(
|
||||
"The ON4KST connection is closed and all windows are rebuilt with the "
|
||||
+ "settings and layout of the selected profile.\n\n"
|
||||
+ "Unsaved settings of the current profile are lost. Window sizes, "
|
||||
+ "divider and column widths are saved automatically.");
|
||||
|
||||
ButtonType switchButton = new ButtonType("Switch profile", ButtonBar.ButtonData.OK_DONE);
|
||||
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
|
||||
confirmation.getButtonTypes().setAll(switchButton, cancelButton);
|
||||
|
||||
return confirmation.showAndWait().orElse(cancelButton) == switchButton;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
System.out.println("[Main.java, Info:] Stage is closing, killing all resources");
|
||||
if (layoutAutosave != null) {
|
||||
layoutAutosave.flushPending();
|
||||
shutdownRuntime();
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every resource this runtime owns, without terminating the process.
|
||||
*
|
||||
* <p>Separated from {@link #stop()} so the same teardown can be reused when the
|
||||
* operator switches to another profile and a fresh runtime is built afterwards.
|
||||
* The method is idempotent and tolerates a runtime that never connected, because a
|
||||
* switch may happen before the first login.</p>
|
||||
*/
|
||||
public void shutdownRuntime() {
|
||||
|
||||
if (runtimeShutdownDone) {
|
||||
return;
|
||||
}
|
||||
timer_buildWindowTitle.purge();
|
||||
timer_buildWindowTitle.cancel();
|
||||
|
||||
runtimeShutdownDone = true;
|
||||
|
||||
System.out.println("[Main.java, Info:] Stage is closing, killing all resources");
|
||||
|
||||
if (layoutAutosave != null) {
|
||||
// Flush before cancelling, otherwise a pending debounced write would either
|
||||
// be lost or land after a profile switch.
|
||||
layoutAutosave.flushPending();
|
||||
layoutAutosave.cancelPending();
|
||||
}
|
||||
|
||||
cancelViewTimer(timer_buildWindowTitle);
|
||||
timer_buildWindowTitle = null;
|
||||
|
||||
// timer_chatMemberTableSortTimer.purge();
|
||||
// timer_chatMemberTableSortTimer.cancel();
|
||||
|
||||
timer_updatePrivatemessageTable.purge();
|
||||
timer_updatePrivatemessageTable.cancel();
|
||||
cancelViewTimer(timer_updatePrivatemessageTable);
|
||||
timer_updatePrivatemessageTable = null;
|
||||
|
||||
stopAnimation(userListRefreshCoalescer);
|
||||
userListRefreshCoalescer = null;
|
||||
stopAnimation(skedWarnBlinkTimeline);
|
||||
skedWarnBlinkTimeline = null;
|
||||
stopAnimation(bandUpgradeBlinkTimeline);
|
||||
bandUpgradeBlinkTimeline = null;
|
||||
|
||||
if (stationMapBridge != null) {
|
||||
stationMapBridge.uninstall();
|
||||
stationMapBridge = null;
|
||||
}
|
||||
|
||||
if (stationMapView != null) {
|
||||
stationMapView.dispose();
|
||||
stationMapView = null;
|
||||
}
|
||||
|
||||
closeOwnedStages();
|
||||
|
||||
try {
|
||||
chatcontroller.disconnect("CLOSEALL");
|
||||
if (chatcontroller != null) {
|
||||
chatcontroller.disconnect(ApplicationConstants.DISCSTRING_DISCONNECT_AND_CLOSE);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.out.println("[Main.java, Warning:] Exception during disconnect: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Platform.exit();
|
||||
System.exit(0);
|
||||
/**
|
||||
* Cancels a timer created during user interface construction.
|
||||
*
|
||||
* @param timerToCancel timer to cancel, may be null when startup did not get that far
|
||||
*/
|
||||
private static void cancelViewTimer(Timer timerToCancel) {
|
||||
|
||||
if (timerToCancel == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
timerToCancel.purge();
|
||||
timerToCancel.cancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a JavaFX animation if it exists.
|
||||
*
|
||||
* @param animationToStop animation to stop, may be null
|
||||
*/
|
||||
private static void stopAnimation(Animation animationToStop) {
|
||||
|
||||
if (animationToStop != null) {
|
||||
animationToStop.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes every window this runtime opened, so no stale window survives a profile
|
||||
* switch. The map window is closed by its own dispose method.
|
||||
*/
|
||||
private void closeOwnedStages() {
|
||||
|
||||
for (Stage ownedStage : new Stage[] {
|
||||
settingsStage, clusterAndQSOMonStage, stage_updateStage, ownPrimaryStage }) {
|
||||
|
||||
if (ownedStage != null) {
|
||||
try {
|
||||
ownedStage.close();
|
||||
} catch (Exception e) {
|
||||
System.out.println("[Main.java, Warning:] Could not close a window: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
settingsStage = null;
|
||||
clusterAndQSOMonStage = null;
|
||||
stage_updateStage = null;
|
||||
ownPrimaryStage = null;
|
||||
}
|
||||
|
||||
private void requestLayoutSave() {
|
||||
@@ -6643,9 +6901,36 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
|
||||
Parameters applicationParameters = getParameters();
|
||||
|
||||
CommandLineOptions.remember(CommandLineOptions.parse(
|
||||
applicationParameters == null ? null : applicationParameters.getRaw()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) throws InterruptedException, IOException, URISyntaxException {
|
||||
|
||||
if (!resolveOperatorProfileIfRequired()) {
|
||||
return;
|
||||
}
|
||||
|
||||
ownPrimaryStage = primaryStage;
|
||||
|
||||
/*
|
||||
* A profile switch closes every window of the old runtime before the new one
|
||||
* exists. With the JavaFX default that would end the process, so the application
|
||||
* takes over the exit decision and closing the main window is handled explicitly.
|
||||
*/
|
||||
Platform.setImplicitExit(false);
|
||||
primaryStage.setOnCloseRequest(closeRequest -> {
|
||||
closeRequest.consume();
|
||||
ApplicationRuntimeLauncher.exitApplication();
|
||||
});
|
||||
ApplicationRuntimeLauncher.setCurrent(this);
|
||||
|
||||
GuiUtils.applyApplicationIcon(primaryStage);
|
||||
|
||||
VBox pnl_inputAndSendButtons = new VBox(); //gets the sendtext field, send button and the timeline
|
||||
@@ -6680,8 +6965,15 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, STYLE_DEFAULTCSSDAY_RESOURCE, STYLE_DEFAULTCSSDAY_FILE);
|
||||
ApplicationFileUtils.copyResourceIfRequired(ApplicationConstants.APPLICATION_NAME, STYLE_DEFAULTCSSEVENING_RESOURCE, STYLE_DEFAULTCSSEVENING_FILE);
|
||||
ChatMember ownChatMemberObject = new ChatMember();
|
||||
OperatorProfileSelection activeOperatorProfile = ActiveOperatorProfile.get();
|
||||
|
||||
chatcontroller = new ChatController(ownChatMemberObject, this); // instantiate the Chatcontroller with the user object
|
||||
// instantiate the Chatcontroller with the user object and the files of the active profile
|
||||
chatcontroller = new ChatController(
|
||||
ownChatMemberObject,
|
||||
this,
|
||||
activeOperatorProfile.getPreferencesRelativeFileName(),
|
||||
activeOperatorProfile.getWorkedDatabaseRelativeFileName(),
|
||||
activeOperatorProfile.isSeedWorkedDatabaseFromResource());
|
||||
layoutAutosave = new LayoutAutosave(chatcontroller.getChatPreferences());
|
||||
messageVariableResolver = new MessageVariableResolver(chatcontroller.getChatPreferences());
|
||||
chatcontroller.setStatusListener(this); //callback interface for updating Thread events in visual
|
||||
@@ -7199,7 +7491,7 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
txt_ownqrgSecondCategory.setFocusTraversable(false);
|
||||
txt_ownqrgSecondCategory.setTooltip(new Tooltip("Enter frequency for second chat-category here by hand! <fixme>"));
|
||||
|
||||
primaryStage.setTitle(chatcontroller.getChatPreferences().getChatState());
|
||||
primaryStage.setTitle(chatcontroller.getChatPreferences().getChatState() + buildOperatorProfileTitleSuffix());
|
||||
|
||||
timer_buildWindowTitle = new Timer();
|
||||
timer_buildWindowTitle.scheduleAtFixedRate(new TimerTask() {
|
||||
@@ -7254,7 +7546,7 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
chatcontroller.getChatPreferences().setChatState(chatState);
|
||||
}
|
||||
|
||||
primaryStage.setTitle(chatcontroller.getChatPreferences().getChatState());
|
||||
primaryStage.setTitle(chatcontroller.getChatPreferences().getChatState() + buildOperatorProfileTitleSuffix());
|
||||
|
||||
// System.out.println(chatcontroller.getChatPreferences().getChatState());
|
||||
});
|
||||
@@ -11750,6 +12042,14 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
Tab tbInternalDB = new Tab("Workedstn database", vbxInternalDB);
|
||||
Tab tbGui = new Tab("GUI", vbxGuiOptions);
|
||||
|
||||
/*
|
||||
* Appended last on purpose so no established tab position shifts. Contest
|
||||
* operators navigate these tabs by muscle memory.
|
||||
*/
|
||||
Tab tbProfiles = new Tab("Profiles", new OperatorProfileSettingsPane(
|
||||
new OperatorProfileManagementService(),
|
||||
this::requestOperatorProfileSwitch));
|
||||
|
||||
|
||||
/**
|
||||
* Automatic update of tab contents out of the database
|
||||
@@ -11765,7 +12065,7 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
|
||||
|
||||
tabPaneOptions.getTabs().addAll(tbStationSettings, tbLogSynchSet, tbTRXSynchSet, tbAirScoutSettings, tbNotify,
|
||||
tbShorts, tbBeacon, tbMsgHandling, tbInternalDB, tbGui);
|
||||
tbShorts, tbBeacon, tbMsgHandling, tbInternalDB, tbGui, tbProfiles);
|
||||
|
||||
optionsPanel.setLeft(tabPaneOptions);
|
||||
|
||||
@@ -12177,10 +12477,12 @@ public class Kst4ContestApplication extends Application implements StatusUpdateL
|
||||
if (res.get().equals(ButtonType.CANCEL)) {
|
||||
// event.consume();
|
||||
} else {
|
||||
System.out.println("closewindowevent: Platform.exit");
|
||||
System.out.println("closewindowevent: exiting the application");
|
||||
|
||||
|
||||
Platform.exit();
|
||||
// Routed through the launcher so the runtime that is actually live
|
||||
// releases its resources. After a profile switch that is no longer the
|
||||
// instance JavaFX would call stop() on.
|
||||
ApplicationRuntimeLauncher.exitApplication();
|
||||
}
|
||||
}
|
||||
// }
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.controller.OperatorProfilePaths;
|
||||
import kst4contest.controller.OperatorProfileStore;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Decides which operator profile the application starts with.
|
||||
*
|
||||
* <p>The class contains no user interface code so the decision can be tested headless.
|
||||
* Asking the operator is delegated to an {@link OperatorProfileChoiceRequester}, and a
|
||||
* problem worth telling the operator about is reported through
|
||||
* {@link #getStartupWarning()} instead of being shown here.</p>
|
||||
*
|
||||
* <p>The most important property of this logic is what it does <em>not</em> do: an
|
||||
* installation with no or exactly one profile is resolved without asking anything and
|
||||
* without touching a single file, so a single operator start stays exactly as fast and
|
||||
* as quiet as it was before profiles existed.</p>
|
||||
*/
|
||||
public class OperatorProfileBootstrap {
|
||||
|
||||
private String startupWarning;
|
||||
|
||||
/**
|
||||
* Resolves the operator profile to start with.
|
||||
*
|
||||
* @param store registry to read the profiles from
|
||||
* @param commandLineOptions parsed command line options
|
||||
* @param choiceRequester requester used when the operator has to choose
|
||||
* @return the resolved selection, or null when the operator chose to quit
|
||||
*/
|
||||
public OperatorProfileSelection resolveAtStartup(final OperatorProfileStore store,
|
||||
final CommandLineOptions commandLineOptions,
|
||||
final OperatorProfileChoiceRequester choiceRequester) {
|
||||
|
||||
startupWarning = null;
|
||||
|
||||
List<OperatorProfile> availableProfiles = store.loadProfiles();
|
||||
String requestedProfileName = commandLineOptions == null
|
||||
? null
|
||||
: commandLineOptions.getRequestedProfileName();
|
||||
|
||||
if (requestedProfileName != null) {
|
||||
OperatorProfile requestedProfile = findProfile(availableProfiles, requestedProfileName);
|
||||
|
||||
if (requestedProfile != null) {
|
||||
return OperatorProfilePaths.resolve(requestedProfile);
|
||||
}
|
||||
|
||||
startupWarning = "The operator profile \"" + requestedProfileName
|
||||
+ "\" is unknown. KST4Contest continues with the normal profile selection.";
|
||||
}
|
||||
|
||||
if (availableProfiles.isEmpty()) {
|
||||
// No registry at all: the historic flat installation is the only profile.
|
||||
return OperatorProfilePaths.resolve(store.buildImplicitRootProfile());
|
||||
}
|
||||
|
||||
if (availableProfiles.size() == 1) {
|
||||
return OperatorProfilePaths.resolve(availableProfiles.get(0));
|
||||
}
|
||||
|
||||
String preselectedProfileId = store.loadLastUsedProfileId().orElse(null);
|
||||
Optional<OperatorProfile> chosenProfile =
|
||||
choiceRequester.requestProfileChoice(availableProfiles, preselectedProfileId);
|
||||
|
||||
return chosenProfile.map(OperatorProfilePaths::resolve).orElse(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a message that should be shown to the operator after startup.
|
||||
*
|
||||
* @return the warning text, or null when startup was unremarkable
|
||||
*/
|
||||
public String getStartupWarning() {
|
||||
return startupWarning;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds a profile by identifier or display name, ignoring case.
|
||||
*
|
||||
* @param availableProfiles profiles to search
|
||||
* @param requestedName identifier or display name entered by the operator
|
||||
* @return the matching profile, or null
|
||||
*/
|
||||
private static OperatorProfile findProfile(final List<OperatorProfile> availableProfiles,
|
||||
final String requestedName) {
|
||||
|
||||
for (OperatorProfile currentProfile : availableProfiles) {
|
||||
if (requestedName.equalsIgnoreCase(currentProfile.getProfileId())) {
|
||||
return currentProfile;
|
||||
}
|
||||
}
|
||||
|
||||
for (OperatorProfile currentProfile : availableProfiles) {
|
||||
if (requestedName.equalsIgnoreCase(currentProfile.getDisplayName())) {
|
||||
return currentProfile;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.model.OperatorProfile;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Asks the operator which profile to start with.
|
||||
*
|
||||
* <p>The startup logic depends on this interface rather than on a dialog, so the
|
||||
* decision which profile to use can be tested without a JavaFX runtime.</p>
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface OperatorProfileChoiceRequester {
|
||||
|
||||
/**
|
||||
* Requests a profile choice.
|
||||
*
|
||||
* @param selectableProfiles profiles to choose from, never empty
|
||||
* @param preselectedProfileId identifier to preselect, may be null
|
||||
* @return the chosen profile, or empty when the operator wants to quit
|
||||
*/
|
||||
Optional<OperatorProfile> requestProfileChoice(List<OperatorProfile> selectableProfiles,
|
||||
String preselectedProfileId);
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.model.OperatorProfile;
|
||||
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.Scene;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.ListCell;
|
||||
import javafx.scene.control.ListView;
|
||||
import javafx.scene.input.KeyCode;
|
||||
import javafx.scene.input.MouseButton;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.stage.Modality;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Asks the operator which profile to start with.
|
||||
*
|
||||
* <p>The dialog is shown only when more than one profile exists. It is intentionally
|
||||
* minimal, because it stands between the operator and a contest: the last used profile
|
||||
* is preselected, the list has the focus, and Enter or a double click start immediately.</p>
|
||||
*/
|
||||
public final class OperatorProfilePickerDialog {
|
||||
|
||||
private OperatorProfilePickerDialog() {
|
||||
// Utility class.
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows the picker and waits for the operator's choice.
|
||||
*
|
||||
* @param selectableProfiles profiles to choose from
|
||||
* @param preselectedProfileId identifier of the profile to preselect, may be null
|
||||
* @return the chosen profile, or empty when the operator wants to quit
|
||||
*/
|
||||
public static Optional<OperatorProfile> showAndSelect(final List<OperatorProfile> selectableProfiles,
|
||||
final String preselectedProfileId) {
|
||||
|
||||
Stage dialogStage = new Stage();
|
||||
GuiUtils.applyApplicationIcon(dialogStage);
|
||||
dialogStage.initModality(Modality.APPLICATION_MODAL);
|
||||
dialogStage.setTitle("Select operator profile");
|
||||
|
||||
ListView<OperatorProfile> profileListView = new ListView<>();
|
||||
profileListView.getItems().addAll(selectableProfiles);
|
||||
profileListView.setCellFactory(listView -> new OperatorProfileListCell());
|
||||
VBox.setVgrow(profileListView, Priority.ALWAYS);
|
||||
|
||||
selectPreselectedProfile(profileListView, selectableProfiles, preselectedProfileId);
|
||||
|
||||
OperatorProfile[] chosenProfile = new OperatorProfile[1];
|
||||
|
||||
Button startButton = new Button("Start");
|
||||
startButton.setDefaultButton(true);
|
||||
startButton.setOnAction(event -> {
|
||||
chosenProfile[0] = profileListView.getSelectionModel().getSelectedItem();
|
||||
dialogStage.close();
|
||||
});
|
||||
|
||||
Button quitButton = new Button("Quit");
|
||||
quitButton.setCancelButton(true);
|
||||
quitButton.setOnAction(event -> {
|
||||
chosenProfile[0] = null;
|
||||
dialogStage.close();
|
||||
});
|
||||
|
||||
profileListView.setOnMouseClicked(event -> {
|
||||
if (event.getButton() == MouseButton.PRIMARY && event.getClickCount() == 2) {
|
||||
startButton.fire();
|
||||
}
|
||||
});
|
||||
|
||||
profileListView.setOnKeyPressed(event -> {
|
||||
if (event.getCode() == KeyCode.ENTER) {
|
||||
startButton.fire();
|
||||
}
|
||||
});
|
||||
|
||||
HBox buttonRow = new HBox(10, startButton, quitButton);
|
||||
buttonRow.setPadding(new Insets(10, 0, 0, 0));
|
||||
|
||||
VBox dialogContent = new VBox(8,
|
||||
new Label("More than one operator profile is configured."),
|
||||
profileListView,
|
||||
buttonRow);
|
||||
dialogContent.setPadding(new Insets(15));
|
||||
|
||||
dialogStage.setScene(new Scene(dialogContent, 380, 280));
|
||||
profileListView.requestFocus();
|
||||
dialogStage.showAndWait();
|
||||
|
||||
return Optional.ofNullable(chosenProfile[0]);
|
||||
}
|
||||
|
||||
private static void selectPreselectedProfile(final ListView<OperatorProfile> profileListView,
|
||||
final List<OperatorProfile> selectableProfiles,
|
||||
final String preselectedProfileId) {
|
||||
|
||||
int profileIndexToSelect = 0;
|
||||
|
||||
if (preselectedProfileId != null) {
|
||||
for (int profileIndex = 0; profileIndex < selectableProfiles.size(); profileIndex++) {
|
||||
if (preselectedProfileId.equalsIgnoreCase(
|
||||
selectableProfiles.get(profileIndex).getProfileId())) {
|
||||
profileIndexToSelect = profileIndex;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
profileListView.getSelectionModel().select(profileIndexToSelect);
|
||||
profileListView.scrollTo(profileIndexToSelect);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a profile with its name and the kind of worked data it uses.
|
||||
*/
|
||||
private static final class OperatorProfileListCell extends ListCell<OperatorProfile> {
|
||||
|
||||
@Override
|
||||
protected void updateItem(final OperatorProfile profile, final boolean empty) {
|
||||
|
||||
super.updateItem(profile, empty);
|
||||
|
||||
if (empty || profile == null) {
|
||||
setText(null);
|
||||
return;
|
||||
}
|
||||
|
||||
String workedDataDescription = profile.isRootProfile() || profile.isSharedWorkedDatabase()
|
||||
? "shared station worked database"
|
||||
: "own worked database";
|
||||
|
||||
setText(profile.getDisplayName() + "\n" + workedDataDescription);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.controller.ActiveOperatorProfile;
|
||||
import kst4contest.controller.OperatorProfileManagementService;
|
||||
import kst4contest.controller.OperatorProfilePaths;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
|
||||
import javafx.beans.property.SimpleStringProperty;
|
||||
import javafx.geometry.Insets;
|
||||
import javafx.scene.control.Alert;
|
||||
import javafx.scene.control.Alert.AlertType;
|
||||
import javafx.scene.control.Button;
|
||||
import javafx.scene.control.ButtonBar;
|
||||
import javafx.scene.control.ButtonType;
|
||||
import javafx.scene.control.Dialog;
|
||||
import javafx.scene.control.Label;
|
||||
import javafx.scene.control.RadioButton;
|
||||
import javafx.scene.control.TableColumn;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.scene.control.TextField;
|
||||
import javafx.scene.control.TextInputDialog;
|
||||
import javafx.scene.control.ToggleGroup;
|
||||
import javafx.scene.layout.GridPane;
|
||||
import javafx.scene.layout.HBox;
|
||||
import javafx.scene.layout.Priority;
|
||||
import javafx.scene.layout.VBox;
|
||||
import javafx.util.Pair;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/**
|
||||
* Settings tab that manages the operator profiles.
|
||||
*
|
||||
* <p>Every profile keeps its own settings and window layout. Whether it also keeps its
|
||||
* own worked stations is chosen per profile, because a multi operator contest station
|
||||
* shares one log while two operators on a private computer usually do not.</p>
|
||||
*/
|
||||
public class OperatorProfileSettingsPane extends VBox {
|
||||
|
||||
private static final DateTimeFormatter LAST_USED_FORMATTER =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").withZone(ZoneId.systemDefault());
|
||||
|
||||
private final OperatorProfileManagementService managementService;
|
||||
private final Consumer<OperatorProfile> profileActivationRequest;
|
||||
|
||||
private final TableView<OperatorProfile> profileTable = new TableView<>();
|
||||
private final Label activeProfileLabel = new Label();
|
||||
private final Label preferencesPathLabel = new Label();
|
||||
private final Label workedDatabasePathLabel = new Label();
|
||||
|
||||
public OperatorProfileSettingsPane(final OperatorProfileManagementService managementService,
|
||||
final Consumer<OperatorProfile> profileActivationRequest) {
|
||||
|
||||
this.managementService = managementService;
|
||||
this.profileActivationRequest = profileActivationRequest;
|
||||
|
||||
setSpacing(10);
|
||||
setPadding(new Insets(15));
|
||||
|
||||
getChildren().addAll(
|
||||
buildActiveProfileHeader(),
|
||||
buildProfileTable(),
|
||||
buildButtonRows(),
|
||||
buildExplanationLabel());
|
||||
|
||||
refreshActiveProfileHeader();
|
||||
refreshProfileTable();
|
||||
}
|
||||
|
||||
private GridPane buildActiveProfileHeader() {
|
||||
|
||||
GridPane headerGrid = new GridPane();
|
||||
headerGrid.setHgap(10);
|
||||
headerGrid.setVgap(4);
|
||||
|
||||
headerGrid.add(new Label("Active profile:"), 0, 0);
|
||||
headerGrid.add(activeProfileLabel, 1, 0);
|
||||
headerGrid.add(new Label("Settings file:"), 0, 1);
|
||||
headerGrid.add(preferencesPathLabel, 1, 1);
|
||||
headerGrid.add(new Label("Worked stations:"), 0, 2);
|
||||
headerGrid.add(workedDatabasePathLabel, 1, 2);
|
||||
|
||||
return headerGrid;
|
||||
}
|
||||
|
||||
private TableView<OperatorProfile> buildProfileTable() {
|
||||
|
||||
TableColumn<OperatorProfile, String> nameColumn = new TableColumn<>("Profile");
|
||||
nameColumn.setCellValueFactory(cellData ->
|
||||
new SimpleStringProperty(cellData.getValue().getDisplayName()));
|
||||
nameColumn.setPrefWidth(200);
|
||||
|
||||
TableColumn<OperatorProfile, String> workedDataColumn = new TableColumn<>("Worked stations");
|
||||
workedDataColumn.setCellValueFactory(cellData ->
|
||||
new SimpleStringProperty(describeWorkedDataMode(cellData.getValue())));
|
||||
workedDataColumn.setPrefWidth(200);
|
||||
|
||||
TableColumn<OperatorProfile, String> lastUsedColumn = new TableColumn<>("Last used");
|
||||
lastUsedColumn.setCellValueFactory(cellData ->
|
||||
new SimpleStringProperty(describeLastUsed(cellData.getValue())));
|
||||
lastUsedColumn.setPrefWidth(140);
|
||||
|
||||
profileTable.getColumns().add(nameColumn);
|
||||
profileTable.getColumns().add(workedDataColumn);
|
||||
profileTable.getColumns().add(lastUsedColumn);
|
||||
profileTable.setPlaceholder(new Label("No operator profile configured."));
|
||||
|
||||
VBox.setVgrow(profileTable, Priority.ALWAYS);
|
||||
|
||||
return profileTable;
|
||||
}
|
||||
|
||||
private VBox buildButtonRows() {
|
||||
|
||||
Button newProfileButton = new Button("New profile...");
|
||||
newProfileButton.setOnAction(event -> createProfile());
|
||||
|
||||
Button duplicateProfileButton = new Button("Duplicate...");
|
||||
duplicateProfileButton.setOnAction(event -> duplicateSelectedProfile());
|
||||
|
||||
Button renameProfileButton = new Button("Rename...");
|
||||
renameProfileButton.setOnAction(event -> renameSelectedProfile());
|
||||
|
||||
Button deleteProfileButton = new Button("Delete...");
|
||||
deleteProfileButton.setOnAction(event -> deleteSelectedProfile());
|
||||
|
||||
Button changeWorkedDataButton = new Button("Change worked stations...");
|
||||
changeWorkedDataButton.setOnAction(event -> changeWorkedDataModeOfSelectedProfile());
|
||||
|
||||
Button switchProfileButton = new Button("Switch to selected profile...");
|
||||
switchProfileButton.setOnAction(event -> activateSelectedProfile());
|
||||
|
||||
HBox managementRow = new HBox(8,
|
||||
newProfileButton, duplicateProfileButton, renameProfileButton, deleteProfileButton);
|
||||
HBox activationRow = new HBox(8, changeWorkedDataButton, switchProfileButton);
|
||||
|
||||
return new VBox(8, managementRow, activationRow);
|
||||
}
|
||||
|
||||
private Label buildExplanationLabel() {
|
||||
|
||||
Label explanation = new Label(
|
||||
"Each profile has its own settings and window layout. A profile can either share the "
|
||||
+ "common station worked stations, which is what a multi operator station wants, "
|
||||
+ "or keep its own. Duplicating a profile copies everything except callsign and "
|
||||
+ "password, and never copies worked stations.");
|
||||
explanation.setWrapText(true);
|
||||
|
||||
return explanation;
|
||||
}
|
||||
|
||||
private void refreshActiveProfileHeader() {
|
||||
|
||||
OperatorProfileSelection activeProfile = ActiveOperatorProfile.get();
|
||||
|
||||
if (activeProfile == null) {
|
||||
activeProfileLabel.setText("unknown");
|
||||
return;
|
||||
}
|
||||
|
||||
activeProfileLabel.setText(activeProfile.getProfile().getDisplayName());
|
||||
preferencesPathLabel.setText(activeProfile.getPreferencesAbsolutePath());
|
||||
workedDatabasePathLabel.setText(activeProfile.getWorkedDatabaseAbsolutePath());
|
||||
}
|
||||
|
||||
private void refreshProfileTable() {
|
||||
|
||||
List<OperatorProfile> knownProfiles = managementService.listProfiles();
|
||||
OperatorProfile previouslySelected = profileTable.getSelectionModel().getSelectedItem();
|
||||
|
||||
profileTable.getItems().setAll(knownProfiles);
|
||||
|
||||
if (previouslySelected != null && knownProfiles.contains(previouslySelected)) {
|
||||
profileTable.getSelectionModel().select(previouslySelected);
|
||||
} else if (!knownProfiles.isEmpty()) {
|
||||
profileTable.getSelectionModel().select(0);
|
||||
}
|
||||
}
|
||||
|
||||
private void createProfile() {
|
||||
|
||||
Optional<Pair<String, Boolean>> enteredProfile =
|
||||
showProfileCreationDialog("New operator profile", "");
|
||||
|
||||
if (enteredProfile.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile(
|
||||
enteredProfile.get().getKey(), enteredProfile.get().getValue());
|
||||
|
||||
if (createdProfile == null) {
|
||||
showError("The profile could not be created. The profile registry could not be written.");
|
||||
return;
|
||||
}
|
||||
|
||||
refreshProfileTable();
|
||||
profileTable.getSelectionModel().select(createdProfile);
|
||||
|
||||
showInformation("The profile \"" + createdProfile.getDisplayName() + "\" was created without "
|
||||
+ "callsign and password. Enter them on the Station tab after switching to it.");
|
||||
}
|
||||
|
||||
private void duplicateSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = requireSelectedProfile();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TextInputDialog nameDialog =
|
||||
new TextInputDialog("Copy of " + selectedProfile.getDisplayName());
|
||||
nameDialog.setTitle("Duplicate operator profile");
|
||||
nameDialog.setHeaderText("Name of the new profile");
|
||||
nameDialog.setContentText(
|
||||
"Everything is copied except callsign and password. Worked stations are never copied.");
|
||||
|
||||
Optional<String> enteredName = nameDialog.showAndWait();
|
||||
|
||||
if (enteredName.isEmpty() || enteredName.get().isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
OperatorProfile duplicatedProfile =
|
||||
managementService.duplicateProfile(selectedProfile, enteredName.get());
|
||||
|
||||
if (duplicatedProfile == null) {
|
||||
showError("The profile could not be duplicated.");
|
||||
return;
|
||||
}
|
||||
|
||||
refreshProfileTable();
|
||||
profileTable.getSelectionModel().select(duplicatedProfile);
|
||||
}
|
||||
|
||||
private void renameSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = requireSelectedProfile();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
TextInputDialog nameDialog = new TextInputDialog(selectedProfile.getDisplayName());
|
||||
nameDialog.setTitle("Rename operator profile");
|
||||
nameDialog.setHeaderText("New name of the profile");
|
||||
nameDialog.setContentText("Files and folders of the profile are not touched.");
|
||||
|
||||
Optional<String> enteredName = nameDialog.showAndWait();
|
||||
|
||||
if (enteredName.isEmpty() || enteredName.get().isBlank()) {
|
||||
return;
|
||||
}
|
||||
|
||||
managementService.renameProfile(selectedProfile, enteredName.get());
|
||||
refreshProfileTable();
|
||||
refreshActiveProfileHeader();
|
||||
}
|
||||
|
||||
private void deleteSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = requireSelectedProfile();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProfile.isRootProfile()) {
|
||||
showError("The default profile uses the files of the installation itself "
|
||||
+ "and cannot be deleted.");
|
||||
return;
|
||||
}
|
||||
|
||||
if (isActiveProfile(selectedProfile)) {
|
||||
showError("The profile currently in use cannot be deleted. Switch to another "
|
||||
+ "profile first.");
|
||||
return;
|
||||
}
|
||||
|
||||
Alert confirmation = new Alert(AlertType.CONFIRMATION);
|
||||
confirmation.setTitle("Delete operator profile");
|
||||
confirmation.setHeaderText("Delete the profile \"" + selectedProfile.getDisplayName() + "\"?");
|
||||
confirmation.setContentText(
|
||||
"The following folder is removed permanently:\n"
|
||||
+ managementService.getProfileDirectory(selectedProfile)
|
||||
+ "\n\n"
|
||||
+ (selectedProfile.isSharedWorkedDatabase()
|
||||
? "The common station worked stations are not touched."
|
||||
: "The worked stations of this profile are deleted as well."));
|
||||
|
||||
ButtonType deleteButton = new ButtonType("Delete profile", ButtonBar.ButtonData.OK_DONE);
|
||||
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
|
||||
confirmation.getButtonTypes().setAll(deleteButton, cancelButton);
|
||||
|
||||
if (confirmation.showAndWait().orElse(cancelButton) != deleteButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!managementService.deleteProfile(selectedProfile)) {
|
||||
showError("The profile could not be deleted.");
|
||||
}
|
||||
|
||||
refreshProfileTable();
|
||||
}
|
||||
|
||||
private void changeWorkedDataModeOfSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = requireSelectedProfile();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProfile.isRootProfile()) {
|
||||
showError("The default profile always uses the common station worked stations, "
|
||||
+ "because that database is the one of the installation itself.");
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<Boolean> chosenMode = showWorkedDataModeDialog(selectedProfile);
|
||||
|
||||
if (chosenMode.isEmpty() || chosenMode.get() == selectedProfile.isSharedWorkedDatabase()) {
|
||||
return;
|
||||
}
|
||||
|
||||
managementService.setSharedWorkedDatabase(selectedProfile, chosenMode.get());
|
||||
refreshProfileTable();
|
||||
|
||||
if (isActiveProfile(selectedProfile)) {
|
||||
showInformation("The change takes effect after switching to this profile again.");
|
||||
}
|
||||
}
|
||||
|
||||
private void activateSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = requireSelectedProfile();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isActiveProfile(selectedProfile)) {
|
||||
showInformation("This profile is already active.");
|
||||
return;
|
||||
}
|
||||
|
||||
profileActivationRequest.accept(selectedProfile);
|
||||
}
|
||||
|
||||
private Optional<Pair<String, Boolean>> showProfileCreationDialog(final String title,
|
||||
final String initialName) {
|
||||
|
||||
Dialog<Pair<String, Boolean>> creationDialog = new Dialog<>();
|
||||
creationDialog.setTitle(title);
|
||||
creationDialog.setHeaderText("Name and worked stations of the new profile");
|
||||
|
||||
ButtonType createButton = new ButtonType("Create profile", ButtonBar.ButtonData.OK_DONE);
|
||||
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
|
||||
creationDialog.getDialogPane().getButtonTypes().setAll(createButton, cancelButton);
|
||||
|
||||
TextField nameField = new TextField(initialName);
|
||||
nameField.setPromptText("for example DN9APW");
|
||||
|
||||
ToggleGroup workedDataGroup = new ToggleGroup();
|
||||
|
||||
RadioButton ownDatabaseOption = new RadioButton("Own worked stations for this profile");
|
||||
ownDatabaseOption.setToggleGroup(workedDataGroup);
|
||||
ownDatabaseOption.setSelected(true);
|
||||
|
||||
RadioButton sharedDatabaseOption =
|
||||
new RadioButton("Share the common station worked stations (multi operator station)");
|
||||
sharedDatabaseOption.setToggleGroup(workedDataGroup);
|
||||
|
||||
VBox dialogContent = new VBox(8,
|
||||
new Label("Profile name"),
|
||||
nameField,
|
||||
new Label("Worked stations"),
|
||||
ownDatabaseOption,
|
||||
sharedDatabaseOption);
|
||||
dialogContent.setPadding(new Insets(10));
|
||||
|
||||
creationDialog.getDialogPane().setContent(dialogContent);
|
||||
|
||||
creationDialog.setResultConverter(pressedButton -> {
|
||||
if (pressedButton != createButton || nameField.getText().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return new Pair<>(nameField.getText().trim(), sharedDatabaseOption.isSelected());
|
||||
});
|
||||
|
||||
return creationDialog.showAndWait();
|
||||
}
|
||||
|
||||
private Optional<Boolean> showWorkedDataModeDialog(final OperatorProfile profile) {
|
||||
|
||||
Dialog<Boolean> modeDialog = new Dialog<>();
|
||||
modeDialog.setTitle("Worked stations");
|
||||
modeDialog.setHeaderText("Worked stations of \"" + profile.getDisplayName() + "\"");
|
||||
|
||||
ButtonType applyButton = new ButtonType("Apply", ButtonBar.ButtonData.OK_DONE);
|
||||
ButtonType cancelButton = new ButtonType("Cancel", ButtonBar.ButtonData.CANCEL_CLOSE);
|
||||
modeDialog.getDialogPane().getButtonTypes().setAll(applyButton, cancelButton);
|
||||
|
||||
ToggleGroup workedDataGroup = new ToggleGroup();
|
||||
|
||||
RadioButton ownDatabaseOption = new RadioButton("Own worked stations for this profile");
|
||||
ownDatabaseOption.setToggleGroup(workedDataGroup);
|
||||
|
||||
RadioButton sharedDatabaseOption =
|
||||
new RadioButton("Share the common station worked stations (multi operator station)");
|
||||
sharedDatabaseOption.setToggleGroup(workedDataGroup);
|
||||
|
||||
sharedDatabaseOption.setSelected(profile.isSharedWorkedDatabase());
|
||||
ownDatabaseOption.setSelected(!profile.isSharedWorkedDatabase());
|
||||
|
||||
Label pathHint = new Label("Switching does not move any data. Worked stations already "
|
||||
+ "collected under the other setting stay where they are.");
|
||||
pathHint.setWrapText(true);
|
||||
|
||||
VBox dialogContent = new VBox(8, ownDatabaseOption, sharedDatabaseOption, pathHint);
|
||||
dialogContent.setPadding(new Insets(10));
|
||||
|
||||
modeDialog.getDialogPane().setContent(dialogContent);
|
||||
modeDialog.setResultConverter(pressedButton ->
|
||||
pressedButton == applyButton ? sharedDatabaseOption.isSelected() : null);
|
||||
|
||||
return modeDialog.showAndWait();
|
||||
}
|
||||
|
||||
private OperatorProfile requireSelectedProfile() {
|
||||
|
||||
OperatorProfile selectedProfile = profileTable.getSelectionModel().getSelectedItem();
|
||||
|
||||
if (selectedProfile == null) {
|
||||
showInformation("Select a profile in the table first.");
|
||||
}
|
||||
|
||||
return selectedProfile;
|
||||
}
|
||||
|
||||
private static boolean isActiveProfile(final OperatorProfile profile) {
|
||||
|
||||
OperatorProfileSelection activeProfile = ActiveOperatorProfile.get();
|
||||
|
||||
return activeProfile != null
|
||||
&& activeProfile.getProfile().getProfileId().equals(profile.getProfileId());
|
||||
}
|
||||
|
||||
private static String describeWorkedDataMode(final OperatorProfile profile) {
|
||||
|
||||
if (profile.isRootProfile() || profile.isSharedWorkedDatabase()) {
|
||||
return "common station database";
|
||||
}
|
||||
|
||||
return "own database";
|
||||
}
|
||||
|
||||
private static String describeLastUsed(final OperatorProfile profile) {
|
||||
|
||||
if (profile.getLastUsedEpochMs() <= 0L) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return LAST_USED_FORMATTER.format(Instant.ofEpochMilli(profile.getLastUsedEpochMs()));
|
||||
}
|
||||
|
||||
private static void showInformation(final String message) {
|
||||
Alert information = new Alert(AlertType.INFORMATION);
|
||||
information.setTitle("Operator profiles");
|
||||
information.setContentText(message);
|
||||
information.showAndWait();
|
||||
}
|
||||
|
||||
private static void showError(final String message) {
|
||||
Alert error = new Alert(AlertType.ERROR);
|
||||
error.setTitle("Operator profiles");
|
||||
error.setContentText(message);
|
||||
error.showAndWait();
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package kst4contest.view.map;
|
||||
|
||||
import javafx.animation.PauseTransition;
|
||||
import javafx.application.Platform;
|
||||
import javafx.beans.value.ChangeListener;
|
||||
import javafx.collections.ListChangeListener;
|
||||
import javafx.scene.control.TableView;
|
||||
import javafx.util.Duration;
|
||||
@@ -54,6 +55,16 @@ public final class StationMapBridge {
|
||||
|
||||
private final PauseTransition refreshCoalescer = new PauseTransition(Duration.seconds(1.0));
|
||||
|
||||
/*
|
||||
* The listeners are kept so install() can be undone. Without that, the coalescing
|
||||
* animation and the registered listeners would keep a discarded runtime reachable
|
||||
* after an operator profile switch.
|
||||
*/
|
||||
private ListChangeListener<ChatMember> chatMemberListListener;
|
||||
private ChangeListener<ChatMember> selectedChatMemberListener;
|
||||
private ChangeListener<Number> antennaDirectionListener;
|
||||
private ListChangeListener<Predicate<ChatMember>> filterPredicateListener;
|
||||
|
||||
public StationMapBridge(ChatController chatController,
|
||||
TableView<ChatMember> chatMemberTable,
|
||||
StationMapView stationMapView,
|
||||
@@ -81,25 +92,59 @@ public final class StationMapBridge {
|
||||
|
||||
stationMapView.setOnResetView(this::handleMapReset);
|
||||
|
||||
chatController.getLst_chatMemberSortedFilteredList().addListener(
|
||||
(ListChangeListener<ChatMember>) change -> scheduleRefresh()
|
||||
);
|
||||
chatMemberListListener = change -> scheduleRefresh();
|
||||
chatController.getLst_chatMemberSortedFilteredList().addListener(chatMemberListListener);
|
||||
|
||||
chatController.getScoreService().selectedChatMemberProperty().addListener(
|
||||
(obs, oldValue, newValue) -> requestImmediateRefresh()
|
||||
);
|
||||
selectedChatMemberListener = (obs, oldValue, newValue) -> requestImmediateRefresh();
|
||||
chatController.getScoreService().selectedChatMemberProperty()
|
||||
.addListener(selectedChatMemberListener);
|
||||
|
||||
chatController.getChatPreferences().getActualQTF().addListener(
|
||||
(obs, oldValue, newValue) -> scheduleRefresh()
|
||||
);
|
||||
antennaDirectionListener = (obs, oldValue, newValue) -> scheduleRefresh();
|
||||
chatController.getChatPreferences().getActualQTF().addListener(antennaDirectionListener);
|
||||
|
||||
chatController.getLst_chatMemberListFilterPredicates().addListener(
|
||||
(ListChangeListener<Predicate<ChatMember>>) change -> requestImmediateRefresh()
|
||||
);
|
||||
filterPredicateListener = change -> requestImmediateRefresh();
|
||||
chatController.getLst_chatMemberListFilterPredicates().addListener(filterPredicateListener);
|
||||
|
||||
requestImmediateRefresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes everything {@link #install()} registered and stops the coalescing timer.
|
||||
*
|
||||
* <p>Needed when the runtime owning this bridge is discarded, for example during an
|
||||
* operator profile switch. A running {@link PauseTransition} would otherwise keep
|
||||
* firing into a dead user interface.</p>
|
||||
*/
|
||||
public void uninstall() {
|
||||
|
||||
refreshCoalescer.stop();
|
||||
|
||||
stationMapView.setOnCallsignRawSelected(null);
|
||||
stationMapView.setOnTriggerClusterSpot(null);
|
||||
stationMapView.setOnResetView(null);
|
||||
|
||||
if (chatMemberListListener != null) {
|
||||
chatController.getLst_chatMemberSortedFilteredList().removeListener(chatMemberListListener);
|
||||
chatMemberListListener = null;
|
||||
}
|
||||
|
||||
if (selectedChatMemberListener != null) {
|
||||
chatController.getScoreService().selectedChatMemberProperty()
|
||||
.removeListener(selectedChatMemberListener);
|
||||
selectedChatMemberListener = null;
|
||||
}
|
||||
|
||||
if (antennaDirectionListener != null) {
|
||||
chatController.getChatPreferences().getActualQTF().removeListener(antennaDirectionListener);
|
||||
antennaDirectionListener = null;
|
||||
}
|
||||
|
||||
if (filterPredicateListener != null) {
|
||||
chatController.getLst_chatMemberListFilterPredicates().removeListener(filterPredicateListener);
|
||||
filterPredicateListener = null;
|
||||
}
|
||||
}
|
||||
|
||||
private void handleMapReset() {
|
||||
Runnable resetAction = () -> {
|
||||
/*
|
||||
|
||||
@@ -244,6 +244,25 @@ public final class StationMapView {
|
||||
stage.hide();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases every resource this map window owns.
|
||||
*
|
||||
* <p>The tile proxy is a local server socket with its own thread pool. It used to
|
||||
* live until the process ended, which was harmless while the map existed exactly
|
||||
* once per process. A runtime that is discarded, for example during an operator
|
||||
* profile switch, has to hand it back.</p>
|
||||
*/
|
||||
public void dispose() {
|
||||
|
||||
if (tileProxyServer != null) {
|
||||
tileProxyServer.stop();
|
||||
tileProxyServer = null;
|
||||
}
|
||||
|
||||
webEngine.load(null);
|
||||
stage.close();
|
||||
}
|
||||
|
||||
public boolean isShowing() {
|
||||
return stage.isShowing();
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package kst4contest.view.map;
|
||||
|
||||
import kst4contest.ApplicationConstants;
|
||||
import kst4contest.controller.DBController;
|
||||
import kst4contest.utils.ApplicationFileUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
@@ -15,30 +17,44 @@ import java.util.Locale;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Persistent terrain profile cache stored in the application's existing SQLite database.
|
||||
* Persistent terrain profile cache, stored globally in its own SQLite database.
|
||||
*
|
||||
* The cache is intentionally owner-bound:
|
||||
* if the configured own callsign or own locator changes, all cached terrain
|
||||
* profiles are cleared automatically.
|
||||
* <p>Terrain profiles are pure geometry derived from two locators and a sample count.
|
||||
* They do not belong to one operator, so the cache is deliberately not part of an
|
||||
* operator profile: at a multi operator station both operators share one location, and
|
||||
* duplicating the cache would double the traffic against an external terrain service.</p>
|
||||
*
|
||||
* <p>Entries are separated by owner identity through the primary key instead. Earlier
|
||||
* versions kept a single owner identity and dropped the whole cache whenever the
|
||||
* configured callsign or locator changed; with several operator profiles that would
|
||||
* discard every computed profile on each switch.</p>
|
||||
*/
|
||||
public final class TerrainProfileCacheRepository {
|
||||
|
||||
private static final String META_KEY_OWNER_CALLSIGN_RAW = "terrain_cache_owner_callsign_raw";
|
||||
private static final String META_KEY_OWNER_LOCATOR6 = "terrain_cache_owner_locator6";
|
||||
/**
|
||||
* File name of the global terrain profile cache below the application directory.
|
||||
*/
|
||||
public static final String TERRAIN_CACHE_DATABASE_FILE = "terrainprofilecache.db";
|
||||
|
||||
private final String databasePath;
|
||||
|
||||
public TerrainProfileCacheRepository() {
|
||||
ApplicationFileUtils.copyResourceIfRequired(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
DBController.DATABASE_RESOURCE,
|
||||
DBController.DATABASE_FILE
|
||||
);
|
||||
|
||||
this.databasePath = ApplicationFileUtils.getFilePath(
|
||||
ApplicationConstants.APPLICATION_NAME,
|
||||
DBController.DATABASE_FILE
|
||||
TERRAIN_CACHE_DATABASE_FILE
|
||||
);
|
||||
|
||||
// SQLite only creates the database file itself, not the directory holding it.
|
||||
Path applicationDirectory = Path.of(databasePath).getParent();
|
||||
|
||||
if (applicationDirectory != null) {
|
||||
try {
|
||||
Files.createDirectories(applicationDirectory);
|
||||
} catch (IOException exception) {
|
||||
System.err.println("[StationMap] Terrain cache directory could not be created: "
|
||||
+ exception.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public synchronized Optional<TerrainProfileData> load(String ownerCallsignRaw,
|
||||
@@ -183,60 +199,37 @@ public final class TerrainProfileCacheRepository {
|
||||
""");
|
||||
|
||||
statement.executeUpdate("""
|
||||
CREATE TABLE IF NOT EXISTS TerrainProfileCacheMeta (
|
||||
meta_key TEXT NOT NULL PRIMARY KEY,
|
||||
meta_value TEXT NOT NULL
|
||||
CREATE TABLE IF NOT EXISTS TerrainProfileCacheOwner (
|
||||
owner_callsign_raw TEXT NOT NULL,
|
||||
owner_locator6 TEXT NOT NULL,
|
||||
last_used_epoch_ms INTEGER NOT NULL,
|
||||
PRIMARY KEY (owner_callsign_raw, owner_locator6)
|
||||
)
|
||||
""");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records that the given owner identity is in use.
|
||||
*
|
||||
* <p>Entries of other owners stay untouched. The cached profiles of an identity are
|
||||
* separated by the primary key already, so a different callsign or locator simply
|
||||
* misses the cache instead of invalidating everybody else's entries.</p>
|
||||
*/
|
||||
private void ensureOwnerIdentity(Connection connection,
|
||||
String currentOwnerCallsignRaw,
|
||||
String currentOwnerLocator6) throws Exception {
|
||||
|
||||
String normalizedOwnerCallsignRaw = normalize(currentOwnerCallsignRaw);
|
||||
String normalizedOwnerLocator6 = normalize(currentOwnerLocator6);
|
||||
|
||||
String storedOwnerCallsignRaw = readMetaValue(connection, META_KEY_OWNER_CALLSIGN_RAW);
|
||||
String storedOwnerLocator6 = readMetaValue(connection, META_KEY_OWNER_LOCATOR6);
|
||||
|
||||
boolean callsignChanged = storedOwnerCallsignRaw != null && !storedOwnerCallsignRaw.equals(normalizedOwnerCallsignRaw);
|
||||
boolean locatorChanged = storedOwnerLocator6 != null && !storedOwnerLocator6.equals(normalizedOwnerLocator6);
|
||||
|
||||
if (callsignChanged || locatorChanged) {
|
||||
clearTerrainCache(connection);
|
||||
}
|
||||
|
||||
writeMetaValue(connection, META_KEY_OWNER_CALLSIGN_RAW, normalizedOwnerCallsignRaw);
|
||||
writeMetaValue(connection, META_KEY_OWNER_LOCATOR6, normalizedOwnerLocator6);
|
||||
}
|
||||
|
||||
private void clearTerrainCache(Connection connection) throws Exception {
|
||||
try (Statement statement = connection.createStatement()) {
|
||||
statement.executeUpdate("DELETE FROM TerrainProfileCache");
|
||||
}
|
||||
}
|
||||
|
||||
private String readMetaValue(Connection connection, String key) throws Exception {
|
||||
try (PreparedStatement statement = connection.prepareStatement(
|
||||
"SELECT meta_value FROM TerrainProfileCacheMeta WHERE meta_key = ?")) {
|
||||
statement.setString(1, key);
|
||||
|
||||
try (ResultSet resultSet = statement.executeQuery()) {
|
||||
return resultSet.next() ? resultSet.getString(1) : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void writeMetaValue(Connection connection, String key, String value) throws Exception {
|
||||
try (PreparedStatement statement = connection.prepareStatement("""
|
||||
INSERT INTO TerrainProfileCacheMeta (meta_key, meta_value)
|
||||
VALUES (?, ?)
|
||||
ON CONFLICT(meta_key) DO UPDATE SET meta_value = excluded.meta_value
|
||||
INSERT INTO TerrainProfileCacheOwner (
|
||||
owner_callsign_raw, owner_locator6, last_used_epoch_ms
|
||||
) VALUES (?, ?, ?)
|
||||
ON CONFLICT(owner_callsign_raw, owner_locator6) DO UPDATE SET
|
||||
last_used_epoch_ms = excluded.last_used_epoch_ms
|
||||
""")) {
|
||||
statement.setString(1, key);
|
||||
statement.setString(2, value == null ? "" : value);
|
||||
statement.setString(1, normalize(currentOwnerCallsignRaw));
|
||||
statement.setString(2, normalize(currentOwnerLocator6));
|
||||
statement.setLong(3, System.currentTimeMillis());
|
||||
statement.executeUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.ChatMember;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.sql.SQLException;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Verifies that one DBController instance works on exactly one database file, so two
|
||||
* operator profiles can keep independent worked-station data inside the same process.
|
||||
*/
|
||||
class DBControllerProfileDatabaseTest {
|
||||
|
||||
private static final String USER_HOME_PROPERTY = "user.home";
|
||||
|
||||
@TempDir
|
||||
Path temporaryHomeDirectory;
|
||||
|
||||
private String originalUserHome;
|
||||
|
||||
@BeforeEach
|
||||
void redirectUserHomeToTemporaryDirectory() {
|
||||
originalUserHome = System.getProperty(USER_HOME_PROPERTY);
|
||||
System.setProperty(USER_HOME_PROPERTY, temporaryHomeDirectory.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreUserHome() {
|
||||
if (originalUserHome == null) {
|
||||
System.clearProperty(USER_HOME_PROPERTY);
|
||||
} else {
|
||||
System.setProperty(USER_HOME_PROPERTY, originalUserHome);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileDatabaseIsCreatedEmptyAndKeepsWorkedDataSeparate() throws SQLException {
|
||||
|
||||
DBController firstProfileDatabase =
|
||||
new DBController("profiles/OP1/praktiKST.db", false);
|
||||
DBController secondProfileDatabase =
|
||||
new DBController("profiles/OP2/praktiKST.db", false);
|
||||
|
||||
try {
|
||||
// A profile database must not inherit the several thousand callsigns of the
|
||||
// bundled template database.
|
||||
assertTrue(firstProfileDatabase.fetchChatMemberWkdDataFromDB().isEmpty());
|
||||
assertTrue(secondProfileDatabase.fetchChatMemberWkdDataFromDB().isEmpty());
|
||||
|
||||
assertNotEquals(firstProfileDatabase.getDatabaseFilePath(),
|
||||
secondProfileDatabase.getDatabaseFilePath());
|
||||
assertTrue(Files.exists(Path.of(firstProfileDatabase.getDatabaseFilePath())));
|
||||
assertTrue(Files.exists(Path.of(secondProfileDatabase.getDatabaseFilePath())));
|
||||
|
||||
ChatMember workedOnFirstProfile = new ChatMember();
|
||||
workedOnFirstProfile.setCallSign("DL0XYZ");
|
||||
workedOnFirstProfile.setQra("JO51IJ");
|
||||
workedOnFirstProfile.setWorked(true);
|
||||
workedOnFirstProfile.setWorked144(true);
|
||||
|
||||
firstProfileDatabase.storeChatMember(workedOnFirstProfile);
|
||||
|
||||
Map<String, ChatMember> firstProfileContent =
|
||||
firstProfileDatabase.fetchChatMemberWkdDataFromDB();
|
||||
Map<String, ChatMember> secondProfileContent =
|
||||
secondProfileDatabase.fetchChatMemberWkdDataFromDB();
|
||||
|
||||
assertEquals(1, firstProfileContent.size());
|
||||
assertTrue(firstProfileContent.get("DL0XYZ").isWorked144());
|
||||
assertTrue(secondProfileContent.isEmpty(),
|
||||
"A worked station of one profile must not appear in the other profile");
|
||||
} finally {
|
||||
firstProfileDatabase.closeDBConnection();
|
||||
secondProfileDatabase.closeDBConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoProfilesPointingAtTheSameFileShareTheirWorkedData() throws SQLException {
|
||||
|
||||
DBController sharedStationDatabase = new DBController("praktiKST.db", false);
|
||||
DBController sameSharedDatabaseAgain = new DBController("praktiKST.db", false);
|
||||
|
||||
try {
|
||||
ChatMember workedAtTheStation = new ChatMember();
|
||||
workedAtTheStation.setCallSign("DL0ABC");
|
||||
workedAtTheStation.setWorked(true);
|
||||
workedAtTheStation.setWorked432(true);
|
||||
|
||||
sharedStationDatabase.storeChatMember(workedAtTheStation);
|
||||
|
||||
Map<String, ChatMember> seenByTheOtherOperator =
|
||||
sameSharedDatabaseAgain.fetchChatMemberWkdDataFromDB();
|
||||
|
||||
assertTrue(seenByTheOtherOperator.containsKey("DL0ABC"),
|
||||
"Operators sharing one station database must see the same worked stations");
|
||||
assertTrue(seenByTheOtherOperator.get("DL0ABC").isWorked432());
|
||||
} finally {
|
||||
sharedStationDatabase.closeDBConnection();
|
||||
sameSharedDatabaseAgain.closeDBConnection();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void closingTheConnectionDeregistersTheShutdownHook() {
|
||||
|
||||
DBController profileDatabase = new DBController("profiles/OP3/praktiKST.db", false);
|
||||
profileDatabase.closeDBConnection();
|
||||
|
||||
// A second close must stay harmless, and the hook must already be gone.
|
||||
profileDatabase.closeDBConnection();
|
||||
|
||||
assertFalse(Files.notExists(Path.of(profileDatabase.getDatabaseFilePath())),
|
||||
"The database file stays on disk after the connection was closed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.ChatPreferences;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class OperatorProfileManagementServiceTest {
|
||||
|
||||
private static final String USER_HOME_PROPERTY = "user.home";
|
||||
|
||||
@TempDir
|
||||
Path temporaryHomeDirectory;
|
||||
|
||||
private String originalUserHome;
|
||||
private OperatorProfileManagementService managementService;
|
||||
|
||||
@BeforeEach
|
||||
void redirectUserHomeToTemporaryDirectory() {
|
||||
originalUserHome = System.getProperty(USER_HOME_PROPERTY);
|
||||
System.setProperty(USER_HOME_PROPERTY, temporaryHomeDirectory.toString());
|
||||
managementService = new OperatorProfileManagementService();
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreUserHome() {
|
||||
if (originalUserHome == null) {
|
||||
System.clearProperty(USER_HOME_PROPERTY);
|
||||
} else {
|
||||
System.setProperty(USER_HOME_PROPERTY, originalUserHome);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aPlainInstallationReportsExactlyOneImplicitRootProfile() {
|
||||
|
||||
List<OperatorProfile> knownProfiles = managementService.listProfiles();
|
||||
|
||||
assertEquals(1, knownProfiles.size());
|
||||
assertTrue(knownProfiles.get(0).isRootProfile());
|
||||
assertFalse(Files.exists(applicationFile("profiles.xml")),
|
||||
"Merely listing profiles must not create a registry");
|
||||
}
|
||||
|
||||
@Test
|
||||
void creatingTheSecondProfileMaterialisesTheRegistryIncludingTheRootProfile() {
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile("DN9APW", false);
|
||||
|
||||
assertNotNull(createdProfile);
|
||||
assertEquals("DN9APW", createdProfile.getProfileId());
|
||||
assertTrue(Files.exists(applicationFile("profiles.xml")));
|
||||
|
||||
List<OperatorProfile> knownProfiles = managementService.listProfiles();
|
||||
|
||||
assertEquals(2, knownProfiles.size());
|
||||
assertTrue(knownProfiles.get(0).isRootProfile());
|
||||
assertEquals("DN9APW", knownProfiles.get(1).getProfileId());
|
||||
|
||||
assertTrue(Files.exists(applicationFile("profiles/DN9APW/preferences.xml")));
|
||||
|
||||
// The historic files must stay exactly where an older release expects them.
|
||||
assertFalse(Files.exists(applicationFile("profiles/default")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNewProfileStartsWithoutLoginCredentials() {
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile("DN9APW", false);
|
||||
|
||||
ChatPreferences createdPreferences =
|
||||
preferencesAt(OperatorProfilePaths.preferencesRelativeFileName(createdProfile));
|
||||
|
||||
assertEquals("", createdPreferences.getStn_loginCallSign());
|
||||
assertEquals("", createdPreferences.getStn_loginPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicatingKeepsTheStationSetupButClearsCallsignAndPassword() {
|
||||
|
||||
OperatorProfile sourceProfile = managementService.createProfile("Source", false);
|
||||
|
||||
ChatPreferences sourcePreferences =
|
||||
preferencesAt(OperatorProfilePaths.preferencesRelativeFileName(sourceProfile));
|
||||
sourcePreferences.setStn_loginCallSign("DM5M");
|
||||
sourcePreferences.setStn_loginPassword("secret");
|
||||
sourcePreferences.setStn_loginLocatorMainCat("JO51IJ");
|
||||
sourcePreferences.setStn_antennaBeamWidthDeg(17.5);
|
||||
assertTrue(sourcePreferences.writePreferencesToXmlFile());
|
||||
|
||||
OperatorProfile duplicatedProfile =
|
||||
managementService.duplicateProfile(sourceProfile, "Copy of source");
|
||||
|
||||
assertNotNull(duplicatedProfile);
|
||||
|
||||
ChatPreferences duplicatedPreferences =
|
||||
preferencesAt(OperatorProfilePaths.preferencesRelativeFileName(duplicatedProfile));
|
||||
|
||||
// The work worth keeping.
|
||||
assertEquals("JO51IJ", duplicatedPreferences.getStn_loginLocatorMainCat());
|
||||
assertEquals(17.5, duplicatedPreferences.getStn_antennaBeamWidthDeg());
|
||||
|
||||
// The identity that must not be inherited.
|
||||
assertEquals("", duplicatedPreferences.getStn_loginCallSign());
|
||||
assertEquals("", duplicatedPreferences.getStn_loginPassword());
|
||||
}
|
||||
|
||||
@Test
|
||||
void switchingBetweenSharedAndOwnWorkedDataChangesOnlyTheDatabasePath() {
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile("DN9APW", false);
|
||||
|
||||
assertEquals("profiles/DN9APW/praktiKST.db",
|
||||
OperatorProfilePaths.workedDatabaseRelativeFileName(createdProfile));
|
||||
|
||||
assertTrue(managementService.setSharedWorkedDatabase(createdProfile, true));
|
||||
|
||||
OperatorProfile reloadedProfile = managementService.listProfiles().get(1);
|
||||
|
||||
assertTrue(reloadedProfile.isSharedWorkedDatabase());
|
||||
assertEquals("praktiKST.db",
|
||||
OperatorProfilePaths.workedDatabaseRelativeFileName(reloadedProfile));
|
||||
assertEquals("profiles/DN9APW/preferences.xml",
|
||||
OperatorProfilePaths.preferencesRelativeFileName(reloadedProfile));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletingRemovesTheProfileDirectoryButNeverTheRootProfile() {
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile("DN9APW", false);
|
||||
assertTrue(Files.exists(applicationFile("profiles/DN9APW/preferences.xml")));
|
||||
|
||||
OperatorProfile rootProfile = managementService.listProfiles().get(0);
|
||||
assertFalse(managementService.deleteProfile(rootProfile),
|
||||
"The root profile is the installation itself and must not be removable");
|
||||
|
||||
assertTrue(managementService.deleteProfile(createdProfile));
|
||||
assertFalse(Files.exists(applicationFile("profiles/DN9APW")));
|
||||
assertEquals(1, managementService.listProfiles().size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void renamingKeepsTheIdentifierAndTherebyAllPaths() {
|
||||
|
||||
OperatorProfile createdProfile = managementService.createProfile("DN9APW", false);
|
||||
|
||||
assertTrue(managementService.renameProfile(createdProfile, "Philipp portable"));
|
||||
|
||||
OperatorProfile renamedProfile = managementService.listProfiles().get(1);
|
||||
|
||||
assertEquals("Philipp portable", renamedProfile.getDisplayName());
|
||||
assertEquals("DN9APW", renamedProfile.getProfileId());
|
||||
assertEquals("profiles/DN9APW/preferences.xml",
|
||||
OperatorProfilePaths.preferencesRelativeFileName(renamedProfile));
|
||||
}
|
||||
|
||||
private ChatPreferences preferencesAt(final String relativeFileName) {
|
||||
ChatPreferences preferences = new ChatPreferences(relativeFileName);
|
||||
preferences.readPreferencesFromXmlFile();
|
||||
return preferences;
|
||||
}
|
||||
|
||||
private Path applicationFile(final String relativeFileName) {
|
||||
return temporaryHomeDirectory.resolve(".praktiKST").resolve(relativeFileName);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class OperatorProfilePathsTest {
|
||||
|
||||
@Test
|
||||
void rootProfileKeepsTheHistoricFlatFileNames() {
|
||||
|
||||
OperatorProfileSelection resolved =
|
||||
OperatorProfilePaths.resolve(OperatorProfilePaths.buildRootProfile("Default"));
|
||||
|
||||
// This is the downgrade guard: an older KST4Contest release reads exactly these
|
||||
// two files. If this test ever fails, existing installations would silently lose
|
||||
// their configuration and worked data when the operator reverts a version.
|
||||
assertEquals("preferences.xml", resolved.getPreferencesRelativeFileName());
|
||||
assertEquals("praktiKST.db", resolved.getWorkedDatabaseRelativeFileName());
|
||||
assertTrue(resolved.isSeedWorkedDatabaseFromResource());
|
||||
}
|
||||
|
||||
@Test
|
||||
void additionalProfileWithSharedDatabaseUsesItsOwnPreferencesButTheStationDatabase() {
|
||||
|
||||
OperatorProfile sharedProfile = new OperatorProfile("OP2", "DN9APW", false, true);
|
||||
OperatorProfileSelection resolved = OperatorProfilePaths.resolve(sharedProfile);
|
||||
|
||||
assertEquals("profiles/OP2/preferences.xml", resolved.getPreferencesRelativeFileName());
|
||||
assertEquals("praktiKST.db", resolved.getWorkedDatabaseRelativeFileName());
|
||||
assertTrue(resolved.isSeedWorkedDatabaseFromResource());
|
||||
}
|
||||
|
||||
@Test
|
||||
void additionalProfileWithOwnDatabaseIsFullySeparatedAndNotSeeded() {
|
||||
|
||||
OperatorProfile ownDatabaseProfile = new OperatorProfile("OP2", "DN9APW", false, false);
|
||||
OperatorProfileSelection resolved = OperatorProfilePaths.resolve(ownDatabaseProfile);
|
||||
|
||||
assertEquals("profiles/OP2/preferences.xml", resolved.getPreferencesRelativeFileName());
|
||||
assertEquals("profiles/OP2/praktiKST.db", resolved.getWorkedDatabaseRelativeFileName());
|
||||
|
||||
// Seeding would hand a new operator the several thousand callsigns of the
|
||||
// bundled template database.
|
||||
assertFalse(resolved.isSeedWorkedDatabaseFromResource());
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileIdIsFileSystemSafe() {
|
||||
|
||||
assertEquals("DN9APW", OperatorProfilePaths.toProfileId("dn9apw", Set.of()));
|
||||
assertEquals("DM5M_CONTEST", OperatorProfilePaths.toProfileId("DM5M Contest", Set.of()));
|
||||
assertEquals("A_B", OperatorProfilePaths.toProfileId("a/../b", Set.of()));
|
||||
assertEquals("MULLER", OperatorProfilePaths.toProfileId("Müller", Set.of()));
|
||||
assertEquals("OP", OperatorProfilePaths.toProfileId(" ", Set.of()));
|
||||
assertEquals("OP", OperatorProfilePaths.toProfileId(null, Set.of()));
|
||||
|
||||
String longName = "A".repeat(60);
|
||||
assertEquals(32, OperatorProfilePaths.toProfileId(longName, Set.of()).length());
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileIdNeverCollidesAndNeverClaimsTheRootIdentifier() {
|
||||
|
||||
assertEquals("DN9APW_2", OperatorProfilePaths.toProfileId("DN9APW", List.of("DN9APW")));
|
||||
assertEquals("DN9APW_3",
|
||||
OperatorProfilePaths.toProfileId("DN9APW", List.of("DN9APW", "DN9APW_2")));
|
||||
|
||||
// "default" is reserved for the historic flat installation.
|
||||
assertNotEquals(OperatorProfilePaths.ROOT_PROFILE_ID,
|
||||
OperatorProfilePaths.toProfileId("default", Set.of()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class OperatorProfileStoreTest {
|
||||
|
||||
@TempDir
|
||||
Path temporaryDirectory;
|
||||
|
||||
@Test
|
||||
void missingRegistryIsNotAnErrorAndIsNotCreated() {
|
||||
|
||||
OperatorProfileStore store = storeAt("profiles.xml");
|
||||
|
||||
assertFalse(store.isRegistryPresent());
|
||||
assertTrue(store.loadProfiles().isEmpty());
|
||||
assertEquals(Optional.empty(), store.loadLastUsedProfileId());
|
||||
|
||||
// A single operator installation must stay untouched by merely starting up.
|
||||
assertFalse(Files.exists(temporaryDirectory.resolve("profiles.xml")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void profilesSurviveAWriteReadRoundTrip() {
|
||||
|
||||
OperatorProfileStore store = storeAt("profiles.xml");
|
||||
|
||||
OperatorProfile rootProfile = OperatorProfilePaths.buildRootProfile("DM5M station");
|
||||
OperatorProfile secondProfile = new OperatorProfile("OP2", "DN9APW", false, false);
|
||||
secondProfile.setLastUsedEpochMs(1757328000000L);
|
||||
|
||||
assertTrue(store.saveProfiles(List.of(rootProfile, secondProfile), "OP2"));
|
||||
assertTrue(store.isRegistryPresent());
|
||||
|
||||
List<OperatorProfile> restored = store.loadProfiles();
|
||||
|
||||
assertEquals(2, restored.size());
|
||||
assertEquals("default", restored.get(0).getProfileId());
|
||||
assertEquals("DM5M station", restored.get(0).getDisplayName());
|
||||
assertTrue(restored.get(0).isRootProfile());
|
||||
assertTrue(restored.get(0).isSharedWorkedDatabase());
|
||||
|
||||
assertEquals("OP2", restored.get(1).getProfileId());
|
||||
assertEquals("DN9APW", restored.get(1).getDisplayName());
|
||||
assertFalse(restored.get(1).isRootProfile());
|
||||
assertFalse(restored.get(1).isSharedWorkedDatabase());
|
||||
assertEquals(1757328000000L, restored.get(1).getLastUsedEpochMs());
|
||||
|
||||
assertEquals(Optional.of("OP2"), store.loadLastUsedProfileId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void atomicWriteLeavesNoTemporaryFileBehind() throws IOException {
|
||||
|
||||
OperatorProfileStore store = storeAt("profiles.xml");
|
||||
store.saveProfiles(List.of(OperatorProfilePaths.buildRootProfile("Default")), "default");
|
||||
|
||||
try (var directoryEntries = Files.list(temporaryDirectory)) {
|
||||
assertTrue(directoryEntries.noneMatch(entry -> entry.getFileName().toString().endsWith(".tmp")));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedRegistryFallsBackToNoAdditionalProfiles() throws IOException {
|
||||
|
||||
Path registryFile = temporaryDirectory.resolve("profiles.xml");
|
||||
Files.writeString(registryFile, "<praktiKSTProfiles><profile><profileId>OP2");
|
||||
|
||||
OperatorProfileStore store = storeAt("profiles.xml");
|
||||
|
||||
assertTrue(store.isRegistryPresent());
|
||||
assertTrue(store.loadProfiles().isEmpty());
|
||||
assertEquals(Optional.empty(), store.loadLastUsedProfileId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void entriesWithoutAnIdentifierAreSkippedInsteadOfBreakingTheRegistry() throws IOException {
|
||||
|
||||
Path registryFile = temporaryDirectory.resolve("profiles.xml");
|
||||
Files.writeString(registryFile,
|
||||
"<praktiKSTProfiles>"
|
||||
+ "<profile><displayName>broken</displayName></profile>"
|
||||
+ "<profile><profileId>OP2</profileId><displayName>DN9APW</displayName>"
|
||||
+ "<sharedWorkedDatabase>false</sharedWorkedDatabase></profile>"
|
||||
+ "</praktiKSTProfiles>");
|
||||
|
||||
List<OperatorProfile> restored = storeAt("profiles.xml").loadProfiles();
|
||||
|
||||
assertEquals(1, restored.size());
|
||||
assertEquals("OP2", restored.get(0).getProfileId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void recordLastUsedDoesNothingWhenNoRegistryExists() {
|
||||
|
||||
OperatorProfileStore store = storeAt("profiles.xml");
|
||||
|
||||
assertFalse(store.recordLastUsed("default"));
|
||||
assertFalse(store.isRegistryPresent());
|
||||
}
|
||||
|
||||
private OperatorProfileStore storeAt(final String fileName) {
|
||||
return new OperatorProfileStore(temporaryDirectory.resolve(fileName).toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class WinTestIhaveInventoryTest {
|
||||
|
||||
private static Optional<WinTestIhaveInventory> parse(String messageText) {
|
||||
return WinTestIhaveInventory.fromPacket(WinTestPacket.fromMessageText(messageText));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inventoryStartingWithPresentQsosIsExpanded() {
|
||||
Optional<WinTestIhaveInventory> inventory =
|
||||
parse("IHAVE: \"STN1\" \"\" \"STN1@9\" E 1 1 911-1-117");
|
||||
|
||||
assertTrue(inventory.isPresent());
|
||||
assertEquals("STN1@9", inventory.get().getLogId());
|
||||
assertEquals(WinTestIhaveInventory.Origin.LOGGED_ELSE, inventory.get().getOrigin());
|
||||
assertEquals(
|
||||
List.of(new WinTestLogSegment(1L, 911L), new WinTestLogSegment(913L, 1029L)),
|
||||
inventory.get().getSegments());
|
||||
assertEquals(1029L, inventory.get().getHighestQsoNumber());
|
||||
}
|
||||
|
||||
@Test
|
||||
void inventoryStartingWithMissingQsosIsExpanded() {
|
||||
Optional<WinTestIhaveInventory> inventory =
|
||||
parse("IHAVE: \"STN1\" \"\" \"STN1@9\" O 1 0 30-5");
|
||||
|
||||
assertTrue(inventory.isPresent());
|
||||
assertEquals(WinTestIhaveInventory.Origin.OWNER, inventory.get().getOrigin());
|
||||
assertEquals(List.of(new WinTestLogSegment(31L, 35L)), inventory.get().getSegments());
|
||||
}
|
||||
|
||||
@Test
|
||||
void splitInventoryStartsAtItsFirstRow() {
|
||||
/*
|
||||
* Win-Test splits long inventories. The documented example "100 1 10-5-5"
|
||||
* means: ten QSOs from 100, five missing, five present again.
|
||||
*/
|
||||
Optional<WinTestIhaveInventory> inventory =
|
||||
parse("IHAVE: \"STN1\" \"\" \"STN1@9\" O 100 1 10-5-5");
|
||||
|
||||
assertTrue(inventory.isPresent());
|
||||
assertEquals(
|
||||
List.of(new WinTestLogSegment(100L, 109L), new WinTestLogSegment(115L, 119L)),
|
||||
inventory.get().getSegments());
|
||||
}
|
||||
|
||||
@Test
|
||||
void runLengthChainWithWrongParityIsRejected() {
|
||||
assertTrue(parse("IHAVE: \"STN1\" \"\" \"STN1@9\" O 1 1 10-5").isEmpty());
|
||||
assertTrue(parse("IHAVE: \"STN1\" \"\" \"STN1@9\" O 1 0 10-5-5").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyInventoryWithoutRunLengthsIsRejected() {
|
||||
assertTrue(parse("IHAVE: \"STN1\" \"\" \"STN1@169\" \"OWNER\" 2").isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void otherMessageTypesAreRejected() {
|
||||
assertTrue(parse("STATUS: \"STN1\" \"\" 0 12 0 0 0 1443210 0").isEmpty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class WinTestLogSyncServiceTest {
|
||||
|
||||
private static final String LOG_ID = "STN1@44510";
|
||||
|
||||
private final List<String> sentRequests = new ArrayList<>();
|
||||
|
||||
private long currentTimeMs = 1_000_000L;
|
||||
|
||||
private WinTestLogSyncService service;
|
||||
|
||||
@BeforeEach
|
||||
void createService() {
|
||||
sentRequests.clear();
|
||||
service = new WinTestLogSyncService(
|
||||
(targetStation, logId, countFrom, countTo) ->
|
||||
sentRequests.add(targetStation + " " + logId + " " + countFrom + "-" + countTo),
|
||||
() -> "KST4Contest",
|
||||
() -> currentTimeMs
|
||||
);
|
||||
}
|
||||
|
||||
private void receiveIhave(String messageText) {
|
||||
service.onIhaveReceived(WinTestPacket.fromMessageText(messageText));
|
||||
}
|
||||
|
||||
private void receiveQsos(long countFrom, long countTo) {
|
||||
for (long qsoNumber = countFrom; qsoNumber <= countTo; qsoNumber++) {
|
||||
service.registerReceivedQso(LOG_ID, qsoNumber);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstBlockOfAnAnnouncedLogIsRequested() {
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 120");
|
||||
|
||||
service.tick();
|
||||
|
||||
assertEquals(List.of("STN1 " + LOG_ID + " 1-50"), sentRequests);
|
||||
assertEquals(WinTestLogSyncService.SyncState.SYNCING, service.getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void answeredBlockTriggersTheNextBlockUntilTheLogIsComplete() {
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 120");
|
||||
|
||||
service.tick();
|
||||
receiveQsos(1L, 50L);
|
||||
service.tick();
|
||||
receiveQsos(51L, 100L);
|
||||
service.tick();
|
||||
receiveQsos(101L, 120L);
|
||||
service.tick();
|
||||
|
||||
assertEquals(
|
||||
List.of(
|
||||
"STN1 " + LOG_ID + " 1-50",
|
||||
"STN1 " + LOG_ID + " 51-100",
|
||||
"STN1 " + LOG_ID + " 101-120"
|
||||
),
|
||||
sentRequests);
|
||||
assertEquals(WinTestLogSyncService.SyncState.IN_SYNC, service.getState());
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyMissingQsoNumbersAreRequested() {
|
||||
receiveQsos(1L, 10L);
|
||||
receiveQsos(21L, 30L);
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 30");
|
||||
|
||||
service.tick();
|
||||
|
||||
assertEquals(List.of("STN1 " + LOG_ID + " 11-20"), sentRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyKnownQsoIsReportedAsKnown() {
|
||||
assertTrue(service.registerReceivedQso(LOG_ID, 5L));
|
||||
assertFalse(service.registerReceivedQso(LOG_ID, 5L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void qsoWithoutUsableIdentityIsAlwaysTreatedAsNew() {
|
||||
assertTrue(service.registerReceivedQso(null, 5L));
|
||||
assertTrue(service.registerReceivedQso("", 5L));
|
||||
assertTrue(service.registerReceivedQso(LOG_ID, 0L));
|
||||
}
|
||||
|
||||
@Test
|
||||
void unansweredRequestIsRepeatedAtAnotherStationHoldingTheSameLog() {
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 120");
|
||||
receiveIhave("IHAVE: \"STN2\" \"\" \"" + LOG_ID + "\" E 1 1 120");
|
||||
|
||||
service.tick();
|
||||
currentTimeMs += WinTestLogSyncService.REQUEST_TIMEOUT_MS;
|
||||
service.tick();
|
||||
|
||||
assertEquals(
|
||||
List.of("STN1 " + LOG_ID + " 1-50", "STN2 " + LOG_ID + " 1-50"),
|
||||
sentRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void silentStationIsDroppedWhenNobodyElseHoldsTheLog() {
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 120");
|
||||
|
||||
service.tick();
|
||||
currentTimeMs += WinTestLogSyncService.REQUEST_TIMEOUT_MS;
|
||||
service.tick();
|
||||
currentTimeMs += WinTestLogSyncService.REQUEST_TIMEOUT_MS;
|
||||
service.tick();
|
||||
|
||||
assertEquals(List.of("STN1 " + LOG_ID + " 1-50"), sentRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void blindFallbackRequestsFixedBlocksWithoutInventory() {
|
||||
service.onStationSeen("STN1");
|
||||
service.registerReceivedQso(LOG_ID, 7L);
|
||||
|
||||
service.tick();
|
||||
assertEquals(List.of(), sentRequests);
|
||||
|
||||
currentTimeMs += WinTestLogSyncService.INVENTORY_GRACE_PERIOD_MS;
|
||||
service.tick();
|
||||
receiveQsos(1L, 50L);
|
||||
service.tick();
|
||||
|
||||
currentTimeMs += WinTestLogSyncService.REQUEST_TIMEOUT_MS;
|
||||
service.tick();
|
||||
currentTimeMs += WinTestLogSyncService.REQUEST_TIMEOUT_MS;
|
||||
service.tick();
|
||||
|
||||
assertEquals(
|
||||
List.of("STN1 " + LOG_ID + " 1-50", "STN1 " + LOG_ID + " 51-100"),
|
||||
sentRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void inventoryStopsTheBlindFallback() {
|
||||
service.onStationSeen("STN1");
|
||||
service.registerReceivedQso(LOG_ID, 7L);
|
||||
currentTimeMs += WinTestLogSyncService.INVENTORY_GRACE_PERIOD_MS;
|
||||
|
||||
receiveIhave("IHAVE: \"STN1\" \"\" \"" + LOG_ID + "\" O 1 1 10");
|
||||
service.tick();
|
||||
|
||||
assertEquals(List.of("STN1 " + LOG_ID + " 1-6"), sentRequests);
|
||||
}
|
||||
|
||||
@Test
|
||||
void ownPacketsDoNotStartASynchronization() {
|
||||
service.onStationSeen("KST4Contest");
|
||||
|
||||
service.tick();
|
||||
|
||||
assertEquals(List.of(), sentRequests);
|
||||
assertEquals(WinTestLogSyncService.SyncState.IDLE, service.getState());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class WinTestNetworkAddressResolverTest {
|
||||
|
||||
private static InetAddress address(String hostAddress) throws UnknownHostException {
|
||||
return InetAddress.getByName(hostAddress);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stationNetworkWinsOverConfiguredAddress() throws UnknownHostException {
|
||||
WinTestNetworkAddressResolver resolver = new WinTestNetworkAddressResolver(
|
||||
remoteAddress -> {
|
||||
try {
|
||||
return address("192.168.122.255");
|
||||
} catch (UnknownHostException exception) {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
resolver.rememberStationAddress(address("192.168.122.1"));
|
||||
|
||||
assertEquals(address("192.168.122.255"),
|
||||
resolver.resolveBroadcastAddress("192.168.101.255"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void configuredAddressIsUsedWhenNoLocalInterfaceServesTheStation()
|
||||
throws UnknownHostException {
|
||||
WinTestNetworkAddressResolver resolver =
|
||||
new WinTestNetworkAddressResolver(remoteAddress -> null);
|
||||
|
||||
resolver.rememberStationAddress(address("10.9.8.7"));
|
||||
|
||||
assertEquals(address("192.168.101.255"),
|
||||
resolver.resolveBroadcastAddress("192.168.101.255"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void limitedBroadcastIsUsedWithoutStationAndWithoutSetting()
|
||||
throws UnknownHostException {
|
||||
WinTestNetworkAddressResolver resolver =
|
||||
new WinTestNetworkAddressResolver(remoteAddress -> null);
|
||||
|
||||
assertEquals(address("255.255.255.255"), resolver.resolveBroadcastAddress(" "));
|
||||
assertEquals(address("255.255.255.255"), resolver.resolveBroadcastAddress(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
void loopbackAndWildcardSourcesAreIgnored() throws UnknownHostException {
|
||||
WinTestNetworkAddressResolver resolver = new WinTestNetworkAddressResolver(
|
||||
remoteAddress -> {
|
||||
throw new IllegalStateException("must not be asked for " + remoteAddress);
|
||||
});
|
||||
|
||||
resolver.rememberStationAddress(address("127.0.0.1"));
|
||||
resolver.rememberStationAddress(address("0.0.0.0"));
|
||||
resolver.rememberStationAddress(null);
|
||||
|
||||
assertEquals(address("192.168.101.255"),
|
||||
resolver.resolveBroadcastAddress("192.168.101.255"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void subnetComparisonHonoursThePrefixLength() throws UnknownHostException {
|
||||
assertTrue(WinTestNetworkAddressResolver.isInSameSubnet(
|
||||
address("192.168.122.1"), address("192.168.122.203"), 24));
|
||||
assertFalse(WinTestNetworkAddressResolver.isInSameSubnet(
|
||||
address("192.168.101.5"), address("192.168.122.1"), 24));
|
||||
assertTrue(WinTestNetworkAddressResolver.isInSameSubnet(
|
||||
address("172.19.0.1"), address("172.19.240.9"), 16));
|
||||
assertFalse(WinTestNetworkAddressResolver.isInSameSubnet(
|
||||
address("10.244.22.73"), address("10.244.23.1"), 24));
|
||||
assertTrue(WinTestNetworkAddressResolver.isInSameSubnet(
|
||||
address("10.244.22.73"), address("10.244.23.1"), 16));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package kst4contest.controller;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class WinTestPacketTest {
|
||||
|
||||
private static final String ADDQSO_MESSAGE =
|
||||
"ADDQSO: \"STN1\" \"\" \"STN1\" 1762202297 1440000 0 12 0 0 0 2 2 "
|
||||
+ "\"DM2RN\" \"599\" \"599001\" \"JO51UM\" \"\" \"\" 0 \"\" \"\" \"\" 44510";
|
||||
|
||||
/**
|
||||
* Builds a datagram exactly like Win-Test does: message text, checksum byte
|
||||
* replacing the placeholder, NUL terminator.
|
||||
*/
|
||||
private static byte[] toDatagram(String messageText) {
|
||||
byte[] datagram = (messageText + "?\0").getBytes(StandardCharsets.US_ASCII);
|
||||
|
||||
int sum = 0;
|
||||
for (int index = 0; index < datagram.length - 2; index++) {
|
||||
sum += datagram[index] & 0xFF;
|
||||
}
|
||||
|
||||
datagram[datagram.length - 2] = (byte) ((sum | 0x80) & 0xFF);
|
||||
return datagram;
|
||||
}
|
||||
|
||||
@Test
|
||||
void checksumByteAndTerminatorAreRemovedFromMessageText() {
|
||||
byte[] datagram = toDatagram(ADDQSO_MESSAGE);
|
||||
|
||||
WinTestPacket packet = WinTestPacket.fromDatagram(datagram, datagram.length);
|
||||
|
||||
assertEquals(ADDQSO_MESSAGE, packet.getMessageText());
|
||||
assertTrue(packet.isChecksumPresent());
|
||||
assertTrue(packet.isChecksumValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
void trailingLogIdStaysReadableAfterFramingIsResolved() {
|
||||
byte[] datagram = toDatagram(ADDQSO_MESSAGE);
|
||||
|
||||
WinTestPacket packet = WinTestPacket.fromDatagram(datagram, datagram.length);
|
||||
List<String> packetFields = WinTestPacket.tokenize(packet.getMessageText());
|
||||
|
||||
assertEquals("STN1@44510",
|
||||
ReadUDPByWintestThread.extractLogIdFromWinTestAddQso(packetFields));
|
||||
assertEquals(2L,
|
||||
ReadUDPByWintestThread.extractQsoNumberFromWinTestAddQso(packetFields));
|
||||
}
|
||||
|
||||
@Test
|
||||
void manipulatedChecksumIsDetected() {
|
||||
byte[] datagram = toDatagram(ADDQSO_MESSAGE);
|
||||
datagram[datagram.length - 2] = (byte) 0xFF;
|
||||
|
||||
WinTestPacket packet = WinTestPacket.fromDatagram(datagram, datagram.length);
|
||||
|
||||
assertTrue(packet.isChecksumPresent());
|
||||
assertFalse(packet.isChecksumValid());
|
||||
}
|
||||
|
||||
@Test
|
||||
void sourceAndDestinationAreSeparatedFromPayload() {
|
||||
byte[] datagram = toDatagram(
|
||||
"IHAVE: \"STN1\" \"KST4Contest\" \"STN1@44510\" O 1 1 120");
|
||||
|
||||
WinTestPacket packet = WinTestPacket.fromDatagram(datagram, datagram.length);
|
||||
|
||||
assertEquals("IHAVE", packet.getMessageType());
|
||||
assertEquals("STN1", packet.getSource());
|
||||
assertEquals("KST4Contest", packet.getDestination());
|
||||
assertEquals(List.of("STN1@44510", "O", "1", "1", "120"), packet.getDataTokens());
|
||||
assertTrue(packet.isAddressedTo("KST4Contest"));
|
||||
assertFalse(packet.isAddressedTo("STN2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyQuotedFieldsKeepFieldPositions() {
|
||||
List<String> packetFields = WinTestPacket.tokenize(ADDQSO_MESSAGE);
|
||||
|
||||
assertEquals("ADDQSO:", packetFields.get(0));
|
||||
assertEquals("STN1", packetFields.get(1));
|
||||
assertEquals("", packetFields.get(2));
|
||||
assertEquals("12", packetFields.get(7));
|
||||
assertEquals("DM2RN", packetFields.get(13));
|
||||
assertEquals(24, packetFields.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageWithoutWinTestFramingIsRejected() {
|
||||
assertNull(WinTestPacket.fromMessageText("no win-test message"));
|
||||
assertNull(WinTestPacket.fromDatagram(new byte[] { 0 }, 1));
|
||||
assertNull(WinTestPacket.fromDatagram(null, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
void broadcastPacketIsAcceptedForEveryStationName() {
|
||||
WinTestPacket packet = WinTestPacket.fromMessageText(ADDQSO_MESSAGE);
|
||||
|
||||
assertTrue(packet.isAddressedTo("KST4Contest"));
|
||||
assertFalse(packet.isChecksumPresent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
class CommandLineOptionsTest {
|
||||
|
||||
@Test
|
||||
void profileArgumentIsAcceptedInBothSpellings() {
|
||||
assertEquals("OP2", CommandLineOptions.parse(List.of("--profile=OP2")).getRequestedProfileName());
|
||||
assertEquals("OP2", CommandLineOptions.parse(List.of("--profile", "OP2")).getRequestedProfileName());
|
||||
assertEquals("DM5M Contest",
|
||||
CommandLineOptions.parse(List.of("--profile", "DM5M Contest")).getRequestedProfileName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingOrEmptyProfileArgumentsAreTreatedAsAbsent() {
|
||||
assertNull(CommandLineOptions.parse(List.of()).getRequestedProfileName());
|
||||
assertNull(CommandLineOptions.parse(null).getRequestedProfileName());
|
||||
assertNull(CommandLineOptions.parse(List.of("--profile=")).getRequestedProfileName());
|
||||
assertNull(CommandLineOptions.parse(List.of("--profile")).getRequestedProfileName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrelatedArgumentsAreIgnoredInsteadOfFailing() {
|
||||
assertEquals("OP2",
|
||||
CommandLineOptions.parse(List.of("--verbose", "--profile=OP2", "somefile.adi"))
|
||||
.getRequestedProfileName());
|
||||
assertNull(CommandLineOptions.parse(List.of("--verbose", "-x")).getRequestedProfileName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rememberedOptionsDefaultToEmptyInsteadOfNull() {
|
||||
CommandLineOptions.remember(null);
|
||||
assertNull(CommandLineOptions.remembered().getRequestedProfileName());
|
||||
|
||||
CommandLineOptions.remember(new CommandLineOptions("OP2"));
|
||||
assertEquals("OP2", CommandLineOptions.remembered().getRequestedProfileName());
|
||||
|
||||
CommandLineOptions.remember(null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
package kst4contest.view;
|
||||
|
||||
import kst4contest.controller.OperatorProfilePaths;
|
||||
import kst4contest.controller.OperatorProfileStore;
|
||||
import kst4contest.model.OperatorProfile;
|
||||
import kst4contest.model.OperatorProfileSelection;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class OperatorProfileBootstrapTest {
|
||||
|
||||
@TempDir
|
||||
Path temporaryDirectory;
|
||||
|
||||
@Test
|
||||
void installationWithoutRegistryStartsSilentlyOnTheHistoricLayout() {
|
||||
|
||||
AtomicInteger pickerInvocations = new AtomicInteger();
|
||||
OperatorProfileStore store = storeAt();
|
||||
|
||||
OperatorProfileSelection resolved = new OperatorProfileBootstrap().resolveAtStartup(
|
||||
store, new CommandLineOptions(null), countingPicker(pickerInvocations, null));
|
||||
|
||||
assertNotNull(resolved);
|
||||
assertEquals("preferences.xml", resolved.getPreferencesRelativeFileName());
|
||||
assertEquals("praktiKST.db", resolved.getWorkedDatabaseRelativeFileName());
|
||||
|
||||
// Nothing may be asked, and nothing may be written.
|
||||
assertEquals(0, pickerInvocations.get());
|
||||
assertTrue(store.loadProfiles().isEmpty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void singleProfileStartsWithoutAskingAnything() {
|
||||
|
||||
AtomicInteger pickerInvocations = new AtomicInteger();
|
||||
OperatorProfileStore store = storeAt();
|
||||
store.saveProfiles(List.of(OperatorProfilePaths.buildRootProfile("Default")), "default");
|
||||
|
||||
OperatorProfileSelection resolved = new OperatorProfileBootstrap().resolveAtStartup(
|
||||
store, new CommandLineOptions(null), countingPicker(pickerInvocations, null));
|
||||
|
||||
assertNotNull(resolved);
|
||||
assertEquals(0, pickerInvocations.get());
|
||||
}
|
||||
|
||||
@Test
|
||||
void twoProfilesAskTheOperatorAndPreselectTheLastUsedOne() {
|
||||
|
||||
OperatorProfileStore store = storeAt();
|
||||
OperatorProfile secondProfile = new OperatorProfile("OP2", "DN9APW", false, false);
|
||||
store.saveProfiles(
|
||||
List.of(OperatorProfilePaths.buildRootProfile("Default"), secondProfile), "OP2");
|
||||
|
||||
AtomicInteger pickerInvocations = new AtomicInteger();
|
||||
String[] observedPreselection = new String[1];
|
||||
|
||||
OperatorProfileSelection resolved = new OperatorProfileBootstrap().resolveAtStartup(
|
||||
store,
|
||||
new CommandLineOptions(null),
|
||||
(profiles, preselectedProfileId) -> {
|
||||
pickerInvocations.incrementAndGet();
|
||||
observedPreselection[0] = preselectedProfileId;
|
||||
return Optional.of(profiles.get(1));
|
||||
});
|
||||
|
||||
assertEquals(1, pickerInvocations.get());
|
||||
assertEquals("OP2", observedPreselection[0]);
|
||||
assertNotNull(resolved);
|
||||
assertEquals("profiles/OP2/praktiKST.db", resolved.getWorkedDatabaseRelativeFileName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aValidProfileArgumentSkipsThePicker() {
|
||||
|
||||
OperatorProfileStore store = storeAt();
|
||||
store.saveProfiles(
|
||||
List.of(OperatorProfilePaths.buildRootProfile("Default"),
|
||||
new OperatorProfile("OP2", "DN9APW", false, false)),
|
||||
"default");
|
||||
|
||||
AtomicInteger pickerInvocations = new AtomicInteger();
|
||||
OperatorProfileBootstrap bootstrap = new OperatorProfileBootstrap();
|
||||
|
||||
OperatorProfileSelection byId = bootstrap.resolveAtStartup(
|
||||
store, new CommandLineOptions("op2"), countingPicker(pickerInvocations, null));
|
||||
|
||||
assertEquals(0, pickerInvocations.get());
|
||||
assertEquals("profiles/OP2/preferences.xml", byId.getPreferencesRelativeFileName());
|
||||
assertNull(bootstrap.getStartupWarning());
|
||||
|
||||
OperatorProfileSelection byDisplayName = bootstrap.resolveAtStartup(
|
||||
store, new CommandLineOptions("DN9APW"), countingPicker(pickerInvocations, null));
|
||||
|
||||
assertEquals(0, pickerInvocations.get());
|
||||
assertEquals("profiles/OP2/preferences.xml", byDisplayName.getPreferencesRelativeFileName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownProfileArgumentWarnsAndFallsBackToTheNormalSelection() {
|
||||
|
||||
OperatorProfileStore store = storeAt();
|
||||
store.saveProfiles(
|
||||
List.of(OperatorProfilePaths.buildRootProfile("Default"),
|
||||
new OperatorProfile("OP2", "DN9APW", false, false)),
|
||||
"default");
|
||||
|
||||
AtomicInteger pickerInvocations = new AtomicInteger();
|
||||
OperatorProfileBootstrap bootstrap = new OperatorProfileBootstrap();
|
||||
|
||||
OperatorProfileSelection resolved = bootstrap.resolveAtStartup(
|
||||
store, new CommandLineOptions("NOPE"), countingPicker(pickerInvocations, 0));
|
||||
|
||||
assertEquals(1, pickerInvocations.get());
|
||||
assertNotNull(resolved);
|
||||
assertNotNull(bootstrap.getStartupWarning());
|
||||
assertTrue(bootstrap.getStartupWarning().contains("NOPE"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void quittingInThePickerYieldsNoSelection() {
|
||||
|
||||
OperatorProfileStore store = storeAt();
|
||||
store.saveProfiles(
|
||||
List.of(OperatorProfilePaths.buildRootProfile("Default"),
|
||||
new OperatorProfile("OP2", "DN9APW", false, false)),
|
||||
"default");
|
||||
|
||||
OperatorProfileSelection resolved = new OperatorProfileBootstrap().resolveAtStartup(
|
||||
store, new CommandLineOptions(null), (profiles, preselected) -> Optional.empty());
|
||||
|
||||
assertNull(resolved);
|
||||
}
|
||||
|
||||
private OperatorProfileChoiceRequester countingPicker(final AtomicInteger invocationCounter,
|
||||
final Integer profileIndexToChoose) {
|
||||
return (profiles, preselectedProfileId) -> {
|
||||
invocationCounter.incrementAndGet();
|
||||
|
||||
if (profileIndexToChoose == null) {
|
||||
return Optional.of(profiles.get(0));
|
||||
}
|
||||
|
||||
return Optional.of(profiles.get(profileIndexToChoose));
|
||||
};
|
||||
}
|
||||
|
||||
private OperatorProfileStore storeAt() {
|
||||
return new OperatorProfileStore(temporaryDirectory.resolve("profiles.xml").toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package kst4contest.view.map;
|
||||
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* Guards the property that made the terrain cache useless with several operator
|
||||
* profiles: it used to drop every cached profile whenever the configured callsign or
|
||||
* locator changed.
|
||||
*/
|
||||
class TerrainProfileCacheRepositoryTest {
|
||||
|
||||
private static final String USER_HOME_PROPERTY = "user.home";
|
||||
private static final String PROVIDER_ID = "test-provider";
|
||||
private static final int SAMPLE_COUNT = 3;
|
||||
|
||||
@TempDir
|
||||
Path temporaryHomeDirectory;
|
||||
|
||||
private String originalUserHome;
|
||||
|
||||
@BeforeEach
|
||||
void redirectUserHomeToTemporaryDirectory() {
|
||||
originalUserHome = System.getProperty(USER_HOME_PROPERTY);
|
||||
System.setProperty(USER_HOME_PROPERTY, temporaryHomeDirectory.toString());
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void restoreUserHome() {
|
||||
if (originalUserHome == null) {
|
||||
System.clearProperty(USER_HOME_PROPERTY);
|
||||
} else {
|
||||
System.setProperty(USER_HOME_PROPERTY, originalUserHome);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void profilesOfDifferentOwnersCoexistAndSurviveSwitchingBackAndForth() {
|
||||
|
||||
TerrainProfileCacheRepository repository = new TerrainProfileCacheRepository();
|
||||
|
||||
repository.save("DM5M", "JO51IJ", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID, profileData("station-a"));
|
||||
|
||||
// Another operator profile with a different callsign and locator.
|
||||
repository.save("DN9APW", "JN59AA", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID, profileData("station-b"));
|
||||
|
||||
Optional<TerrainProfileData> firstOwnerEntry = repository.load(
|
||||
"DM5M", "JO51IJ", "DL0ABC", "JN49FK", SAMPLE_COUNT, PROVIDER_ID);
|
||||
Optional<TerrainProfileData> secondOwnerEntry = repository.load(
|
||||
"DN9APW", "JN59AA", "DL0ABC", "JN49FK", SAMPLE_COUNT, PROVIDER_ID);
|
||||
|
||||
assertTrue(firstOwnerEntry.isPresent(),
|
||||
"Working under a second operator identity must not discard the first one's cache");
|
||||
assertTrue(secondOwnerEntry.isPresent());
|
||||
assertEquals("station-a", firstOwnerEntry.get().sourceName());
|
||||
assertEquals("station-b", secondOwnerEntry.get().sourceName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnknownOwnerSimplyMissesTheCacheInsteadOfClearingIt() {
|
||||
|
||||
TerrainProfileCacheRepository repository = new TerrainProfileCacheRepository();
|
||||
|
||||
repository.save("DM5M", "JO51IJ", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID, profileData("station-a"));
|
||||
|
||||
assertTrue(repository.load("DL0XYZ", "JO60AA", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID).isEmpty());
|
||||
|
||||
assertTrue(repository.load("DM5M", "JO51IJ", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID).isPresent(),
|
||||
"A cache miss of one owner must not remove the entries of another");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theCacheLivesInItsOwnGlobalFileAndNotInTheWorkedStationDatabase() {
|
||||
|
||||
TerrainProfileCacheRepository repository = new TerrainProfileCacheRepository();
|
||||
repository.save("DM5M", "JO51IJ", "DL0ABC", "JN49FK",
|
||||
SAMPLE_COUNT, PROVIDER_ID, profileData("station-a"));
|
||||
|
||||
Path applicationDirectory = temporaryHomeDirectory.resolve(".praktiKST");
|
||||
|
||||
assertTrue(Files.exists(applicationDirectory.resolve("terrainprofilecache.db")));
|
||||
assertFalse(Files.exists(applicationDirectory.resolve("praktiKST.db")),
|
||||
"The terrain cache must not pull in the worked station database");
|
||||
}
|
||||
|
||||
private static TerrainProfileData profileData(final String sourceName) {
|
||||
return new TerrainProfileData(
|
||||
List.of(
|
||||
new PathProfilePoint(0.0, 51.0, 10.0, 100.0),
|
||||
new PathProfilePoint(10.0, 51.1, 10.1, 220.0),
|
||||
new PathProfilePoint(20.0, 51.2, 10.2, 150.0)),
|
||||
sourceName,
|
||||
false);
|
||||
}
|
||||
}
|
||||
+12
-1
@@ -2391,4 +2391,15 @@ SM6VTZ;Chris .135;JO58UJ;StringProperty [value: 144.135]; wkd true; wkd144 true;
|
||||
SM6VTZ;Chris .135;JO58UJ;StringProperty [value: 432.135]; wkd true; wkd144 true; wkd432true; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; 2: 144/432 MHz
|
||||
LA0BY;Stefan @ hilltop;JO59IX;StringProperty [value: 144.062]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; 2: 144/432 MHz
|
||||
LA0BY;null;JO49ML;StringProperty [value: null]; wkd true; wkd144 false; wkd432true; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
OV3T;null;JO46CM;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
OV3T;null;JO46CM;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
DK0TR;null;JO40QL;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
DD0VF;null;JO61TB;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F5DYD;null;JN03KG;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F6DRO;null;JN03TJ;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F4VRB;null;IN98PT;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
DK0TR;null;JO40QL;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
DD0VF;null;JO61TB;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F5DYD;null;JN03KG;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F6DRO;null;JN03TJ;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
F4VRB;null;IN98PT;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
DK5KMA;null;JO50IK;StringProperty [value: null]; wkd true; wkd144 true; wkd432false; wkd1240false; wkd2300false; wkd3400false; wkd5600false; wkd10Gfalse ; null
|
||||
@@ -49,6 +49,8 @@ The general UDP listener processes packets from UCXLog, N1MM+, QARTest and DXLog
|
||||
|
||||
Win-Test uses a separate listener for its native network protocol. KST4Contest resolves the Win-Test band ID, including 50 and 70 MHz, and stores the resulting Worked information in the same internal database.
|
||||
|
||||
QSOs logged before KST4Contest was started are recovered from Win-Test as well. As soon as a Win-Test station is detected, the missing part of its log is requested over the native protocol, so stations already worked are marked as worked even when the client joins the contest late. The recovery needs no setting, keeps running to close gaps caused by lost packets, and covers every log in a multi-station network.
|
||||
|
||||
STATUS packets can also update the local QRG when QRG synchronisation is enabled and valid packets actually arrive. Enabling the source alone does not supply a frequency. In multi-operator networks, a station-name filter prevents STATUS packets from another operating position from replacing the frequency of the intended radio.
|
||||
|
||||
Win-Test can additionally receive skeds created in KST4Contest. The handover only takes place when a QRG matching the selected band can be determined. No fixed fallback frequency is inserted merely to make the packet technically valid.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
---
|
||||
title: Version 1.43.1 released
|
||||
summary: Reliable log synchronisation, persistent layouts and better DX Cluster compatibility
|
||||
date: 2026-09-03
|
||||
---
|
||||
|
||||
## Version 1.43.1
|
||||
|
||||
Version 1.43 focuses on the parts of KST4Contest that have to keep working during a long contest: ON4KST connection monitoring, log synchronisation, Worked information and the data sent to external logging software.
|
||||
|
||||
The first v1.43.0 packages already contained all functional changes described below, but some embedded version metadata still identified the build as version 1.42. v1.43.1 corrects this. If you already downloaded v1.43.0, use v1.43.1 instead.
|
||||
|
||||
### What changed
|
||||
|
||||
- **More reliable log synchronisation:** The Simplelogfile parser now closes the selected file after every pass, handles suffix variants by their base callsign and reports when a missing file has been created. UCXLog-compatible packets and Win-Test events share the same band normalisation, including the existing microwave bands.
|
||||
- **Correct Worked state after login:** Persisted Worked information is applied before the initial ON4KST user list becomes visible. Reconnects and both chat categories therefore start with the correct state.
|
||||
- **No false disconnect on a quiet server:** KST4Contest actively checks a quiet ON4KST session before treating it as dead. A period without new activity lines no longer causes an unnecessary reconnect.
|
||||
- **DX Cluster compatibility:** Local spots now use a fixed, DXSpider-compatible 75-character line format that is also accepted reliably by DXLog. Frequencies up to 24 GHz keep the required column positions.
|
||||
- **Layouts that stay where you put them:** Table column widths, window sizes and relevant dividers are saved automatically. Truncated table values expose their full text in a tooltip.
|
||||
- **Controllable map grouping:** **Group nearby stations** switches map clustering on or off without changing the current viewport or selected station.
|
||||
- **Smaller corrections:** Complete QRGs without a decimal separator are recognised across the supported bands, and private-message age highlighting no longer remains attached to reused table rows.
|
||||
|
||||
The complete technical list is available in the [changelog](/manual/en/changelog/) and the [GitHub release notes](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.1).
|
||||
|
||||
### Getting it
|
||||
|
||||
Packages for Windows, Linux and macOS are available on the [download page](/download/) and in the [GitHub release](https://github.com/praktimarc/kst4contest/releases/tag/v1.43.1). The AUR packages are updated through their normal release workflow.
|
||||
|
||||
The German and English manuals have also been revised. The new contest-workflow chapter connects the individual functions into a practical operating sequence instead of describing them only in isolation. 73
|
||||
Reference in New Issue
Block a user