fix: Release-Härtung, JSON-Dateiformat und Quality-Meilenstein

- Export: Runtime-Bridge-Autoload und Skater-GLB samt Texturen einschließen, Editor-Addons ausschließen
- tools/check_export.sh als headless Smoke-Test; ./tools/test.sh --export
- RoutineFile: JSON-Format, atomare Saves, Whitelist für Legacy-.tres
- Überschreibschutz für Speichern unter/Export, Session- und Autosave-Restore
- Globaler Delete-Shortcut blockiert bei offenen Dialogen
- Sync akzeptiert .json und Legacy-.tres, Konfliktnamen behalten die Endung
- Tests für Dateiformat, Überschreiben, Session und Legacy-Schutz
- Quality-Meilenstein mit 'Als Nächstes' und 'Danach' in der Roadmap
This commit is contained in:
torsten 2026-11-03 23:48:01 +01:00
parent edf12a11c2
commit 7bbd8c9c1d
21 changed files with 1711 additions and 158 deletions

View file

@ -11,6 +11,16 @@ Beim Hochladen eines macOS-Builds auf den Webspace (programmschmiede.de):
- Download-Links relativ zur `index.html` setzen, z. B.
`rinkplanner/download/rinkplanner.zip`.
## Dateiformat und Release-Check
- Neue Kürdateien werden als JSON gespeichert (`RoutineFile`). `.tres` ist
nur noch Legacy-Import und wird vor dem Laden per Whitelist geprüft; nicht
wieder als neues Speicherformat einführen.
- Vor einem Release `./tools/check_export.sh` laufen lassen. Es baut den
Linux-Export, startet ihn headless und prüft Autoload, Testausschluss und
die Skater-Texturen. Die GLB muss vorher per `tools/sync_assets.sh --sync`
vorliegen.
## MCP-Werkzeuge
- **Godot:** `godot-mcp` steuert das Projekt über `--project rinkplanner/rinkplanner`.

View file

@ -28,6 +28,7 @@ wird nicht weiterentwickelt. Phase 2 konsumiert später dasselbe Datenmodell
├── project.godot
├── src/
│ ├── core/model/ # reine Daten-Resources
│ ├── core/io/ # JSON-Dateiformat, Legacy-Import
│ ├── core/rules/ # ISU-Katalog (JSON + Lookup)
│ ├── presentation3d/ # 3D-Vorschau, lazy geladen
│ └── whiteboard/ # Phase 1: view / ctrl / io
@ -60,6 +61,7 @@ Implementiert in `rinkplanner/src/core/model/`:
| `RoutineSection` | chronologischer Block, Ghosting-Einheit, Segmentliste |
| `PathSegment` | Pfad mit Richtung, Kante, Dauer, Element-Marker, Sprungkombination und Label |
| `RinkDimensions` | Maße, Koordinaten, Punkte-/Kurvenprüfung |
| `RoutineFile` | JSON-Serialisierung, atomare Saves, Legacy-`.tres`-Import |
Implementiert in `rinkplanner/src/core/rules/`:
@ -423,31 +425,47 @@ ggf. eines nach `touchend` (300-ms-Guard).
`user://exports/`.
- **PDF** ist nicht nativ in Godot. Erste Stufe: Browser-Druck aus SVG;
eine echte PDF-Ausgabe ist ein separates Arbeitspaket.
- **Persistenz** erfolgt lokal als `.tres`-Ressourcen unter
`user://routines/`. `Routine.schema_version` (aktuell 2) schützt vor
inkompatiblen neueren Dateien; Schema-1-Dateien werden beim Laden migriert
und behalten ihre bisherige Dauer. Die Elementfelder kamen additiv mit
Defaults hinzu, deshalb bleibt das Schema bei 2. Benannte Kürläufe werden über das Datei-Menü gespeichert
und geladen; der Öffnen-Dialog nutzt 48-px-Buttons statt einer kleinen
Dateiliste.
- **Autosave** schreibt nach 1,5 s Inaktivität nach `user://autosave.tres`
und wird beim Start automatisch wiederhergestellt. Der Dirty-State wird im
Fenstertitel als `*` angezeigt. Beim Verlassen wird zusätzlich gespeichert.
- **Persistenz** erfolgt lokal als JSON unter `user://routines/`
(`RoutineFile`, Format `rinkplanner.routine`). Die Datei enthält
`schema_version` (aktuell 2); neuere Schemata werden abgelehnt,
Schema-1-Dateien beim Laden migriert. Die Elementfelder kamen additiv mit
Defaults hinzu, deshalb bleibt das Schema bei 2. Legacy-`.tres`-Dateien
bleiben lesbar: Vor `ResourceLoader.load` prüft `RoutineFile` eine
Whitelist (nur die vier Modellskripte, kein eingebettetes GDScript, keine
Szenen). Neue Speicherungen schreiben immer `.json`; eine geöffnete
`.tres` wird beim nächsten Speichern zur `.json`-Datei migriert.
Speichern läuft atomar über eine Temp-Datei mit `.bak`-Sicherung. Benannte
Kürläufe werden über das Datei-Menü gespeichert und geladen; der
Öffnen-Dialog zeigt `.json` und Legacy-`.tres`, wobei eine vorhandene
`.json` die gleichnamige `.tres` verdeckt.
- **Autosave** schreibt nach 1,5 s Inaktivität nur bei ungespeicherten
Änderungen nach `user://autosave.json`; beim Speichern oder Öffnen einer
Datei wird der Autosave entfernt. Der letzte Dateipfad liegt in
`user://session.cfg`. Beim Start wird der Autosave nur übernommen, wenn er
neuer als die zugehörige Datei ist; dann bleibt der Dateipfad erhalten und
die Kür ist als geändert markiert. Der Dirty-State wird im Fenstertitel als
`*` angezeigt. Beim Verlassen wird bei Änderungen zusätzlich gespeichert.
- **Überschreibschutz:** „Speichern unter“ und Export fragen nach, bevor eine
vorhandene Datei ersetzt wird.
- **Builds:** Linux, Windows, macOS und Android über
`tools/export_*.sh`; Presets in `rinkplanner/export_presets.cfg`.
Android nutzt das Template-Export-Verfahren ohne Gradle-Projekt,
`arm64-v8a`, `minSdk 24`, `targetSdk 36`, Landscape und Immersive Mode.
Details in `docs/builds.md`.
Der Export enthält die Skater-GLB (`assets/external/characters/*.glb`) und
den Runtime-Bridge-Autoload, aber keine Test-, Prototyp- oder
Editor-Addon-Skripte. `tools/check_export.sh` exportiert und startet den
Linux-Build headless als Smoke-Test. Details in `docs/builds.md`.
- **Lokale Daten:** `user://` liegt pro Plattform getrennt (Linux
`~/.local/share/godot/app_userdata/Rinkplanner/`, Android im
app-internen Speicher).
- **Kontosync:** manueller FTP-/FTPS-Abgleich der `.tres`-Dateien über
`FtpClient`, `SyncPlan` und `RoutineSync`; Details in `docs/sync.md`.
Zugangsdaten liegen in `user://sync.cfg`, der letzte gemeinsame Stand in
`user://sync_state.cfg`. Beim ersten Abgleich einer beidseitig vorhandenen
Datei übernimmt die Serverfassung den Namen, die lokale bleibt als
`(Lokal …)`-Kopie; bei einem echten Konflikt bleibt die lokale Fassung
Hauptdatei und die Serverfassung kommt als `(Server …)`-Kopie dazu.
- **Kontosync:** manueller FTP-/FTPS-Abgleich der `.json`- und
Legacy-`.tres`-Dateien über `FtpClient`, `SyncPlan` und `RoutineSync`;
Details in `docs/sync.md`. Zugangsdaten liegen in `user://sync.cfg`, der
letzte gemeinsame Stand in `user://sync_state.cfg`. Beim ersten Abgleich
einer beidseitig vorhandenen Datei übernimmt die Serverfassung den Namen,
die lokale bleibt als `(Lokal …)`-Kopie; bei einem echten Konflikt bleibt
die lokale Fassung Hauptdatei und die Serverfassung kommt als
`(Server …)`-Kopie dazu. Konfliktnamen behalten die jeweilige Endung.
## 7. Tests
@ -455,6 +473,8 @@ Headless, ohne Editor und ohne Display:
```bash
./tools/test.sh
# inklusive Export-Smoke-Test:
./tools/test.sh --export
```
Aktueller Stand:
@ -462,6 +482,10 @@ Aktueller Stand:
- **Model:** 100 Assertions für Rink-Geometrie, Clamping, Segment-Timing,
Timing-Modi, Template-Metadaten, Element-Marker samt Kürzel-/Level-/Dauer-Grenzen,
Schema-Version, Section-Aggregation und Routine-Validierung.
- **Dateiformat:** 54 Assertions für JSON-Roundtrip (inkl. Kurven-Handles,
Elemente, Features, Kombinationen), Schema-/Enum-Fehler, atomare Saves und
die Legacy-`.tres`-Whitelist (eingebettetes GDScript und fremde Skripte
werden vor dem Laden abgelehnt).
- **Regelwerk:** 169 Assertions für Katalog-Metadaten, Saison/Quelle,
Sprung-/Pirouetten-/Sequenz-Base-Values, Level-Auflösung, Kürzel-Suffixe,
Case-Insensitivität, Vorschläge, Segment-Integration und fehlerhafte Kataloge.
@ -478,14 +502,16 @@ Aktueller Stand:
- **Adult-Kategorien:** 70 Assertions für Metadaten, Gold/Silver/Bronze,
Sprungerlaubnis, Level-Caps, Pflichtelemente, Wiederholungen, Kombinationen,
Dauer und unbekannte Kategorien.
- **Whiteboard:** 297 Assertions für Controller-Verdrahtung, Segmenterzeugung,
- **Whiteboard:** 314 Assertions für Controller-Verdrahtung, Segmenterzeugung,
Linien-/Bogenpfade, Klemmen an der Bande, Auswahl, Griff- und
Richtungs-/Kanten-Bearbeitung, Segmentlöschung, Element-Marker (Setzen,
Typwechsel, Inspector inkl. Kürzelauswahl, Standzeit, Base-Value- und
Feature-Hinweis, Feature-Menü, strukturierte Sprungkombinationen,
Verschieben, Löschen), Section-Verwaltung,
Ghosting-Zustand, Segment-Labels inklusive Dialog und Sichtbarkeits-Schalter,
Speichern/Laden, Schema-Prüfung, Dirty-State, Prüfdialog mit
Speichern/Laden, Schema-Prüfung, Dirty-State,
Überschreibschutz, Autosave-/Session-Wiederherstellung und den
Dialog-sicheren Delete-Shortcut, Prüfdialog mit
Punktschätzung und inline änderbaren Annahmen,
Navigationsmodus und den Maus-Drag-Pfad.
- **History:** 53 Assertions für Undo/Redo von Segmenten, Kanten, Labels, Sections,
@ -507,8 +533,9 @@ Aktueller Stand:
Leistenlayout bei 1024 und 1400 px.
- **Performance:** Stresstest mit 480 Segmenten in 12 Sections; die mittlere
Redraw-Zeit muss unter 120 ms bleiben (aktuell ca. 7–10 ms).
- **Sync:** 32 Assertions für Vergleichsregeln, Konfliktnamen, Zeitstempel,
PASV/EPSV/MDTM-Parsing, Sync-Stand und die Einstellungs-Verdrahtung.
- **Sync:** 34 Assertions für Vergleichsregeln, Konfliktnamen (JSON und
Legacy-`.tres`), Zeitstempel, PASV/EPSV/MDTM-Parsing, Sync-Stand und die
Einstellungs-Verdrahtung.
Der FTP-Client wurde zusätzlich gegen den echten Zielserver geprüft
(Upload, Download, Übernahme, Konflikt, Aufräumen).
- **3D-Assets:** 57 Assertions für Manifest-Schema, Pfade, FTP-Pfade,
@ -523,8 +550,13 @@ Aktueller Stand:
--dry-run`), nicht in `./tools/test.sh`, weil Blender und ffmpeg
Host-Abhängigkeiten sind.
`tools/check_export.sh` baut zusätzlich den Linux-Release, startet ihn
headless und prüft auf Autoload-/Startfehler, ausgeschlossene Tests und die
Skater-GLB im Build.
Autosave/Restore wird zusätzlich in einem isolierten `XDG_DATA_HOME`
end-to-end geprüft.
end-to-end geprüft (neuer Autosave hängt am letzten Dateipfad, sauberes
Speichern entfernt ihn).
Visuelle Smoke-Tests laufen zusätzlich über `xvfb-run` und einen
Viewport-Screenshot; sie ersetzen die headless Tests nicht.

View file

@ -179,10 +179,12 @@ eine still veränderte Workbench-Datei wird nicht kopiert, sondern gemeldet.
- `assets/external/` ist gitignored und wird nach dem Sync importiert.
- `asset_manifest.json` wird über `include_filter="*.json"` mit exportiert.
- Die aktuellen Phase-1-Export-Presets schließen `assets/external/*` aus.
Für einen 3D-Build muss bewusst ein eigenes Preset die Dateien einschließen.
Desktop kann die GLB einbetten; für Android sind 1K-Texturen oder ein
separater Asset-Pack vorgesehen.
- Die Export-Presets schließen Test- und Gewichts-Assets
(`weights_rings*`) sowie `assets/models/*` aus, nehmen aber die
Skater-GLB samt ihren Quelltexturen
(`assets/external/characters/skater_figure_glide_v006*`) mit. Fehlt die
GLB auf einem frischen Checkout, baut `Skater3D` weiterhin den Platzhalter;
`tools/check_export.sh` weist darauf hin und prüft die Texturen im Build.
- Phase 1 bleibt unberührt: Der 2D-Code lädt keine 3D-Ressourcen.
## Aktueller Bestand

View file

@ -9,17 +9,22 @@ nicht von Browser-Speicherlimits abhängt.
| Ziel | Preset | Ausgabe | Größe (ca.) |
| :--- | :--- | :--- | :--- |
| Linux x86_64 | `Linux` | `build/linux/rinkplanner.x86_64` | 77 MB |
| Windows x86_64 | `Windows` | `build/windows/rinkplanner.exe` | 113 MB |
| macOS universal | `macOS` | `build/macos/rinkplanner.zip` | 64 MB |
| Android arm64 | `Android` | `build/android/rinkplanner-debug.apk` | 28 MB |
| Linux x86_64 | `Linux` | `build/linux/rinkplanner.x86_64` | 80 MB |
| Windows x86_64 | `Windows` | `build/windows/rinkplanner.exe` | 116 MB |
| macOS universal | `macOS` | `build/macos/rinkplanner.zip` | 67 MB |
| Android arm64 | `Android` | `build/android/rinkplanner-debug.apk` | 31 MB |
Die PCK ist bei Linux und Windows **eingebettet** (eine Datei zum
Weitergeben). `build/` ist nicht versioniert.
Weitergeben). `build/` ist nicht versioniert. Seit die Skater-GLB samt
Texturen in den Exporten liegt (`docs/assets.md`), sind die Builds etwa
6 MB größer; die Werte sind Richtwerte.
## Voraussetzungen
- Godot **4.7.2** (oder `GODOT=/pfad/zu/godot` setzen)
- Für die 3D-Vorschau im Build: `tools/sync_assets.sh --sync` (GLB plus
Texturen unter `assets/external/characters/`); ohne diese Dateien baut der
Export den Platzhalter.
- Export-Templates derselben Version unter
`~/.local/share/godot/export_templates/4.7.2.stable/`
- Für Android zusätzlich JDK 17 + Android SDK (siehe unten)
@ -148,16 +153,34 @@ Godot schreibt `user://` pro Plattform getrennt:
| macOS | `~/Library/Application Support/Godot/app_userdata/Rinkplanner/` |
| Android | App-interner Speicher (`/data/data/de.rinkplanner.app/files/`) |
Dort liegen `routines/`, `autosave.tres` und `exports/`. Die Android-Daten
Dort liegen `routines/`, `autosave.json` und `exports/`. Die Android-Daten
sind ohne Root nicht direkt sichtbar – der Export-Dialog der App schreibt
nach `user://exports/`, von dort kann man Dateien über einen Dateimanager
mit App-Zugriff oder `adb pull` holen:
```bash
adb shell run-as de.rinkplanner.app ls files/
adb exec-out run-as de.rinkplanner.app cat files/routines/kuer.tres > kuer.tres
adb exec-out run-as de.rinkplanner.app cat files/routines/kuer.json > kuer.json
```
## Export-Smoke-Test
`tools/check_export.sh` baut den Linux-Release in ein temporäres Verzeichnis,
startet ihn headless und bricht bei Start-/Autoload-Fehlern ab. Zusätzlich
prüft es, dass keine Testskripte im Build landen und die Skater-Szene samt
Texturen enthalten ist, sofern die GLB lokal unter
`assets/external/characters/` liegt.
```bash
./tools/check_export.sh
# oder zusammen mit den Headless-Tests:
./tools/test.sh --export
```
Fehlt die GLB auf einem frischen Checkout, bricht der Test mit einem Hinweis
auf `tools/sync_assets.sh --sync` ab. Für einen reinen Starttest ohne
3D-Asset: `./tools/check_export.sh --allow-placeholder`.
## Bekannte Grenzen
- Die obere Werkzeugleiste hat eine Mindestbreite von ca. 994 logischen
@ -175,9 +198,9 @@ adb exec-out run-as de.rinkplanner.app cat files/routines/kuer.tres > kuer.tres
Der Debug-Keystore ist nur zum Testen.
- **Windows/macOS:** siehe Hinweise oben (rcedit, Codesign/Notarization).
## Nächster Schritt: Kontosync
## Kontosync
Geplant ist ein manueller Sync über FTP: Ein Button lädt die neuesten
`.tres`-Dateien je Kür hoch bzw. herunter, Konflikte bleiben als Kopien mit
Zeitstempel erhalten. Zugangsdaten liegen in den App-Einstellungen
(`user://`), nicht im Repository.
Der manuelle Sync über FTP lädt die neuesten `.json`-Dateien
(Legacy-`.tres` weiterhin) je Kür hoch bzw. herunter, Konflikte bleiben als
Kopien mit Zeitstempel erhalten. Zugangsdaten liegen in den
App-Einstellungen (`user://`), nicht im Repository.

View file

@ -1,6 +1,6 @@
# Rinkplanner – Roadmap
Stand: 2026-11-01 (ISU 2026/27, Adult-Kategorien Gold/Silver/Bronze; Sync-Komfort und UI-Refactoring zurückgestellt)
Stand: 2026-11-03 (ISU 2026/27, Adult-Kategorien Gold/Silver/Bronze; JSON-Dateiformat, Export-Smoke-Test und Quality-Meilenstein ergänzt)
Diese Reihenfolge ist die verbindliche Arbeitsgrundlage für Phase 1. Änderungen
nur bewusst und nach Rücksprache. Letzte Erkenntnisse:
`docs/findings-2026-10-31-arm-gewichte.md`.
@ -25,7 +25,8 @@ Voraussetzung für Phase 1.
- [x] Segment löschen, Undo/Redo mit Snapshot-Historie
- [x] Sections anlegen, umbenennen, löschen, sortieren
- [x] Ghosting inaktiver Sections mit 20 % Deckkraft
- [x] Speichern/Laden als `.tres`, Schema-Prüfung, Autosave und Restore
- [x] Speichern/Laden als JSON, Schema-Prüfung, atomare Saves, Autosave und
Session-Restore (Legacy-`.tres` lesbar)
- [x] Playback-Dot mit Blickrichtung, Timeline, Play/Pause/Reset und
Geschwindigkeit 0,25×–2,0×
- [x] Geschwindigkeits-Arbeitsannahmen in `docs/speed-assumptions.md`
@ -86,7 +87,8 @@ Voraussetzung für Phase 1.
- [x] Sync-Einstellungen in der App (FTP-Host, Port, Benutzer, Passwort,
Verzeichnis, FTPS, Zertifikatsprüfung), Zugangsdaten unter `user://`
- [x] Manueller Sync: `.tres` je Kür laden/hochladen, Sync-Stand lokal
- [x] Manueller Sync: `.json` je Kür laden/hochladen (Legacy-`.tres` weiterhin),
Sync-Stand lokal
- [x] Konflikte als Kopien mit Server-Zeitstempel behalten
- [x] Fortschritt und Zusammenfassung in der Oberfläche
- [x] FTP/FTPS-Client ohne externe Bibliothek
@ -174,12 +176,66 @@ UI-Refactoring sind zurückgestellt, weil der bestehende Stand für Tests
genügt und die endgültige Sync-Architektur (PHP-Webserver) sowie das
UI-Feedback der Tester ohnehin noch ausstehen.
## Quality-Meilenstein
Stand: 2026-11-03. Ziel: den PoC release- und wartbar machen, ohne die
fachliche Roadmap zu blockieren. Die Sofortmaßnahmen aus der
Projekt-Durchsicht sind umgesetzt; die folgenden Punkte sind die nächsten
Schritte.
### Erledigt: Sofortmaßnahmen (2026-11-03)
- [x] Export startet ohne Autoload-/Startfehler; der Runtime-Bridge-Autoload
ist im Export enthalten, Editor-Addons bleiben draußen.
- [x] 3D-Skater in Desktop-/Android-Exporten: GLB plus Quelltexturen sind
eingeschlossen; `tools/check_export.sh` prüft den headless Start, das
Fehlen von Testskripten und die Texturen.
- [x] Kürdateien als JSON (`RoutineFile`, `rinkplanner.routine`, Limits,
Schema-Prüfung). Legacy-`.tres` bleibt lesbar, wird aber vor
`ResourceLoader.load` per Whitelist geprüft (kein eingebettetes GDScript,
nur Modellskripte).
- [x] Atomare Saves über Temp + `.bak`, Überschreibschutz für
„Speichern unter“ und Export, letzter Pfad in `user://session.cfg`;
Autosave wird beim Start nur bei neueren Änderungen übernommen und bleibt
am letzten Dateipfad.
- [x] Entf/Backspace löscht nicht mehr durch offene Dialoge (modal guard).
### Als Nächstes
- [ ] `WhiteboardController` in Services/Panels zerlegen: Datei-I/O, Sync,
Playback, Validierung, Element-Inspector, Section-Liste. Ziel: < 1.500
Zeilen pro Datei, keine 100 `%`-Lookups in einem Skript.
- [ ] Gemeinsamer Test-Harness (oder gdUnit4), Timeout pro Testlauf,
Coverage; CI auf dem Gitea-/Forgejo-Remote mit `tools/test.sh` und
`tools/check_export.sh`.
- [ ] Saison datengetrieben: Saison-Auswahl/Default aus `data/`, 2025/26
auswählbar machen oder entfernen; Regelstand im UI anzeigen.
- [ ] Android-Export teilen: Share-Intent/SAF statt nur `user://exports/`.
- [ ] `Ctrl+S`/`Ctrl+O`/`Ctrl+N` und sichtbarer Speicherstatus (auch ohne
Fenstertitel auf Android).
### Danach
- [ ] Theme-Ressource + zentrale UI-Texte (`tr()`/CSV), kompakte Labels nicht
mehr im Controller; Dark/Light und skalierbare Schriftgrößen.
- [ ] Canvas: Culling/Dirty-Regions, Kurven-Cache auch für Pan/Zoom;
Perf-Test mit realistischem Budget (< 16 ms bei 480 Segmenten).
- [ ] Doku konsolidieren: 18 `findings-*.md` nach `docs/notes/` oder ins
Archiv; Architektur/Manual als aktuelle Quellen; Docstrings und
Assertion-Zahlen pflegen.
- [ ] Altlasten entfernen: `Flieger.obj` (nur Prototyp), alte
`.godot`-Importe, eingefrorenen Prototyp; `.gitattributes` um Binärregeln
ergänzen.
- [ ] Release: Lizenz, Changelog, Version aus einer Quelle, signierte
macOS-/Android-Builds.
## Querschnittsaufgaben
- [ ] Tests bei jedem Feature erweitern; `./tools/test.sh` bleibt grün
- [ ] MCP gezielt für Editor-/Runtime-Verifikation nutzen, sobald der Editor
mit dem richtigen Projektpfad läuft
- [ ] Persistenz-Backups und Dateiverwaltung prüfen
- [x] Persistenz-Backups und Dateiverwaltung prüfen (atomare Saves,
`.bak`-Sicherung, Autosave-/Session-Regeln)
- [ ] Architektur- und Geschwindigkeitsdokumentation aktuell halten
## Phase 2 – 3D-Präsentation

View file

@ -23,8 +23,12 @@ Danach **Datei → Jetzt synchronisieren**.
## Was passiert
- Jede Kür liegt als `.tres` unter `user://routines/` und wird 1:1 in das
FTP-Verzeichnis gespiegelt (flach, keine Unterordner).
- Jede Kür liegt als `.json` unter `user://routines/` und wird 1:1 in das
FTP-Verzeichnis gespiegelt (flach, keine Unterordner). Legacy-`.tres`-
Dateien werden weiterhin mit synchronisiert, damit bestehende Installationen
ihre Serverkopien nicht verlieren; neue Speicherungen schreiben `.json`.
Beim Laden wird eine `.tres` vor dem `ResourceLoader` gegen eine Whitelist
geprüft (nur Modellskripte, kein eingebettetes GDScript).
- Der Sync vergleicht pro Datei den letzten gemeinsamen Stand
(`user://sync_state.cfg`) mit den aktuellen Zeitstempeln:
@ -50,17 +54,19 @@ kein „Update“, sondern eine Kollision:
- **Erster Sync einer Datei auf beiden Seiten** (kein gemeinsamer Stand):
Die **Serverfassung übernimmt den Namen**, die lokale Fassung bleibt als
`name (Lokal JJJJ-MM-TT HHMM).tres` daneben. So bekommt ein neues Gerät die
`name (Lokal JJJJ-MM-TT HHMM).json` daneben. So bekommt ein neues Gerät die
gemeinsame Version, ohne die lokale Arbeit zu verlieren.
- **Beide Seiten seit dem letzten Sync geändert**: Die lokale Fassung bleibt
Hauptdatei, die Serverfassung kommt als
`name (Server JJJJ-MM-TT HHMM).tres` dazu. Beim nächsten Sync wird diese
`name (Server JJJJ-MM-TT HHMM).json` dazu. Beim nächsten Sync wird diese
Kopie als neue Kür hochgeladen. Zusammenführen musst du selbst.
Die Kopien behalten die Endung der Ausgangsdatei; bei Legacy-`.tres`
entstehen also weiterhin `.tres`-Kopien.
Wenn du auf dem Tablet also eine leere „Testkür1“ anlegst, obwohl es die
Desktop-Version schon gibt, hast du nach dem Sync zwei Dateien: die
Desktop-Version unter dem normalen Namen und deine leere Fassung als
`testkür1 (Lokal …).tres`. Besser: erst synchronisieren, dann die vorhandene
`testkür1 (Lokal …).json`. Besser: erst synchronisieren, dann die vorhandene
Kür öffnen und bearbeiten.
- Vor dem Sync wird eine geänderte, bereits gespeicherte Kür automatisch
gespeichert. Eine noch nie gespeicherte Kür öffnet zuerst „Speichern unter“.
@ -82,6 +88,11 @@ Kür öffnen und bearbeiten.
- Uploads gehen zuerst nach `name.uploading` und werden dann umbenannt
(falls der Server das verweigert: direkter Upload).
- Downloads landen in `name.part` und ersetzen die Zieldatei erst danach.
- Heruntergeladene `.json`-Dateien werden als JSON validiert; Legacy-`.tres`
laufen vor dem Laden durch die Whitelist in `RoutineFile`. Ein präparierter
Server kann damit keine eingebetteten GDScripts ausführen.
- Neue Speicherungen sind JSON; der Sync akzeptiert weiterhin `.tres`, damit
bestehende Dateien auf Server und Tablet nicht verschwinden.
- Zugangsdaten liegen in `user://sync.cfg` (Klartext, app-privat). Auf
Android ist das der interne App-Speicher, auf dem Desktop
`~/.local/share/godot/app_userdata/Rinkplanner/`.

View file

@ -7,8 +7,8 @@ advanced_options=false
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="*.json"
exclude_filter="tests/*,prototype/*,docs/*,addons/*,assets/models/*,assets/external/*"
include_filter="*.json,assets/external/characters/*.glb"
exclude_filter="tests/*,prototype/*,docs/*,addons/script-ide/*,addons/godot_ai_bridge/godot_ai_bridge.gd,addons/godot_ai_bridge/message_handler.gd,addons/godot_ai_bridge/ws_server.gd,assets/models/*,assets/external/characters/weights_rings*"
export_path="build/linux/rinkplanner.x86_64"
patches=PackedStringArray()
encryption_include_filters=""
@ -39,8 +39,8 @@ advanced_options=false
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="*.json"
exclude_filter="tests/*,prototype/*,docs/*,addons/*,assets/models/*,assets/external/*"
include_filter="*.json,assets/external/characters/*.glb"
exclude_filter="tests/*,prototype/*,docs/*,addons/script-ide/*,addons/godot_ai_bridge/godot_ai_bridge.gd,addons/godot_ai_bridge/message_handler.gd,addons/godot_ai_bridge/ws_server.gd,assets/models/*,assets/external/characters/weights_rings*"
export_path="build/windows/rinkplanner.exe"
patches=PackedStringArray()
encryption_include_filters=""
@ -94,8 +94,8 @@ advanced_options=false
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="*.json"
exclude_filter="tests/*,prototype/*,docs/*,addons/*,assets/models/*,assets/external/*"
include_filter="*.json,assets/external/characters/*.glb"
exclude_filter="tests/*,prototype/*,docs/*,addons/script-ide/*,addons/godot_ai_bridge/godot_ai_bridge.gd,addons/godot_ai_bridge/message_handler.gd,addons/godot_ai_bridge/ws_server.gd,assets/models/*,assets/external/characters/weights_rings*"
export_path="build/macos/rinkplanner.zip"
patches=PackedStringArray()
encryption_include_filters=""
@ -214,8 +214,8 @@ advanced_options=false
dedicated_server=false
custom_features=""
export_filter="all_resources"
include_filter="*.json"
exclude_filter="tests/*,prototype/*,docs/*,addons/*,assets/models/*,assets/external/*"
include_filter="*.json,assets/external/characters/*.glb"
exclude_filter="tests/*,prototype/*,docs/*,addons/script-ide/*,addons/godot_ai_bridge/godot_ai_bridge.gd,addons/godot_ai_bridge/message_handler.gd,addons/godot_ai_bridge/ws_server.gd,assets/models/*,assets/external/characters/weights_rings*"
export_path="build/android/rinkplanner.apk"
patches=PackedStringArray()
encryption_include_filters=""

View file

@ -0,0 +1,720 @@
class_name RoutineFile
extends RefCounted
## Reads and writes routine files.
##
## New routines are stored as JSON with a small, explicit schema. Legacy
## `.tres` resources are still readable for existing installations, but only
## after a strict whitelist check: the file may reference the four model
## scripts and nothing else. That check runs before `ResourceLoader.load`, so a
## synced file cannot smuggle an embedded GDScript (`script/source`) into the
## app. The JSON path has no such risk because it never instantiates a script.
const FORMAT_NAME := "rinkplanner.routine"
const FORMAT_VERSION := 1
const JSON_EXTENSION := ".json"
const LEGACY_EXTENSION := ".tres"
const AUTOSAVE_JSON := "user://autosave.json"
const AUTOSAVE_LEGACY := "user://autosave.tres"
## Hard limits keep a malformed or hostile file from exhausting memory.
const MAX_FILE_BYTES := 8 * 1024 * 1024
const MAX_SECTIONS := 500
const MAX_SEGMENTS_PER_SECTION := 5000
const MAX_TOTAL_SEGMENTS := 20000
const MAX_CURVE_POINTS := 10000
const MAX_TEXT_LENGTH := 256
const MAX_LABEL_LENGTH := 40
const MAX_ELEMENT_CODE_LENGTH := 24
const MAX_FEATURES := 16
const MAX_COMBINATION_JUMPS := 2
## Only the model resources may be referenced by a legacy `.tres`. The list is
## deliberately small; it contains no script with an `_init` side effect.
const ALLOWED_SCRIPTS := {
"res://src/core/model/routine.gd": true,
"res://src/core/model/routine_section.gd": true,
"res://src/core/model/path_segment.gd": true,
"res://src/core/model/rink_dimensions.gd": true,
}
## Turns any route path into its JSON form. `.tres` paths are migrated to the
## sibling `.json` path without touching the old file.
static func json_path(path: String) -> String:
var lower := path.to_lower()
if lower.ends_with(JSON_EXTENSION):
return path
if lower.ends_with(LEGACY_EXTENSION):
return (
path.substr(0, path.length() - LEGACY_EXTENSION.length())
+ JSON_EXTENSION
)
return path + JSON_EXTENSION
static func is_routine_path(path: String) -> bool:
var lower := path.to_lower()
return lower.ends_with(JSON_EXTENSION) or lower.ends_with(LEGACY_EXTENSION)
## Saves [param routine] atomically at [param path]. Returns an empty string on
## success, or a user-facing error message.
static func save(routine: Routine, path: String) -> String:
if routine == null:
return "Keine Kür zum Speichern."
if path.strip_edges().is_empty():
return "Der Zielpfad ist leer."
if routine.schema_version <= 0:
routine.schema_version = Routine.CURRENT_SCHEMA_VERSION
return _write_atomic(json_path(path), encode(routine))
## Loads a routine from a JSON file or a guarded legacy `.tres` file.
## Returns `{"routine": Routine, "error": String}`; exactly one of the two
## values is meaningful.
static func load_file(path: String) -> Dictionary:
var source := path
if not FileAccess.file_exists(source):
var backup := path + ".bak"
if FileAccess.file_exists(backup):
source = backup
else:
return _error("Datei nicht gefunden: %s" % path)
var file := FileAccess.open(source, FileAccess.READ)
if file == null:
return _error(
"Datei nicht lesbar: %s (Fehler %d)"
% [path, FileAccess.get_open_error()]
)
if file.get_length() > MAX_FILE_BYTES:
file.close()
return _error("Die Datei ist zu groß (max. 8 MB).")
var text := file.get_as_text()
file.close()
if source.to_lower().ends_with(LEGACY_EXTENSION):
return _load_legacy(source, text)
return decode_json(text)
static func decode_json(text: String) -> Dictionary:
if text.strip_edges().is_empty():
return _error("Die Datei ist leer.")
if text.length() > MAX_FILE_BYTES:
return _error("Die Datei ist zu groß (max. 8 MB).")
var json := JSON.new()
if json.parse(text) != OK:
return _error("Die Datei enthält kein gültiges JSON.")
var parsed: Variant = json.data
if not parsed is Dictionary:
return _error("Die Datei enthält kein gültiges JSON.")
var data: Dictionary = parsed
if str(data.get("format", "")) != FORMAT_NAME:
return _error("Die Datei ist keine Rinkplanner-Kür.")
var format_version := int(data.get("format_version", 0))
if format_version <= 0 or format_version > FORMAT_VERSION:
return _error(
"Das Dateiformat wird nicht unterstützt (Version %d)."
% format_version
)
var schema_version := int(
data.get("schema_version", Routine.CURRENT_SCHEMA_VERSION)
)
if schema_version > Routine.CURRENT_SCHEMA_VERSION:
return _error(
"Die Datei wurde mit einer neueren Version erstellt (Schema %d)."
% schema_version
)
var routine := Routine.new()
routine.schema_version = schema_version
routine.routine_id = _text(data, "routine_id", "routine").left(MAX_TEXT_LENGTH)
routine.title = _text(data, "title", "").left(MAX_TEXT_LENGTH)
routine.skater_name = _text(data, "skater_name", "").left(MAX_TEXT_LENGTH)
routine.adult_category = (
_text(data, "adult_category", "").left(MAX_TEXT_LENGTH)
)
routine.assumed_pcs_average = clampf(
_number(data, "assumed_pcs_average", 5.0),
0.0,
10.0
)
routine.assumed_falls = clampi(
int(_number(data, "assumed_falls", 0.0)),
0,
9999
)
var rink_data: Variant = data.get("rink", {})
if not rink_data is Dictionary:
return _error("Die Rink-Daten fehlen oder sind ungültig.")
var rink := RinkDimensions.new()
rink.length_m = clampf(_number(rink_data, "length_m", 60.0), 1.0, 200.0)
rink.width_m = clampf(_number(rink_data, "width_m", 30.0), 1.0, 100.0)
rink.corner_radius_m = clampf(
_number(rink_data, "corner_radius_m", 8.5),
0.0,
50.0
)
if not rink.is_valid():
return _error("Die Rink-Maße sind ungültig.")
routine.rink = rink
var sections_value: Variant = data.get("sections", [])
if not sections_value is Array:
return _error("Die Abschnitte fehlen oder sind ungültig.")
if sections_value.size() > MAX_SECTIONS:
return _error("Die Kür enthält zu viele Abschnitte.")
var sections: Array[RoutineSection] = []
var total_segments := 0
for section_entry: Variant in sections_value:
if not section_entry is Dictionary:
return _error("Ein Abschnitt ist ungültig.")
var section_result := _decode_section(section_entry)
if not str(section_result["error"]).is_empty():
return section_result
var section: RoutineSection = section_result["section"]
total_segments += section.segments.size()
if total_segments > MAX_TOTAL_SEGMENTS:
return _error("Die Kür enthält zu viele Segmente.")
sections.append(section)
routine.sections = sections
return {"routine": routine, "error": ""}
## Stores a routine as pretty-printed JSON. Exposed separately so tests can
## inspect the serialized form without touching the filesystem.
static func encode(routine: Routine) -> String:
var data := {
"format": FORMAT_NAME,
"format_version": FORMAT_VERSION,
"schema_version": routine.schema_version,
"routine_id": routine.routine_id,
"title": routine.title,
"skater_name": routine.skater_name,
"adult_category": routine.adult_category,
"assumed_pcs_average": routine.assumed_pcs_average,
"assumed_falls": routine.assumed_falls,
"rink": {
"length_m": routine.rink.length_m if routine.rink != null else 60.0,
"width_m": routine.rink.width_m if routine.rink != null else 30.0,
"corner_radius_m": (
routine.rink.corner_radius_m if routine.rink != null else 8.5
),
},
"sections": [],
}
var sections: Array = data["sections"]
for section: RoutineSection in routine.sections:
if section == null:
continue
sections.append(_encode_section(section))
return JSON.stringify(data, "\t", false, true)
static func _encode_section(section: RoutineSection) -> Dictionary:
var segments: Array = []
for segment: PathSegment in section.segments:
if segment != null:
segments.append(_encode_segment(segment))
return {
"section_id": section.section_id,
"title": section.title,
"sequence_order": section.sequence_order,
"segments": segments,
}
static func _encode_segment(segment: PathSegment) -> Dictionary:
var features: Array = []
for feature: String in segment.element_features:
features.append(feature)
var combination: Array = []
for jump: String in segment.combination_jumps:
combination.append(jump)
var points: Array = []
if segment.curve != null:
for index: int in range(segment.curve.point_count):
points.append(
{
"position": _vec2_json(
segment.curve.get_point_position(index)
),
"in": _vec2_json(segment.curve.get_point_in(index)),
"out": _vec2_json(segment.curve.get_point_out(index)),
}
)
return {
"segment_id": segment.segment_id,
"direction": _direction_name(segment.direction),
"edge": _edge_name(segment.edge),
"duration_seconds": segment.duration_seconds,
"speed_mps": segment.speed_mps,
"timing_mode": _timing_mode_name(segment.timing_mode),
"label": segment.label,
"template": _template_name(segment.template),
"arc_depth_ratio": segment.arc_depth_ratio,
"arc_bulge_left": segment.arc_bulge_left,
"element": {
"id": segment.element_id,
"type": _element_type_name(segment.element_type),
"code": segment.element_code,
"level": segment.element_level,
"features": features,
"jump_kind": _jump_kind_name(segment.jump_kind),
"combination_jumps": combination,
"duration_seconds": segment.element_duration_seconds,
},
"curve": {
"bake_interval": (
segment.curve.bake_interval if segment.curve != null else 5.0
),
"points": points,
},
}
static func _decode_section(data: Dictionary) -> Dictionary:
var section := RoutineSection.new()
section.section_id = _text(data, "section_id", "").left(MAX_TEXT_LENGTH)
if section.section_id.is_empty():
return _error("Ein Abschnitt hat keine ID.")
section.title = _text(data, "title", "Abschnitt").left(MAX_TEXT_LENGTH)
section.sequence_order = clampi(
int(_number(data, "sequence_order", 0.0)),
0,
MAX_SECTIONS * 10
)
var segments_value: Variant = data.get("segments", [])
if not segments_value is Array:
return _error("Die Segmente von „%s“ sind ungültig." % section.title)
if segments_value.size() > MAX_SEGMENTS_PER_SECTION:
return _error("Abschnitt „%s“ enthält zu viele Segmente." % section.title)
var segments: Array[PathSegment] = []
for segment_entry: Variant in segments_value:
if not segment_entry is Dictionary:
return _error("Ein Segment in „%s“ ist ungültig." % section.title)
var segment_result := _decode_segment(segment_entry)
if not str(segment_result["error"]).is_empty():
return segment_result
segments.append(segment_result["segment"])
section.segments = segments
return {"section": section, "error": ""}
static func _decode_segment(data: Dictionary) -> Dictionary:
var segment := PathSegment.new()
segment.segment_id = _text(data, "segment_id", "").left(MAX_TEXT_LENGTH)
if segment.segment_id.is_empty():
return _error("Ein Segment hat keine ID.")
var direction := _direction_from_name(_text(data, "direction", "forward"))
if direction < 0:
return _error("Segment „%s“ hat eine unbekannte Richtung." % segment.segment_id)
segment.direction = direction
var edge := _edge_from_name(_text(data, "edge", "outside"))
if edge < 0:
return _error("Segment „%s“ hat eine unbekannte Kante." % segment.segment_id)
segment.edge = edge
var timing_mode := _timing_mode_from_name(
_text(data, "timing_mode", "speed")
)
if timing_mode < 0:
return _error("Segment „%s“ hat einen unbekannten Zeitmodus." % segment.segment_id)
segment.timing_mode = timing_mode
segment.duration_seconds = clampf(
_number(data, "duration_seconds", 0.0),
0.0,
86400.0
)
var speed := clampf(_number(data, "speed_mps", 4.3), 0.0, 100.0)
segment.speed_mps = speed if speed > 0.0 else 4.3
segment.label = _text(data, "label", "").strip_edges().left(MAX_LABEL_LENGTH)
var template := _template_from_name(_text(data, "template", "line"))
if template < 0:
return _error("Segment „%s“ hat eine unbekannte Vorlage." % segment.segment_id)
segment.template = template
segment.arc_depth_ratio = clampf(
_number(data, "arc_depth_ratio", 0.4),
ArcGeometry.MIN_DEPTH_RATIO,
ArcGeometry.MAX_DEPTH_RATIO
)
var bulge_value: Variant = data.get("arc_bulge_left", true)
segment.arc_bulge_left = bulge_value if bulge_value is bool else true
var curve_result := _decode_curve(data.get("curve", {}))
if not str(curve_result["error"]).is_empty():
return curve_result
segment.curve = curve_result["curve"]
var element_value: Variant = data.get("element", {})
if not element_value is Dictionary:
return _error("Die Elementdaten von „%s“ sind ungültig." % segment.segment_id)
var element: Dictionary = element_value
var element_type := _element_type_from_name(
_text(element, "type", "none")
)
if element_type < 0:
return _error("Segment „%s“ hat einen unbekannten Elementtyp." % segment.segment_id)
var element_code := _text(element, "code", "").strip_edges().left(
MAX_ELEMENT_CODE_LENGTH
)
var element_level := clampi(
int(_number(element, "level", 0.0)),
0,
PathSegment.ELEMENT_MAX_LEVEL
)
segment.set_element(element_type, element_code, element_level)
segment.element_id = _text(element, "id", "").left(MAX_TEXT_LENGTH)
segment.element_duration_seconds = clampf(
_number(element, "duration_seconds", 0.0),
0.0,
PathSegment.ELEMENT_MAX_DURATION_SECONDS
)
var features_value: Variant = element.get("features", [])
if not features_value is Array:
return _error("Die Features von „%s“ sind ungültig." % segment.segment_id)
var features: PackedStringArray = PackedStringArray()
for feature_entry: Variant in features_value:
if not feature_entry is String:
return _error("Ein Feature von „%s“ ist ungültig." % segment.segment_id)
var feature := str(feature_entry).strip_edges().left(
MAX_ELEMENT_CODE_LENGTH
)
if not feature.is_empty():
features.append(feature)
if features.size() >= MAX_FEATURES:
break
segment.set_element_features(features)
var jump_kind := _jump_kind_from_name(
_text(element, "jump_kind", "solo")
)
if jump_kind < 0:
return _error("Segment „%s“ hat eine unbekannte Sprungart." % segment.segment_id)
var combination_value: Variant = element.get("combination_jumps", [])
if not combination_value is Array:
return _error("Die Sprungkombination von „%s“ ist ungültig." % segment.segment_id)
var combination: PackedStringArray = PackedStringArray()
for jump_entry: Variant in combination_value:
if not jump_entry is String:
return _error("Ein Kombinationssprung von „%s“ ist ungültig." % segment.segment_id)
var jump := str(jump_entry).strip_edges().left(
MAX_ELEMENT_CODE_LENGTH
)
if not jump.is_empty():
combination.append(jump)
if combination.size() >= MAX_COMBINATION_JUMPS:
break
segment.set_jump_combination(jump_kind, combination)
return {"segment": segment, "error": ""}
static func _decode_curve(value: Variant) -> Dictionary:
if not value is Dictionary:
return _error("Die Kurve eines Segments ist ungültig.")
var data: Dictionary = value
var points_value: Variant = data.get("points", [])
if not points_value is Array or points_value.is_empty():
return _error("Ein Segment hat keine Kurvenpunkte.")
if points_value.size() > MAX_CURVE_POINTS:
return _error("Eine Kurve enthält zu viele Punkte.")
var curve := Curve2D.new()
curve.bake_interval = clampf(
_number(data, "bake_interval", 5.0),
0.01,
100.0
)
for point_entry: Variant in points_value:
if not point_entry is Dictionary:
return _error("Ein Kurvenpunkt ist ungültig.")
var point: Dictionary = point_entry
if (
not _is_vec2(point.get("position", null))
or not _is_vec2(point.get("in", null))
or not _is_vec2(point.get("out", null))
):
return _error("Ein Kurvenpunkt hat ungültige Koordinaten.")
curve.add_point(
_vec2(point["position"]),
_vec2(point["in"]),
_vec2(point["out"])
)
return {"curve": curve, "error": ""}
static func _load_legacy(path: String, text: String) -> Dictionary:
var guard_error := legacy_guard_error(text)
if not guard_error.is_empty():
return _error(guard_error)
var resource := ResourceLoader.load(
path,
"",
ResourceLoader.CACHE_MODE_IGNORE
)
if not (resource is Routine):
return _error("Die Datei enthält keine gültige Rinkplanner-Kür.")
var routine := resource as Routine
if routine.schema_version > Routine.CURRENT_SCHEMA_VERSION:
return _error(
"Die Datei wurde mit einer neueren Version erstellt (Schema %d)."
% routine.schema_version
)
return {"routine": routine, "error": ""}
## Returns an error string when a legacy `.tres` is not a plain routine
## resource. The file is rejected before `ResourceLoader` sees it.
static func legacy_guard_error(text: String) -> String:
if text.length() > MAX_FILE_BYTES:
return "Die Datei ist zu groß (max. 8 MB)."
var stripped := text.strip_edges()
if not stripped.begins_with("[gd_resource type=\"Resource\""):
return "Die Datei ist keine Rinkplanner-Ressource."
if stripped.contains("[gd_scene") or stripped.contains("[node "):
return "Die Datei ist eine Szene, keine Kür."
if stripped.contains("script/source"):
return "Die Datei enthält eingebetteten Code und wird abgelehnt."
var sub_resource_re := RegEx.new()
sub_resource_re.compile("\\[sub_resource[^\\]]*type\\s*=\\s*\"([^\"]+)\"")
for match: RegExMatch in sub_resource_re.search_all(stripped):
if match.get_string(1) == "GDScript":
return "Die Datei enthält eingebetteten Code und wird abgelehnt."
var ext_resource_re := RegEx.new()
ext_resource_re.compile("\\[ext_resource[^\\]]*\\]")
var type_re := RegEx.new()
type_re.compile("type\\s*=\\s*\"([^\"]+)\"")
var path_re := RegEx.new()
path_re.compile("path\\s*=\\s*\"([^\"]+)\"")
for match: RegExMatch in ext_resource_re.search_all(stripped):
var line := match.get_string(0)
var type_match := type_re.search(line)
if type_match == null or type_match.get_string(1) != "Script":
return "Die Datei referenziert eine unerlaubte Ressource."
var path_match := path_re.search(line)
if (
path_match == null
or not ALLOWED_SCRIPTS.has(path_match.get_string(1))
):
return "Die Datei referenziert ein unerlaubtes Skript."
if (
not stripped.contains("script_class=\"Routine\"")
and not stripped.contains("path=\"res://src/core/model/routine.gd\"")
):
return "Die Datei enthält keine Rinkplanner-Kür."
return ""
static func _write_atomic(path: String, content: String) -> String:
var absolute := ProjectSettings.globalize_path(path)
var directory := absolute.get_base_dir()
if not DirAccess.dir_exists_absolute(directory):
if DirAccess.make_dir_recursive_absolute(directory) != OK:
return "Zielordner nicht anlegbar: %s" % directory
var temporary := absolute + ".tmp"
var backup := absolute + ".bak"
var file := FileAccess.open(temporary, FileAccess.WRITE)
if file == null:
return (
"Temporäre Datei nicht schreibbar: %s (Fehler %d)"
% [temporary, FileAccess.get_open_error()]
)
file.store_string(content)
file.flush()
file.close()
if FileAccess.file_exists(backup):
DirAccess.remove_absolute(backup)
var has_backup := false
if FileAccess.file_exists(absolute):
if DirAccess.rename_absolute(absolute, backup) != OK:
DirAccess.remove_absolute(temporary)
return "Vorhandene Datei nicht sicherbar: %s" % absolute
has_backup = true
if DirAccess.rename_absolute(temporary, absolute) != OK:
if has_backup:
DirAccess.rename_absolute(backup, absolute)
DirAccess.remove_absolute(temporary)
return "Datei nicht ersetzbar: %s" % absolute
if has_backup:
DirAccess.remove_absolute(backup)
return ""
static func _error(message: String) -> Dictionary:
return {"routine": null, "error": message}
static func _text(
data: Dictionary,
key: String,
fallback: String = ""
) -> String:
var value: Variant = data.get(key, fallback)
if value is String:
return value
return fallback
static func _number(
data: Dictionary,
key: String,
fallback: float
) -> float:
var value: Variant = data.get(key, fallback)
if value is int or value is float:
var number := float(value)
if is_finite(number):
return number
return fallback
static func _is_vec2(value: Variant) -> bool:
if not value is Array or value.size() != 2:
return false
return (
(value[0] is int or value[0] is float)
and (value[1] is int or value[1] is float)
and is_finite(float(value[0]))
and is_finite(float(value[1]))
)
static func _vec2(value: Array) -> Vector2:
return Vector2(float(value[0]), float(value[1]))
static func _vec2_json(value: Vector2) -> Array:
return [value.x, value.y]
static func _direction_name(value: PathSegment.Direction) -> String:
match value:
PathSegment.Direction.BACKWARD:
return "backward"
return "forward"
static func _direction_from_name(value: String) -> int:
match value:
"forward":
return PathSegment.Direction.FORWARD
"backward":
return PathSegment.Direction.BACKWARD
return -1
static func _edge_name(value: PathSegment.Edge) -> String:
match value:
PathSegment.Edge.INSIDE:
return "inside"
return "outside"
static func _edge_from_name(value: String) -> int:
match value:
"outside":
return PathSegment.Edge.OUTSIDE
"inside":
return PathSegment.Edge.INSIDE
return -1
static func _timing_mode_name(value: PathSegment.TimingMode) -> String:
match value:
PathSegment.TimingMode.DURATION:
return "duration"
return "speed"
static func _timing_mode_from_name(value: String) -> int:
match value:
"speed":
return PathSegment.TimingMode.SPEED
"duration":
return PathSegment.TimingMode.DURATION
return -1
static func _template_name(value: PathSegment.Template) -> String:
match value:
PathSegment.Template.ARC:
return "arc"
return "line"
static func _template_from_name(value: String) -> int:
match value:
"line":
return PathSegment.Template.LINE
"arc":
return PathSegment.Template.ARC
return -1
static func _element_type_name(value: PathSegment.ElementType) -> String:
match value:
PathSegment.ElementType.JUMP:
return "jump"
PathSegment.ElementType.SPIN:
return "spin"
PathSegment.ElementType.SEQUENCE:
return "sequence"
return "none"
static func _element_type_from_name(value: String) -> int:
match value:
"none":
return PathSegment.ElementType.NONE
"jump":
return PathSegment.ElementType.JUMP
"spin":
return PathSegment.ElementType.SPIN
"sequence":
return PathSegment.ElementType.SEQUENCE
return -1
static func _jump_kind_name(value: PathSegment.JumpKind) -> String:
match value:
PathSegment.JumpKind.COMBINATION:
return "combination"
PathSegment.JumpKind.SEQUENCE:
return "sequence"
return "solo"
static func _jump_kind_from_name(value: String) -> int:
match value:
"solo":
return PathSegment.JumpKind.SOLO
"combination":
return PathSegment.JumpKind.COMBINATION
"sequence":
return PathSegment.JumpKind.SEQUENCE
return -1

View file

@ -0,0 +1 @@
uid://bnpn0uoydk6o8

View file

@ -9,7 +9,9 @@ const LOCAL_DIR := "user://routines"
const STATE_PATH := "user://sync_state.cfg"
const TEMP_SUFFIX := ".part"
const UPLOAD_SUFFIX := ".uploading"
const ROUTINE_EXTENSION := ".tres"
## New routines are JSON; legacy `.tres` files stay in the sync so existing
## installations do not lose their server copies.
const ROUTINE_EXTENSIONS := [".json", ".tres"]
var progress: String = ""
var error: String = ""
@ -271,11 +273,19 @@ func _save_state(client: FtpClient, state: Dictionary) -> void:
save_state(STATE_PATH, state)
static func is_routine_file(name: String) -> bool:
var lower := name.to_lower()
for extension: String in ROUTINE_EXTENSIONS:
if lower.ends_with(extension):
return true
return false
func _remote_files(client: FtpClient) -> Dictionary:
var files: Dictionary = {}
for entry: Dictionary in client.list_files():
var name := str(entry.get("name", ""))
if not name.ends_with(ROUTINE_EXTENSION):
if not is_routine_file(name):
continue
files[name] = {
"modify": int(entry.get("modify", 0)),
@ -292,7 +302,7 @@ static func local_files(directory: String = LOCAL_DIR) -> Dictionary:
dir.list_dir_begin()
var name := dir.get_next()
while not name.is_empty():
if not dir.current_is_dir() and name.ends_with(ROUTINE_EXTENSION):
if not dir.current_is_dir() and is_routine_file(name):
var path := directory.path_join(name)
files[name] = {
"mtime": FileAccess.get_modified_time(path),

View file

@ -91,16 +91,29 @@ static func action_name(action: Action) -> String:
return ACTION_NAMES.get(action, "unknown")
## "kuer.tres" -> "kuer (Server 2026-10-30 1050).tres"
## "kuer.json" -> "kuer (Server 2026-10-30 1050).json"
static func conflict_file_name(file_name: String, stamp: String) -> String:
var base := file_name.get_basename()
return "%s (Server %s).tres" % [base, stamp]
return "%s (Server %s)%s" % [
file_name.get_basename(),
stamp,
_extension_suffix(file_name),
]
## "kuer.tres" -> "kuer (Lokal 2026-10-30 1050).tres"
## "kuer.json" -> "kuer (Lokal 2026-10-30 1050).json"
static func local_backup_file_name(file_name: String, stamp: String) -> String:
var base := file_name.get_basename()
return "%s (Lokal %s).tres" % [base, stamp]
return "%s (Lokal %s)%s" % [
file_name.get_basename(),
stamp,
_extension_suffix(file_name),
]
static func _extension_suffix(file_name: String) -> String:
var extension := file_name.get_extension()
if extension.is_empty():
return ""
return "." + extension
static func timestamp_label(unix_time: int = -1) -> String:
@ -125,9 +138,10 @@ static func unique_name(file_name: String, used: Dictionary) -> String:
if not used.has(file_name):
return file_name
var base := file_name.get_basename()
var extension := _extension_suffix(file_name)
var index := 2
while true:
var candidate := "%s %d.tres" % [base, index]
var candidate := "%s %d%s" % [base, index, extension]
if not used.has(candidate):
return candidate
index += 1

View file

@ -58,7 +58,10 @@ const FEATURE_MENU_RESET_ID := 1000000
const CODE_OPTION_PLACEHOLDER_ID := 0
const CODE_OPTION_FREE_ID := 1000000
const EXPORT_IMAGE_SIZE := Vector2i(2560, 1600)
const AUTOSAVE_PATH := "user://autosave.tres"
const ROUTINE_EXTENSION := RoutineFile.JSON_EXTENSION
const AUTOSAVE_PATH := RoutineFile.AUTOSAVE_JSON
const LEGACY_AUTOSAVE_PATH := RoutineFile.AUTOSAVE_LEGACY
const SESSION_PATH := "user://session.cfg"
const SYNC_SETTINGS_PATH := "user://sync.cfg"
const AUTOSAVE_DELAY_SECONDS := 1.5
const MAX_HISTORY := 50
@ -317,7 +320,7 @@ func _ready() -> void:
_apply_responsive_layout.call_deferred()
_ensure_routines_dir()
if not (restore_autosave and _try_load_autosave()):
if not (restore_autosave and _restore_session()):
new_routine()
@ -353,23 +356,26 @@ func new_routine() -> void:
routine.sections = sections
_set_routine(routine, "")
_clear_session_path()
_delete_autosave()
func save_to_path(path: String) -> bool:
if _routine == null or path.is_empty():
return false
_ensure_routines_dir()
var error := ResourceSaver.save(_routine, path)
if error != OK:
_show_message("Speichern fehlgeschlagen: %s" % error_string(error))
var target := RoutineFile.json_path(path)
var error := RoutineFile.save(_routine, target)
if not error.is_empty():
_show_message("Speichern fehlgeschlagen: %s" % error)
return false
_current_path = path
_current_path = target
_dirty = false
autosave_timer.stop()
_update_window_title()
_save_autosave()
_delete_autosave()
_save_session_path(target)
return true
@ -2301,17 +2307,9 @@ func _unhandled_key_input(event: InputEvent) -> void:
return
var focused := get_viewport().gui_get_focus_owner()
if focused is LineEdit:
if focused is LineEdit or focused is TextEdit:
return
if (
rename_dialog.visible
or delete_dialog.visible
or save_as_dialog.visible
or open_dialog.visible
or confirm_dialog.visible
or message_dialog.visible
or segment_label_dialog.visible
):
if _any_modal_open():
return
var modifier := key.ctrl_pressed or key.meta_pressed
@ -2337,6 +2335,15 @@ func _unhandled_key_input(event: InputEvent) -> void:
get_viewport().set_input_as_handled()
## Any visible dialog or popup blocks the global canvas shortcuts. This covers
## all current and future dialogs instead of maintaining a manual list.
func _any_modal_open() -> bool:
for node: Node in find_children("*", "Window", true, false):
if node is Window and node.visible:
return true
return false
func _setup_tool_options() -> void:
tool_option.clear()
tool_option.add_item("Auswählen", Tool.SELECT)
@ -3411,6 +3418,9 @@ func _set_routine(routine: Routine, path: String) -> void:
_current_path = path
_dirty = false
autosave_timer.stop()
if not path.is_empty():
_save_session_path(path)
_delete_autosave()
_undo_stack.clear()
_redo_stack.clear()
@ -3418,7 +3428,6 @@ func _set_routine(routine: Routine, path: String) -> void:
_update_history_buttons()
_update_window_title()
_save_autosave()
func _install_routine(
@ -3525,41 +3534,71 @@ func _max_numeric_suffix(prefix: String, ids: Array[String]) -> int:
func _read_routine(path: String, show_error: bool = true) -> Routine:
if not FileAccess.file_exists(path):
var result := RoutineFile.load_file(path)
var error := str(result.get("error", ""))
if not error.is_empty():
if show_error:
_show_message("Datei nicht gefunden:\n%s" % path)
_show_message(error)
return null
var resource := ResourceLoader.load(path, "", ResourceLoader.CACHE_MODE_IGNORE)
if not (resource is Routine):
if show_error:
_show_message("Die Datei enthält keine gültige Rinkplanner-Kür.")
return null
var routine := resource as Routine
if routine.schema_version > Routine.CURRENT_SCHEMA_VERSION:
if show_error:
_show_message(
"Die Datei wurde mit einer neueren Version erstellt (Schema %d)."
% routine.schema_version
)
return null
var routine: Routine = result.get("routine", null)
if routine == null and show_error:
_show_message("Die Datei enthält keine gültige Rinkplanner-Kür.")
return routine
## Loads the last opened routine, or the autosave when it is newer than the
## file it belongs to. This keeps the file path after a restart, so Ctrl+S
## does not silently become "Save As".
func _restore_session() -> bool:
var last_path := _load_session_path()
if last_path.is_empty() or not FileAccess.file_exists(last_path):
return _try_load_autosave()
var autosave_path := _newest_autosave_path()
if (
not autosave_path.is_empty()
and FileAccess.get_modified_time(autosave_path)
> FileAccess.get_modified_time(last_path)
):
var autosave := _read_routine(autosave_path, false)
if autosave != null:
_set_routine(autosave, last_path)
_dirty = true
_update_window_title()
_save_autosave()
return true
var last_routine := _read_routine(last_path, false)
if last_routine != null:
_set_routine(last_routine, last_path)
return true
return _try_load_autosave()
func _try_load_autosave() -> bool:
if not FileAccess.file_exists(AUTOSAVE_PATH):
var path := _newest_autosave_path()
if path.is_empty():
return false
var loaded := _read_routine(AUTOSAVE_PATH, false)
var loaded := _read_routine(path, false)
if loaded == null:
return false
_set_routine(loaded, "")
# The draft is not backed by a saved file yet; keep it dirty so Ctrl+S
# opens "Save As" and closing does not discard the recovered autosave.
_dirty = true
_update_window_title()
return true
func _newest_autosave_path() -> String:
if FileAccess.file_exists(AUTOSAVE_PATH):
return AUTOSAVE_PATH
if FileAccess.file_exists(LEGACY_AUTOSAVE_PATH):
return LEGACY_AUTOSAVE_PATH
return ""
func _ensure_routines_dir() -> void:
if not DirAccess.dir_exists_absolute(ROUTINES_DIR):
DirAccess.make_dir_recursive_absolute(ROUTINES_DIR)
@ -3568,9 +3607,49 @@ func _ensure_routines_dir() -> void:
func _save_autosave() -> void:
if not autosave_enabled or _routine == null:
return
if not _dirty:
_delete_autosave()
return
_ensure_routines_dir()
ResourceSaver.save(_routine, AUTOSAVE_PATH)
var error := RoutineFile.save(_routine, AUTOSAVE_PATH)
if not error.is_empty():
push_warning("Autosave fehlgeschlagen: %s" % error)
func _delete_autosave() -> void:
for path: String in [
AUTOSAVE_PATH,
LEGACY_AUTOSAVE_PATH,
AUTOSAVE_PATH + ".tmp",
AUTOSAVE_PATH + ".bak",
]:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
func _save_session_path(path: String) -> void:
if path.is_empty():
return
var config := ConfigFile.new()
config.set_value("session", "last_path", path)
config.save(SESSION_PATH)
func _clear_session_path() -> void:
var config := ConfigFile.new()
if config.load(SESSION_PATH) != OK:
return
if config.has_section_key("session", "last_path"):
config.erase_section_key("session", "last_path")
config.save(SESSION_PATH)
func _load_session_path() -> String:
var config := ConfigFile.new()
if config.load(SESSION_PATH) != OK:
return ""
return str(config.get_value("session", "last_path", "")).strip_edges()
func _mark_dirty() -> void:
@ -3628,11 +3707,27 @@ func _on_save_as_confirmed() -> void:
return
var stem := _normalize_file_stem(name)
_routine.title = name
if _routine.routine_id.is_empty() or _routine.routine_id == "draft-routine":
_routine.routine_id = stem
var path := ROUTINES_DIR.path_join(stem + ROUTINE_EXTENSION)
var apply := func() -> void:
_routine.title = name
if _routine.routine_id.is_empty() or _routine.routine_id == "draft-routine":
_routine.routine_id = stem
save_to_path(path)
if FileAccess.file_exists(path) and path != _current_path:
_confirm_overwrite(path, apply)
return
apply.call()
save_to_path(ROUTINES_DIR.path_join(stem + ".tres"))
## Asks before an existing file is replaced. The action is invoked by the
## shared confirmation dialog.
func _confirm_overwrite(path: String, action: Callable) -> void:
_pending_action = action
confirm_dialog.title = "Datei überschreiben"
confirm_dialog.dialog_text = (
"Die Datei „%s“ existiert bereits. Überschreiben?" % path.get_file()
)
confirm_dialog.popup_centered(Vector2i(480, 180))
func _setup_export_controls() -> void:
@ -3887,6 +3982,20 @@ func _on_export_confirmed() -> void:
var is_svg := export_format_option.selected == 0
var extension := "svg" if is_svg else "png"
var path := EXPORTS_DIR.path_join(stem + scope_suffix + "." + extension)
if FileAccess.file_exists(path):
_confirm_overwrite(
path,
_perform_export.bind(path, is_svg, scope_section_id)
)
return
await _perform_export(path, is_svg, scope_section_id)
func _perform_export(
path: String,
is_svg: bool,
scope_section_id: String
) -> void:
_ensure_exports_dir()
var success := false
@ -3958,11 +4067,21 @@ func _refresh_open_list() -> void:
child.free()
_ensure_routines_dir()
var entries: Array[String] = []
var by_stem: Dictionary[String, String] = {}
for file: String in DirAccess.get_files_at(ROUTINES_DIR):
if file.ends_with(".tres"):
entries.append(file)
entries.sort()
if not RoutineFile.is_routine_path(file):
continue
var stem := file.get_basename()
var is_json := file.to_lower().ends_with(RoutineFile.JSON_EXTENSION)
if not by_stem.has(stem) or is_json:
by_stem[stem] = file
var entries: Array[String] = []
for file: String in by_stem.values():
entries.append(file)
entries.sort_custom(
func(a: String, b: String) -> bool:
return a.get_basename().naturalnocasecmp_to(b.get_basename()) < 0
)
for file: String in entries:
var button := Button.new()
@ -3994,6 +4113,7 @@ func _request_document_change(action: Callable) -> void:
return
_pending_action = action
confirm_dialog.title = "Ungespeicherte Änderungen"
confirm_dialog.dialog_text = "Ungespeicherte Änderungen verwerfen?"
confirm_dialog.popup_centered(Vector2i(460, 170))

View file

@ -8,6 +8,8 @@ From the repository root:
```bash
./tools/test.sh
# inklusive Export-Smoke-Test:
./tools/test.sh --export
```
Or manually:
@ -23,6 +25,9 @@ $GODOT --headless --path rinkplanner --import
# Run model tests
$GODOT --headless --path rinkplanner --script res://tests/run_model_tests.gd
# Run JSON/legacy file-format tests
$GODOT --headless --path rinkplanner --script res://tests/run_file_format_tests.gd
# Run ISU element catalog tests
$GODOT --headless --path rinkplanner --script res://tests/run_rules_tests.gd

View file

@ -0,0 +1,332 @@
extends SceneTree
## Headless tests for the routine file format: JSON round-trip, schema checks,
## atomic writes and the legacy `.tres` whitelist.
##
## Run with:
## godot --headless --path rinkplanner --script res://tests/run_file_format_tests.gd
const JSON_PATH := "user://test_format.json"
const LEGACY_PATH := "user://test_format_legacy.tres"
const EVIL_PATH := "user://test_format_evil.tres"
const EVIL_SCRIPT_PATH := "user://test_format_evil_script.tres"
var _assertions: int = 0
var _failures: PackedStringArray = PackedStringArray()
func _init() -> void:
_run.call_deferred()
func _run() -> void:
_test_json_roundtrip()
_test_json_rejects()
_test_atomic_write()
_test_legacy_roundtrip()
_test_legacy_guard()
_cleanup()
_finish()
func _test_json_roundtrip() -> void:
var routine := _make_routine()
var encoded := RoutineFile.encode(routine)
_check(
encoded.contains("\"format\": \"rinkplanner.routine\""),
"JSON contains the format marker"
)
_check(
encoded.contains("\"direction\": \"backward\""),
"enums are stored as readable names"
)
var result := RoutineFile.decode_json(encoded)
_check(str(result["error"]).is_empty(), "encoded JSON decodes without error")
var loaded: Routine = result["routine"]
_check(loaded != null, "decoded JSON yields a routine")
if loaded == null:
return
_check(loaded.routine_id == routine.routine_id, "routine id survives")
_check(loaded.title == routine.title, "title survives")
_check(loaded.skater_name == routine.skater_name, "skater name survives")
_check(loaded.adult_category == routine.adult_category, "category survives")
_check_approx(
loaded.assumed_pcs_average,
routine.assumed_pcs_average,
"PCS assumption survives"
)
_check(loaded.assumed_falls == routine.assumed_falls, "fall count survives")
_check_approx(loaded.rink.length_m, 40.0, "rink length survives")
_check(loaded.sections.size() == 1, "section survives")
var section := loaded.get_section_by_id("section-001")
_check(section != null, "section id survives")
if section == null:
return
_check(section.title == "Abschnitt 1", "section title survives")
_check(section.segments.size() == 3, "all segments survive")
var arc := section.get_segment_by_id("seg-arc")
_check(arc != null, "arc segment survives")
if arc != null:
_check(arc.direction == PathSegment.Direction.BACKWARD, "direction survives")
_check(arc.edge == PathSegment.Edge.INSIDE, "edge survives")
_check(arc.timing_mode == PathSegment.TimingMode.DURATION, "timing mode survives")
_check(arc.template == PathSegment.Template.ARC, "arc template survives")
_check(arc.label == "Kür & Test", "label survives")
_check(arc.element_type == PathSegment.ElementType.JUMP, "element type survives")
_check(arc.element_code == "3Lz", "element code survives")
_check(
arc.combination_jumps == PackedStringArray(["2T", "2S"]),
"jump combination survives"
)
_check(
arc.element_features == PackedStringArray(["difficult_exit"]),
"features survive"
)
_check(arc.curve.point_count == 2, "curve points survive")
_check_vec(
arc.curve.get_point_position(0),
Vector2(-10.0, -5.0),
"first curve point survives"
)
_check_vec(
arc.curve.get_point_in(0),
Vector2(-1.0, 0.5),
"curve in-handle survives"
)
_check_vec(
arc.curve.get_point_out(1),
Vector2(2.0, -0.5),
"curve out-handle survives"
)
var marker := section.get_segment_by_id("seg-marker")
_check(marker != null, "marker survives")
if marker != null:
_check(marker.is_element_marker(), "marker stays a point marker")
_check(marker.curve.point_count == 1, "marker keeps one point")
_check_approx(
marker.element_duration_seconds,
0.7,
"marker stand time survives"
)
func _test_json_rejects() -> void:
_check(
not str(RoutineFile.decode_json("{}")["error"]).is_empty(),
"empty JSON object is rejected"
)
_check(
not str(RoutineFile.decode_json("{")["error"]).is_empty(),
"broken JSON is rejected"
)
var too_new := RoutineFile.decode_json(
'{"format":"rinkplanner.routine","format_version":1,'
+ '"schema_version":99,"rink":{},"sections":[]}'
)
_check(not str(too_new["error"]).is_empty(), "newer schema is rejected")
var routine := _make_routine()
var encoded := RoutineFile.encode(routine)
var bad_direction := encoded.replace(
"\"direction\": \"backward\"",
"\"direction\": \"sideways\""
)
_check(
not str(RoutineFile.decode_json(bad_direction)["error"]).is_empty(),
"unknown enum value is rejected"
)
_check(
RoutineFile.json_path("user://kuer.tres") == "user://kuer.json",
"legacy paths migrate to the JSON extension"
)
_check(
RoutineFile.json_path("user://kuer") == "user://kuer.json",
"paths without extension get .json"
)
func _test_atomic_write() -> void:
var routine := _make_routine()
_check(
RoutineFile.save(routine, JSON_PATH).is_empty(),
"routine saves without error"
)
_check(FileAccess.file_exists(JSON_PATH), "JSON file exists")
_check(not FileAccess.file_exists(JSON_PATH + ".tmp"), "no temp file remains")
_check(not FileAccess.file_exists(JSON_PATH + ".bak"), "no backup remains")
routine.title = "Zweite Fassung"
_check(
RoutineFile.save(routine, JSON_PATH).is_empty(),
"routine can be replaced atomically"
)
var result := RoutineFile.load_file(JSON_PATH)
var loaded: Routine = result["routine"]
_check(
loaded != null and loaded.title == "Zweite Fassung",
"atomic replacement writes the new content"
)
func _test_legacy_roundtrip() -> void:
var routine := _make_routine()
_check(
ResourceSaver.save(routine, LEGACY_PATH) == OK,
"legacy resource can be written"
)
var result := RoutineFile.load_file(LEGACY_PATH)
_check(str(result["error"]).is_empty(), "benign legacy file passes the guard")
var loaded: Routine = result["routine"]
_check(loaded != null, "benign legacy file loads")
if loaded != null:
_check(loaded.title == routine.title, "legacy fields survive")
_check(loaded.sections.size() == 1, "legacy sections survive")
func _test_legacy_guard() -> void:
var embedded := (
"[gd_resource type=\"Resource\" format=3]\n\n"
+ "[sub_resource type=\"GDScript\" id=\"1_script\"]\n"
+ "script/source = \"extends Resource\\n\\nfunc _init():\\n"
+ "\\tprint(\\\"PWNED\\\")\\n\"\n\n"
+ "[resource]\nscript = SubResource(\"1_script\")\n"
)
_write(EVIL_PATH, embedded)
var evil_result := RoutineFile.load_file(EVIL_PATH)
_check(evil_result["routine"] == null, "embedded GDScript is rejected")
_check(
str(evil_result["error"]).contains("eingebetteten Code"),
"embedded code error is explicit"
)
var foreign_script := (
"[gd_resource type=\"Resource\" script_class=\"Routine\" format=3]\n\n"
+ "[ext_resource type=\"Script\" "
+ "path=\"res://src/whiteboard/ctrl/whiteboard_controller.gd\" id=\"1\"]\n\n"
+ "[resource]\nscript = ExtResource(\"1\")\n"
)
_write(EVIL_SCRIPT_PATH, foreign_script)
var script_result := RoutineFile.load_file(EVIL_SCRIPT_PATH)
_check(script_result["routine"] == null, "foreign script reference is rejected")
_check(
str(script_result["error"]).contains("unerlaubtes Skript"),
"foreign script error is explicit"
)
func _make_routine() -> Routine:
var routine := Routine.new()
routine.routine_id = "format-test"
routine.title = "Format Test"
routine.skater_name = "Erika"
routine.adult_category = "gold"
routine.assumed_pcs_average = 4.75
routine.assumed_falls = 1
routine.rink = RinkDimensions.new()
routine.rink.length_m = 40.0
routine.rink.width_m = 20.0
routine.rink.corner_radius_m = 6.0
var section := RoutineSection.new()
section.section_id = "section-001"
section.title = "Abschnitt 1"
section.sequence_order = 0
var line := PathSegment.new()
line.segment_id = "seg-line"
line.curve = Curve2D.new()
line.curve.add_point(Vector2(-15.0, 0.0))
line.curve.add_point(Vector2(-5.0, 0.0))
line.set_speed_mps(4.0)
var arc := PathSegment.new()
arc.segment_id = "seg-arc"
arc.direction = PathSegment.Direction.BACKWARD
arc.edge = PathSegment.Edge.INSIDE
arc.timing_mode = PathSegment.TimingMode.DURATION
arc.duration_seconds = 2.5
arc.speed_mps = 4.0
arc.template = PathSegment.Template.ARC
arc.arc_depth_ratio = 0.35
arc.arc_bulge_left = false
arc.label = "Kür & Test"
arc.curve = Curve2D.new()
arc.curve.add_point(
Vector2(-10.0, -5.0),
Vector2(-1.0, 0.5),
Vector2(1.0, -0.5)
)
arc.curve.add_point(
Vector2(0.0, -5.0),
Vector2(-2.0, 0.5),
Vector2(2.0, -0.5)
)
arc.set_element(PathSegment.ElementType.JUMP, "3Lz", 0)
arc.set_element_features(PackedStringArray(["difficult_exit"]))
arc.set_jump_combination(
PathSegment.JumpKind.COMBINATION,
PackedStringArray(["2T", "2S"])
)
var marker := PathSegment.new()
marker.segment_id = "seg-marker"
marker.curve = Curve2D.new()
marker.curve.add_point(Vector2(5.0, 5.0))
marker.speed_mps = 4.0
marker.set_element(PathSegment.ElementType.SPIN, "CCoSp4", 4)
marker.set_element_duration(0.7)
section.segments = [line, arc, marker]
routine.sections = [section]
return routine
func _write(path: String, text: String) -> void:
var file := FileAccess.open(path, FileAccess.WRITE)
file.store_string(text)
file.close()
func _cleanup() -> void:
for path: String in [JSON_PATH, LEGACY_PATH, EVIL_PATH, EVIL_SCRIPT_PATH]:
for suffix: String in ["", ".tmp", ".bak"]:
if FileAccess.file_exists(path + suffix):
DirAccess.remove_absolute(
ProjectSettings.globalize_path(path + suffix)
)
func _check(condition: bool, message: String) -> void:
_assertions += 1
if not condition:
_failures.append(message)
func _check_approx(actual: float, expected: float, message: String) -> void:
_check(
absf(actual - expected) <= 0.001,
"%s (expected %.3f, got %.3f)" % [message, expected, actual]
)
func _check_vec(actual: Vector2, expected: Vector2, message: String) -> void:
_check(
actual.distance_to(expected) <= 0.001,
"%s (expected %s, got %s)" % [message, expected, actual]
)
func _finish() -> void:
if _failures.is_empty():
print("PASS: %d assertions" % _assertions)
quit(0)
return
for failure: String in _failures:
printerr("FAIL: %s" % failure)
printerr("%d of %d assertions failed" % [_failures.size(), _assertions])
quit(1)

View file

@ -0,0 +1 @@
uid://bchm7iw3mfvw7

View file

@ -27,50 +27,50 @@ func _run() -> void:
func _test_plan() -> void:
var local := {
"neu.tres": {"mtime": 100, "size": 10},
"lokal.tres": {"mtime": 200, "size": 10},
"server.tres": {"mtime": 300, "size": 10},
"beide.tres": {"mtime": 400, "size": 10},
"gleich.tres": {"mtime": 500, "size": 10},
"entfernt.tres": {"mtime": 600, "size": 10},
"neu.json": {"mtime": 100, "size": 10},
"lokal.json": {"mtime": 200, "size": 10},
"server.json": {"mtime": 300, "size": 10},
"beide.json": {"mtime": 400, "size": 10},
"gleich.json": {"mtime": 500, "size": 10},
"entfernt.json": {"mtime": 600, "size": 10},
}
var remote := {
"server-neu.tres": {"modify": 700, "size": 10},
"lokal.tres": {"modify": 200, "size": 10},
"server.tres": {"modify": 900, "size": 10},
"beide.tres": {"modify": 900, "size": 10},
"gleich.tres": {"modify": 500, "size": 10},
"entfernt.tres": {"modify": 600, "size": 10},
"server-neu.json": {"modify": 700, "size": 10},
"lokal.json": {"modify": 200, "size": 10},
"server.json": {"modify": 900, "size": 10},
"beide.json": {"modify": 900, "size": 10},
"gleich.json": {"modify": 500, "size": 10},
"entfernt.json": {"modify": 600, "size": 10},
}
var state := {
"lokal.tres": {"local_mtime": 100, "remote_modify": 200},
"server.tres": {"local_mtime": 300, "remote_modify": 300},
"beide.tres": {"local_mtime": 401, "remote_modify": 400},
"gleich.tres": {"local_mtime": 500, "remote_modify": 500},
"entfernt.tres": {"local_mtime": 600, "remote_modify": 600},
"lokal.json": {"local_mtime": 100, "remote_modify": 200},
"server.json": {"local_mtime": 300, "remote_modify": 300},
"beide.json": {"local_mtime": 401, "remote_modify": 400},
"gleich.json": {"local_mtime": 500, "remote_modify": 500},
"entfernt.json": {"local_mtime": 600, "remote_modify": 600},
}
var plan := SyncPlan.build(local, remote, state)
var actions := {}
for entry: Dictionary in plan:
actions[entry["name"]] = entry["action"]
_check(actions.get("neu.tres") == SyncPlan.Action.UPLOAD, "nur lokal wird hochgeladen")
_check(actions.get("server-neu.tres") == SyncPlan.Action.DOWNLOAD, "nur Server wird geladen")
_check(actions.get("neu.json") == SyncPlan.Action.UPLOAD, "nur lokal wird hochgeladen")
_check(actions.get("server-neu.json") == SyncPlan.Action.DOWNLOAD, "nur Server wird geladen")
_check(
actions.get("beide.tres") == SyncPlan.Action.CONFLICT,
actions.get("beide.json") == SyncPlan.Action.CONFLICT,
"beidseitige Änderung ist ein Konflikt"
)
_check(actions.get("lokal.tres") == SyncPlan.Action.UPLOAD, "lokale Änderung wird hochgeladen")
_check(actions.get("server.tres") == SyncPlan.Action.DOWNLOAD, "Server-Änderung wird geladen")
_check(actions.get("gleich.tres") == SyncPlan.Action.SKIP, "unverändert wird übersprungen")
_check(actions.get("lokal.json") == SyncPlan.Action.UPLOAD, "lokale Änderung wird hochgeladen")
_check(actions.get("server.json") == SyncPlan.Action.DOWNLOAD, "Server-Änderung wird geladen")
_check(actions.get("gleich.json") == SyncPlan.Action.SKIP, "unverändert wird übersprungen")
_check(
actions.get("entfernt.tres") == SyncPlan.Action.SKIP,
actions.get("entfernt.json") == SyncPlan.Action.SKIP,
"Server-Datei verschwunden: nicht wiederherstellen"
)
var first_sync := SyncPlan.build(
{"a.tres": {"mtime": 1, "size": 1}},
{"a.tres": {"modify": 2, "size": 1}},
{"a.json": {"mtime": 1, "size": 1}},
{"a.json": {"modify": 2, "size": 1}},
{}
)
_check(
@ -80,8 +80,8 @@ func _test_plan() -> void:
var local_deleted := SyncPlan.build(
{},
{"weg.tres": {"modify": 2, "size": 1}},
{"weg.tres": {"local_mtime": 1, "remote_modify": 2}}
{"weg.json": {"modify": 2, "size": 1}},
{"weg.json": {"local_mtime": 1, "remote_modify": 2}}
)
_check(
local_deleted.size() == 1 and local_deleted[0]["action"] == SyncPlan.Action.SKIP,
@ -91,25 +91,36 @@ func _test_plan() -> void:
func _test_naming() -> void:
_check(
SyncPlan.conflict_file_name("kuer.tres", "2026-10-30 1050")
== "kuer (Server 2026-10-30 1050).tres",
SyncPlan.conflict_file_name("kuer.json", "2026-10-30 1050")
== "kuer (Server 2026-10-30 1050).json",
"Konfliktname enthält Zeitstempel"
)
var used := {"kuer (Server 2026-10-30 1050).tres": true}
var used := {"kuer (Server 2026-10-30 1050).json": true}
_check(
SyncPlan.unique_name("kuer (Server 2026-10-30 1050).tres", used)
== "kuer (Server 2026-10-30 1050) 2.tres",
SyncPlan.unique_name("kuer (Server 2026-10-30 1050).json", used)
== "kuer (Server 2026-10-30 1050) 2.json",
"Konfliktname wird bei Bedarf durchnummeriert"
)
_check(
SyncPlan.unique_name("frei.tres", used) == "frei.tres",
SyncPlan.unique_name("frei.json", used) == "frei.json",
"freier Name bleibt unverändert"
)
_check(
SyncPlan.local_backup_file_name("kuer.tres", "2026-10-30 1050")
== "kuer (Lokal 2026-10-30 1050).tres",
SyncPlan.local_backup_file_name("kuer.json", "2026-10-30 1050")
== "kuer (Lokal 2026-10-30 1050).json",
"lokale Sicherung trägt den Lokal-Zeitstempel"
)
_check(
SyncPlan.conflict_file_name("alt.tres", "2026-10-30 1050")
== "alt (Server 2026-10-30 1050).tres",
"Legacy-Dateien behalten ihre .tres-Endung"
)
_check(
RoutineSync.is_routine_file("kuer.json")
and RoutineSync.is_routine_file("alt.tres")
and not RoutineSync.is_routine_file("sync.cfg"),
"der Sync akzeptiert JSON und Legacy-.tres"
)
var label := SyncPlan.timestamp_label(0)
_check(
label.length() == 15 and label.contains("-") and label.contains(" "),
@ -142,14 +153,14 @@ func _test_parsers() -> void:
func _test_state_roundtrip() -> void:
var path := "user://test_sync_state.cfg"
var state := {
"kuer.tres": {"local_mtime": 111, "remote_modify": 222},
"zweite.tres": {"local_mtime": 333, "remote_modify": 444},
"kuer.json": {"local_mtime": 111, "remote_modify": 222},
"zweite.json": {"local_mtime": 333, "remote_modify": 444},
}
RoutineSync.save_state(path, state)
var loaded := RoutineSync.load_state(path)
_check(loaded.size() == 2, "Sync-Stand wird gespeichert und geladen")
_check(
int(loaded.get("kuer.tres", {}).get("remote_modify", 0)) == 222,
int(loaded.get("kuer.json", {}).get("remote_modify", 0)) == 222,
"Sync-Stand behält die Server-Zeit"
)
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))

View file

@ -181,7 +181,7 @@ func _run() -> void:
_check_approx(bronze.get_speed_mps(), 3.0, "new segment uses the bronze preset")
_check_approx(bronze.duration_seconds, 2.0, "bronze duration follows the length")
var save_path := "user://test_timing.tres"
var save_path := "user://test_timing.json"
_check(controller.save_to_path(save_path), "timing routine can be saved")
_check(controller.load_from_path(save_path), "timing routine can be loaded")
var loaded_first := controller.get_routine().get_section_by_id(

View file

@ -1061,7 +1061,7 @@ func _run() -> void:
var saved_marker_id: String = jump.segment_id
# Save/load round-trip.
var roundtrip_path := "user://test_roundtrip.tres"
var roundtrip_path := "user://test_roundtrip.json"
var saved_section_title := controller.get_active_section().title
var saved_segment_count := controller.get_active_section().segments.size()
var saved_arc_id := arc_left.segment_id
@ -1158,7 +1158,7 @@ func _run() -> void:
controller.save_name_edit.text = "Test Kür"
controller.save_as_dialog.confirmed.emit()
var save_as_path := "user://routines/test_kür.tres"
var save_as_path := "user://routines/test_kür.json"
_check(
FileAccess.file_exists(save_as_path),
"save-as dialog writes a normalized filename"
@ -1514,6 +1514,111 @@ func _run() -> void:
)
controller.help_dialog.hide()
# Save-as must not replace an existing file without confirmation.
var overwrite_path := "user://routines/overwrite.json"
_check(
RoutineFile.save(controller.get_routine(), overwrite_path).is_empty(),
"overwrite fixture can be saved"
)
var overwrite_before := FileAccess.get_file_as_string(overwrite_path)
controller.save_name_edit.text = "overwrite"
controller.save_as_dialog.confirmed.emit()
_check(
controller.confirm_dialog.visible,
"save-as asks before replacing an existing file"
)
_check(
FileAccess.get_file_as_string(overwrite_path) == overwrite_before,
"the existing file stays untouched before confirmation"
)
controller.confirm_dialog.canceled.emit()
controller.confirm_dialog.hide()
_check(
FileAccess.get_file_as_string(overwrite_path) == overwrite_before,
"canceling keeps the existing file"
)
controller.save_as_dialog.confirmed.emit()
controller.confirm_dialog.confirmed.emit()
controller.confirm_dialog.hide()
_check(
FileAccess.get_file_as_string(overwrite_path) != overwrite_before,
"confirming replaces the existing file"
)
_check(
controller.get_current_path() == overwrite_path,
"confirmed save-as becomes the current file"
)
DirAccess.remove_absolute(overwrite_path)
# Global Delete shortcut must not reach the canvas through a modal.
var delete_section := controller.get_active_section()
var segment_count := delete_section.segments.size()
var doomed := controller.add_segment(
Vector2(-18.0, 10.0),
Vector2(-12.0, 10.0),
PathSegment.Direction.FORWARD,
PathSegment.Edge.OUTSIDE
)
controller.select_segment(doomed.segment_id)
controller.undo_button.grab_focus()
controller.message_dialog.hide()
controller.validation_dialog.popup_centered()
await process_frame
var delete_event := InputEventKey.new()
delete_event.keycode = KEY_DELETE
delete_event.pressed = true
controller._unhandled_key_input(delete_event)
_check(
delete_section.segments.size() == segment_count + 1,
"a visible dialog blocks the Delete shortcut"
)
controller.validation_dialog.hide()
controller._unhandled_key_input(delete_event)
_check(
delete_section.segments.size() == segment_count,
"Delete works again after the dialog closes"
)
# A dirty autosave is restored and reattached to the last file path.
var session_path := "user://routines/session_test.json"
controller.autosave_enabled = true
_check(controller.save_to_path(session_path), "session fixture can be saved")
controller.get_routine().title = "Autosave-Fassung"
controller._mark_dirty()
controller._save_autosave()
OS.delay_msec(1100)
controller._dirty = true
controller._save_autosave()
_check(controller._restore_session(), "session restore succeeds")
_check(
controller.get_current_path() == session_path,
"autosave restore keeps the last file path"
)
_check(controller.is_dirty(), "restored autosave is marked dirty")
_check(
controller.get_routine().title == "Autosave-Fassung",
"autosave content wins over the older file"
)
_check(controller.save_to_path(session_path), "restored autosave can be saved")
_check(
not FileAccess.file_exists(WhiteboardController.AUTOSAVE_PATH),
"saving removes the stale autosave"
)
_check(controller._restore_session(), "clean session restore succeeds")
_check(
not controller.is_dirty()
and controller.get_current_path() == session_path,
"clean session restores the file without dirty state"
)
controller.autosave_enabled = false
for path: String in [
session_path,
WhiteboardController.AUTOSAVE_PATH,
WhiteboardController.LEGACY_AUTOSAVE_PATH,
]:
if FileAccess.file_exists(path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(path))
scene.queue_free()
await process_frame
_finish()

View file

@ -14,10 +14,15 @@ require_godot() {
fi
}
# build_preset <preset> <release|debug> <relativer Zielpfad>
# build_preset <preset> <release|debug> <relativer oder absoluter Zielpfad>
build_preset() {
local preset="$1" mode="$2" relative="$3"
local out="$REPO_ROOT/$relative"
local out
if [[ "$relative" = /* ]]; then
out="$relative"
else
out="$REPO_ROOT/$relative"
fi
require_godot
mkdir -p "$(dirname "$out")"

77
tools/check_export.sh Executable file
View file

@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Exportiert den Linux-Release und prüft, dass er ohne Fehler startet.
#
# Prüft:
# - keine ERROR-/Autoload-Meldungen beim Start
# - keine Testskripte im Build
# - die Skater-GLB ist im Build, sofern sie lokal vorhanden ist
#
# Aufruf:
# ./tools/check_export.sh
# ./tools/check_export.sh --allow-placeholder
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
# shellcheck source=tools/_export_common.sh
source "$REPO_ROOT/tools/_export_common.sh"
ALLOW_PLACEHOLDER=0
if [[ "${1:-}" == "--allow-placeholder" ]]; then
ALLOW_PLACEHOLDER=1
fi
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/rinkplanner-export.XXXXXX")"
trap 'rm -rf "$TMP_DIR"' EXIT
BINARY="$TMP_DIR/rinkplanner.x86_64"
LOG="$TMP_DIR/run.log"
GLB="$PROJECT_DIR/assets/external/characters/skater_figure_glide_v006.glb"
echo "Exportiere Linux-Release nach $TMP_DIR …"
build_preset "Linux" release "$BINARY"
echo "Starte den Export headless …"
mkdir -p "$TMP_DIR/userdata"
set +e
XDG_DATA_HOME="$TMP_DIR/userdata" "$BINARY" --headless --quit-after 5 >"$LOG" 2>&1
STATUS=$?
set -e
cat "$LOG"
if [[ "$STATUS" -ne 0 ]]; then
echo "FEHLER: Export endet mit Status $STATUS." >&2
exit 1
fi
if grep -qE "ERROR:|SCRIPT ERROR|Failed to instantiate an autoload" "$LOG"; then
echo "FEHLER: Export startet mit Fehlermeldungen." >&2
exit 1
fi
STRINGS_FILE="$TMP_DIR/strings.txt"
strings "$BINARY" >"$STRINGS_FILE"
if grep -qE "run_[a-z0-9_]+_tests" "$STRINGS_FILE"; then
echo "FEHLER: Testskripte sind im Export enthalten." >&2
exit 1
fi
if [[ -f "$GLB" ]]; then
if ! grep -q "skater_figure_glide_v006.glb-" "$STRINGS_FILE"; then
echo "FEHLER: Die Skater-Szene fehlt im Export." >&2
exit 1
fi
if ! grep -q "skater_figure_glide_v006_Image" "$STRINGS_FILE"; then
echo "FEHLER: Die Skater-Texturen fehlen im Export." >&2
exit 1
fi
echo "3D-Asset: im Build enthalten."
elif [[ "$ALLOW_PLACEHOLDER" -eq 1 ]]; then
echo "Hinweis: GLB fehlt lokal; Export nutzt den 3D-Platzhalter."
else
echo "FEHLER: GLB fehlt lokal. Zuerst tools/sync_assets.sh --sync ausführen" >&2
echo " oder mit --allow-placeholder nur den Start prüfen." >&2
exit 1
fi
echo "OK: Export startet fehlerfrei."

View file

@ -4,6 +4,11 @@ set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
PROJECT_DIR="$REPO_ROOT/rinkplanner"
GODOT="${GODOT:-/opt/godot/Godot_v4.7.2-stable_linux.x86_64}"
WITH_EXPORT=0
if [[ "${1:-}" == "--export" ]]; then
WITH_EXPORT=1
fi
ORIGINAL_XDG_DATA_HOME="${XDG_DATA_HOME:-}"
if [[ ! -x "$GODOT" && -x "/Applications/Godot.app/Contents/MacOS/Godot" ]]; then
GODOT="/Applications/Godot.app/Contents/MacOS/Godot"
fi
@ -25,6 +30,9 @@ fi
"$GODOT" --headless --path "$PROJECT_DIR" \
--script res://tests/run_model_tests.gd
"$GODOT" --headless --path "$PROJECT_DIR" \
--script res://tests/run_file_format_tests.gd
"$GODOT" --headless --path "$PROJECT_DIR" \
--script res://tests/run_rules_tests.gd
@ -69,3 +77,13 @@ fi
"$GODOT" --headless --path "$PROJECT_DIR" \
--script res://tests/run_presentation3d_tests.gd
if [[ "$WITH_EXPORT" -eq 1 ]]; then
# The temp XDG_DATA_HOME above isolates user://, but Godot also finds its
# export templates there. Run the export check with the real environment.
if [[ -n "$ORIGINAL_XDG_DATA_HOME" ]]; then
( export XDG_DATA_HOME="$ORIGINAL_XDG_DATA_HOME"; "$REPO_ROOT/tools/check_export.sh" )
else
( unset XDG_DATA_HOME; "$REPO_ROOT/tools/check_export.sh" )
fi
fi