feat: Musik, Timeline-Labels, Abschnittssprung, PDF-Export und responsive Dialoge

This commit is contained in:
torsten 2026-11-04 13:37:12 +01:00
parent 7bbd8c9c1d
commit 533a12ef1a
17 changed files with 3483 additions and 60 deletions

View file

@ -340,7 +340,18 @@ Fahrtrichtung.
den Marker während der Standzeit mit 1,5 Umdrehungen pro Sekunde. Während den Marker während der Standzeit mit 1,5 Umdrehungen pro Sekunde. Während
des Playbacks wird die aktuelle Section hervorgehoben, des Playbacks wird die aktuelle Section hervorgehoben,
ohne die Bearbeitungs-Section zu wechseln. Steuerung: Play/Pause, Reset, ohne die Bearbeitungs-Section zu wechseln. Steuerung: Play/Pause, Reset,
Timeline-Scrubbing und Geschwindigkeit 0,25×–2,0×. Die Dauer kommt aus dem Timeline-Scrubbing und Geschwindigkeit 0,25×–2,0×. Ein optionales
Musikstück (MP3/OGG/WAV) liegt neben der Kür-JSON in `user://routines/`
und läuft über einen `AudioStreamPlayer` auf derselben Zeitbasis: Start,
Pause, Reset, Scrubbing und Geschwindigkeit wirken auf Bild und Ton. Über
der Timeline liegt eine Label-Spur: Labels von Segmenten und Kürzel von
Elementen ohne Freitext erscheinen schräg an ihrem Startzeitpunkt (auch
Elemente mit 0 s Standzeit); ein Klick in die Spur legt ein eigenes,
frei beschriftetes Timeline-Label an, das per Klick wieder bearbeitet oder
gelöscht werden kann. Ein Wechsel des aktiven Abschnitts setzt Marker,
Timeline-Slider und Label-Spur an den Anfang dieses Abschnitts; eine
laufende Wiedergabe hält dabei an. Die
Dauer kommt aus dem
Segment-Timing (Default Adult Gold, 4,3 m/s) bzw. bei Punktmarkern aus der Segment-Timing (Default Adult Gold, 4,3 m/s) bzw. bei Punktmarkern aus der
Element-Standzeit. Nicht verbundene Segmente Element-Standzeit. Nicht verbundene Segmente
führen zu einem Sprung des Markers an den Start des nächsten Segments. führen zu einem Sprung des Markers an den Start des nächsten Segments.
@ -423,13 +434,23 @@ ggf. eines nach `touchend` (300-ms-Guard).
(2560 × 1600) mit Titel, Section-Nummern und Legende. (2560 × 1600) mit Titel, Section-Nummern und Legende.
- **Umfang:** Gesamte Kür oder aktiver Abschnitt; Dateien landen unter - **Umfang:** Gesamte Kür oder aktiver Abschnitt; Dateien landen unter
`user://exports/`. `user://exports/`.
- **PDF** ist nicht nativ in Godot. Erste Stufe: Browser-Druck aus SVG; - **PDF** erzeugt `RoutinePdfExporter` direkt als Vektordokument über einen
eine echte PDF-Ausgabe ist ein separates Arbeitspaket. kleinen eigenen PDF-Writer (Helvetica/WinAnsi, keine externe Bibliothek):
eine Übersichtsseite mit allen Laufwegen und der Abschnittstabelle, danach
eine Seite pro Abschnitt mit nummerierten Laufwegen sowie Start-/Endzeit,
Dauer und Element bzw. Label. Lange Abschnitte laufen auf
Fortsetzungsseiten weiter. Die Kurven werden als PDF-Bézierkurven aus den
`Curve2D`-Handles geschrieben. Nach jedem Export zeigt ein Abschlussdialog
den absoluten Pfad und bietet **Öffnen**, **Ordner anzeigen** und
**Pfad kopieren** über `OS.shell_open` / `OS.shell_show_in_file_manager`;
optional startet das Ergebnis direkt im Standardprogramm.
- **Persistenz** erfolgt lokal als JSON unter `user://routines/` - **Persistenz** erfolgt lokal als JSON unter `user://routines/`
(`RoutineFile`, Format `rinkplanner.routine`). Die Datei enthält (`RoutineFile`, Format `rinkplanner.routine`). Die Datei enthält
`schema_version` (aktuell 2); neuere Schemata werden abgelehnt, `schema_version` (aktuell 4); neuere Schemata werden abgelehnt,
Schema-1-Dateien beim Laden migriert. Die Elementfelder kamen additiv mit ältere Dateien beim Laden migriert (Schema 1: Dauer→Tempo, Schema 2→3:
Defaults hinzu, deshalb bleibt das Schema bei 2. Legacy-`.tres`-Dateien additives Feld `music_file`, Schema 3→4: additive Timeline-Labels).
Die Elementfelder kamen additiv mit
Defaults hinzu. Legacy-`.tres`-Dateien
bleiben lesbar: Vor `ResourceLoader.load` prüft `RoutineFile` eine bleiben lesbar: Vor `ResourceLoader.load` prüft `RoutineFile` eine
Whitelist (nur die vier Modellskripte, kein eingebettetes GDScript, keine Whitelist (nur die vier Modellskripte, kein eingebettetes GDScript, keine
Szenen). Neue Speicherungen schreiben immer `.json`; eine geöffnete Szenen). Neue Speicherungen schreiben immer `.json`; eine geöffnete
@ -438,6 +459,10 @@ ggf. eines nach `touchend` (300-ms-Guard).
Kürläufe werden über das Datei-Menü gespeichert und geladen; der Kürläufe werden über das Datei-Menü gespeichert und geladen; der
Öffnen-Dialog zeigt `.json` und Legacy-`.tres`, wobei eine vorhandene Öffnen-Dialog zeigt `.json` und Legacy-`.tres`, wobei eine vorhandene
`.json` die gleichnamige `.tres` verdeckt. `.json` die gleichnamige `.tres` verdeckt.
`music_file` nennt nur den Dateinamen; die Audiodatei liegt flach daneben
in `user://routines/` und wird vom Sync mitübertragen.
`timeline_labels` speichert freie Timeline-Annotationen als
`{time_seconds, text}`.
- **Autosave** schreibt nach 1,5 s Inaktivität nur bei ungespeicherten - **Autosave** schreibt nach 1,5 s Inaktivität nur bei ungespeicherten
Änderungen nach `user://autosave.json`; beim Speichern oder Öffnen einer Änderungen nach `user://autosave.json`; beim Speichern oder Öffnen einer
Datei wird der Autosave entfernt. Der letzte Dateipfad liegt in Datei wird der Autosave entfernt. Der letzte Dateipfad liegt in
@ -599,4 +624,5 @@ Viewport-Screenshot; sie ersetzen die headless Tests nicht.
umgesetzt. Offen sind Beschleunigung/Verzögerung innerhalb eines Segments umgesetzt. Offen sind Beschleunigung/Verzögerung innerhalb eines Segments
und eine noch genauere Profilpflege aus eigenen Messungen. und eine noch genauere Profilpflege aus eigenen Messungen.
12. **Playback-Komfort:** Loop, Scrubbing während des Abspielens und 12. **Playback-Komfort:** Loop, Scrubbing während des Abspielens und
Audio-Synchronisation sind bewusst noch nicht enthalten. Audio-Synchronisation sind umgesetzt; offen sind Loop-Modus und eine
Lautstärkeregelung für die Musik.

View file

@ -63,6 +63,63 @@ die 2D-Funktionen sind davon nicht betroffen.
nicht. nicht.
- Es gibt keine Bearbeitung und keine Auswahl in 3D. - Es gibt keine Bearbeitung und keine Auswahl in 3D.
## Musik
Ein Musikstück gehört optional zur Kür. **Musik…** in der Playback-Leiste
öffnet die Dateiauswahl für **MP3** (auch OGG/WAV). Die Datei wird in den
Kür-Ordner kopiert und in der Kür-JSON als Dateiname vermerkt.
- **Start/Pause/Reset** steuern Bild und Musik gemeinsam.
- **Timeline-Scrubbing** setzt auch die Musik an die entsprechende Stelle.
- **Geschwindigkeit** wirkt auf beide: bei 0,5× läuft die Musik langsamer
(und tiefer), bei 2× schneller.
- **×** entfernt die Musik aus der Kür, löscht die Datei aber nicht. So
bleibt sie für andere Kürdateien erhalten.
- Beim **Sync** wird die Musikdatei wie die Kür-JSON hoch- und
heruntergeladen. Fehlt sie auf einem Gerät, zeigt die Leiste
„(fehlt)“; nach dem nächsten Sync ist sie verfügbar.
## Timeline-Labels
Über der Playback-Timeline liegt eine Label-Spur:
- **Kür-Labels:** Segmente mit eigener Beschriftung erscheinen schräg an
ihrem Startzeitpunkt (blau). Elemente ohne Freitext zeigen ihr Kürzel
(z. B. `1Lz`, `CCoSp`, `StSq`); auch Elemente mit 0 s Standzeit bleiben
sichtbar.
- **Eigene Labels:** Ein Klick in eine freie Stelle der Spur legt ein Label
an diesem Zeitpunkt an; der Text wird im Dialog eingegeben.
- **Bearbeiten:** Ein Klick auf ein goldenes eigenes Label öffnet den Dialog
erneut. Dort lässt es sich umbenennen oder löschen.
- Labels gehören zur Kür, werden mitgespeichert und über Undo/Redo sowie den
Sync mitgeführt.
## Abschnittswechsel und Playback
Wird in der Abschnittsliste ein anderer Abschnitt gewählt, springen die
Abspielfigur und die Playback-Timeline an den **Anfang dieses Abschnitts**.
Eine laufende Wiedergabe wird dabei angehalten; mit **Start** läuft sie ab
dieser Stelle weiter. Die Position berücksichtigt alle davor liegenden
Abschnitte inklusive Element-Standzeiten.
## Export
**Datei → Exportieren…** schreibt nach `user://exports/`. Zur Wahl stehen:
- **SVG (Vektor):** gesamte Kür oder aktiver Abschnitt als druckbares Blatt.
- **PNG (hochauflösend):** 2560 × 1600 für Tablet-Weitergabe.
- **PDF (Laufwege mit Zeit):** eine Übersichtsseite mit allen Laufwegen und
Abschnittszeiten, danach eine Seite pro Abschnitt. Dort sind die Laufwege
in Reihenfolge nummeriert; die Tabelle nennt Start, Ende, Dauer und
Element/Label. Lange Abschnitte werden auf weiteren Seiten fortgesetzt.
Bei „Aktiver Abschnitt“ entsteht nur die Seite dieses Abschnitts.
Nach dem Export erscheint der **absolute Dateipfad** mit den Buttons
**Öffnen**, **Ordner anzeigen** und **Pfad kopieren**. Die Option
**„Nach dem Export mit dem Standardprogramm öffnen“** ist standardmäßig
aktiv; damit startet z. B. das PDF direkt im PDF-Betrachter. Über
**Datei → Exportordner öffnen** erreicht man den Ordner auch später.
## Kürzel und Base Value ## Kürzel und Base Value
- Das **Kürzel** bezeichnet die Elementfamilie, z. B. `3Lz`, `CCoSp` oder - Das **Kürzel** bezeichnet die Elementfamilie, z. B. `3Lz`, `CCoSp` oder

View file

@ -29,6 +29,13 @@ Voraussetzung für Phase 1.
Session-Restore (Legacy-`.tres` lesbar) Session-Restore (Legacy-`.tres` lesbar)
- [x] Playback-Dot mit Blickrichtung, Timeline, Play/Pause/Reset und - [x] Playback-Dot mit Blickrichtung, Timeline, Play/Pause/Reset und
Geschwindigkeit 0,25×–2,0× Geschwindigkeit 0,25×–2,0×
- [x] Musikstück (MP3/OGG/WAV) je Kür laden; Wiedergabe, Scrubbing und
Geschwindigkeit laufen synchron zum Läufer; der FTP-Sync überträgt die
Musikdatei mit der Kür
- [x] Timeline-Labels: Kür-Labels schräg auf der Timeline, eigene Labels per
Klick anlegen, bearbeiten und löschen
- [x] Abschnittswechsel setzt Abspielfigur und Timeline an den
Abschnittsanfang
- [x] Geschwindigkeits-Arbeitsannahmen in `docs/speed-assumptions.md` - [x] Geschwindigkeits-Arbeitsannahmen in `docs/speed-assumptions.md`
- [x] Headless-Tests und visuelle Smoke-Tests - [x] Headless-Tests und visuelle Smoke-Tests
@ -49,6 +56,10 @@ Voraussetzung für Phase 1.
- [x] SVG direkt aus dem Modell (Kurven, Sections, Legende, Rink) - [x] SVG direkt aus dem Modell (Kurven, Sections, Legende, Rink)
- [x] Export der aktiven Section und des gesamten Programms - [x] Export der aktiven Section und des gesamten Programms
- [x] SVG als Grundlage für Browser-Druck (PDF) - [x] SVG als Grundlage für Browser-Druck (PDF)
- [x] Native PDF-Ausgabe der Laufwege mit Zeit (Übersicht + Abschnittsseiten,
Vektorpfade, Tabellen, Fortsetzungsseiten)
- [x] Export-Abschluss mit absolutem Pfad sowie „Öffnen“, „Ordner anzeigen“
und „Pfad kopieren“; optional direkt im Standardprogramm öffnen
- [x] Export-Tests: Geometrie, Section-Reihenfolge, Sichtbarkeit - [x] Export-Tests: Geometrie, Section-Reihenfolge, Sichtbarkeit
- [x] Export-Dialog mit Dateiname, Format und Umfang - [x] Export-Dialog mit Dateiname, Format und Umfang
@ -260,8 +271,8 @@ Schritte.
## Bewusst nicht jetzt ## Bewusst nicht jetzt
- Audio-Synchronisation (laut Definition in Phase 1 zurückgestellt) - Native PDF-Ausgabe mit Bildern/Screenshots (die aktuelle PDF-Ausgabe ist
- Native PDF-Ausgabe vektorbasiert und enthält keine Fotos)
- Vollständiges ISU-Regelwerk vor dem stabilen Planungs-Workflow - Vollständiges ISU-Regelwerk vor dem stabilen Planungs-Workflow
- Sync-Komfort und visuelles UI-Refactoring (erst nach dem PoC) - Sync-Komfort und visuelles UI-Refactoring (erst nach dem PoC)
- 3D-Produktionsreife - 3D-Produktionsreife

View file

@ -24,7 +24,9 @@ Danach **Datei → Jetzt synchronisieren**.
## Was passiert ## Was passiert
- Jede Kür liegt als `.json` unter `user://routines/` und wird 1:1 in das - Jede Kür liegt als `.json` unter `user://routines/` und wird 1:1 in das
FTP-Verzeichnis gespiegelt (flach, keine Unterordner). Legacy-`.tres`- FTP-Verzeichnis gespiegelt (flach, keine Unterordner). Gehört eine
Musikdatei zur Kür (`.mp3`, `.ogg`, `.wav`), liegt sie im selben Ordner und
wird mit denselben Regeln hoch- und heruntergeladen. Legacy-`.tres`-
Dateien werden weiterhin mit synchronisiert, damit bestehende Installationen Dateien werden weiterhin mit synchronisiert, damit bestehende Installationen
ihre Serverkopien nicht verlieren; neue Speicherungen schreiben `.json`. ihre Serverkopien nicht verlieren; neue Speicherungen schreiben `.json`.
Beim Laden wird eine `.tres` vor dem `ResourceLoader` gegen eine Whitelist Beim Laden wird eine `.tres` vor dem `ResourceLoader` gegen eine Whitelist
@ -93,6 +95,13 @@ Kür öffnen und bearbeiten.
Server kann damit keine eingebetteten GDScripts ausführen. Server kann damit keine eingebetteten GDScripts ausführen.
- Neue Speicherungen sind JSON; der Sync akzeptiert weiterhin `.tres`, damit - Neue Speicherungen sind JSON; der Sync akzeptiert weiterhin `.tres`, damit
bestehende Dateien auf Server und Tablet nicht verschwinden. bestehende Dateien auf Server und Tablet nicht verschwinden.
- Musikdateien werden als normale Anhänge der Kür behandelt: Die JSON nennt
nur den Dateinamen (`music_file`), die Datei liegt daneben. Ändert sich die
Musik auf einem Gerät, lädt der nächste Sync sie hoch; auf dem anderen Gerät
wird sie heruntergeladen und beim Öffnen der Kür verwendet. Konfliktkopien
behalten die Audio-Endung (z. B. `kuer (Server …).mp3`).
- Eigene Timeline-Labels stehen in der Kür-JSON (`timeline_labels`) und
werden ohne Zusatzdateien mit der Kür übertragen.
- Zugangsdaten liegen in `user://sync.cfg` (Klartext, app-privat). Auf - Zugangsdaten liegen in `user://sync.cfg` (Klartext, app-privat). Auf
Android ist das der interne App-Speicher, auf dem Desktop Android ist das der interne App-Speicher, auf dem Desktop
`~/.local/share/godot/app_userdata/Rinkplanner/`. `~/.local/share/godot/app_userdata/Rinkplanner/`.

View file

@ -1,7 +1,8 @@
[gd_scene load_steps=9 format=3] [gd_scene load_steps=10 format=3]
[ext_resource type="Script" path="res://src/whiteboard/ctrl/whiteboard_controller.gd" id="1_controller"] [ext_resource type="Script" path="res://src/whiteboard/ctrl/whiteboard_controller.gd" id="1_controller"]
[ext_resource type="Script" path="res://src/whiteboard/view/rink_canvas.gd" id="2_canvas"] [ext_resource type="Script" path="res://src/whiteboard/view/rink_canvas.gd" id="2_canvas"]
[ext_resource type="Script" path="res://src/whiteboard/view/timeline_label_lane.gd" id="3_label_lane"]
[sub_resource type="ButtonGroup" id="ButtonGroup_direction"] [sub_resource type="ButtonGroup" id="ButtonGroup_direction"]
[sub_resource type="ButtonGroup" id="ButtonGroup_edge"] [sub_resource type="ButtonGroup" id="ButtonGroup_edge"]
@ -454,7 +455,7 @@ text = "Labels"
tooltip_text = "Beschriftungen ein- oder ausblenden" tooltip_text = "Beschriftungen ein- oder ausblenden"
[node name="PlaybackBar" type="PanelContainer" parent="Layout"] [node name="PlaybackBar" type="PanelContainer" parent="Layout"]
custom_minimum_size = Vector2(0, 72) custom_minimum_size = Vector2(0, 124)
layout_mode = 2 layout_mode = 2
theme_override_styles/panel = SubResource("StyleBoxFlat_playback") theme_override_styles/panel = SubResource("StyleBoxFlat_playback")
@ -490,11 +491,22 @@ text = "0,0 / 0,0 s"
horizontal_alignment = 1 horizontal_alignment = 1
vertical_alignment = 1 vertical_alignment = 1
[node name="PlaybackTimeline" type="HSlider" parent="Layout/PlaybackBar/PlaybackContent"] [node name="PlaybackTimelineArea" type="VBoxContainer" parent="Layout/PlaybackBar/PlaybackContent"]
unique_name_in_owner = true custom_minimum_size = Vector2(0, 100)
custom_minimum_size = Vector2(0, 56)
layout_mode = 2 layout_mode = 2
size_flags_horizontal = 3 size_flags_horizontal = 3
theme_override_constants/separation = 0
[node name="TimelineLabelLane" type="Control" parent="Layout/PlaybackBar/PlaybackContent/PlaybackTimelineArea"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 60)
layout_mode = 2
script = ExtResource("3_label_lane")
[node name="PlaybackTimeline" type="HSlider" parent="Layout/PlaybackBar/PlaybackContent/PlaybackTimelineArea"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
max_value = 0.0 max_value = 0.0
step = 0.01 step = 0.01
editable = false editable = false
@ -506,6 +518,33 @@ layout_mode = 2
theme_override_font_sizes/font_size = 15 theme_override_font_sizes/font_size = 15
tooltip_text = "Wiedergabegeschwindigkeit" tooltip_text = "Wiedergabegeschwindigkeit"
[node name="MusicButton" type="Button" parent="Layout/PlaybackBar/PlaybackContent"]
unique_name_in_owner = true
custom_minimum_size = Vector2(96, 56)
layout_mode = 2
theme_override_font_sizes/font_size = 15
text = "Musik…"
tooltip_text = "Musikstück (MP3) für diese Kür laden"
[node name="MusicLabel" type="Label" parent="Layout/PlaybackBar/PlaybackContent"]
unique_name_in_owner = true
custom_minimum_size = Vector2(190, 56)
layout_mode = 2
theme_override_colors/font_color = Color(0.85098, 0.890196, 0.941176, 1)
theme_override_font_sizes/font_size = 13
text = "Keine Musik"
clip_text = true
vertical_alignment = 1
[node name="MusicClearButton" type="Button" parent="Layout/PlaybackBar/PlaybackContent"]
unique_name_in_owner = true
custom_minimum_size = Vector2(48, 56)
layout_mode = 2
theme_override_font_sizes/font_size = 18
disabled = true
text = "×"
tooltip_text = "Musik von dieser Kür entfernen"
[node name="StatusBar" type="PanelContainer" parent="Layout"] [node name="StatusBar" type="PanelContainer" parent="Layout"]
custom_minimum_size = Vector2(0, 64) custom_minimum_size = Vector2(0, 64)
layout_mode = 2 layout_mode = 2
@ -887,6 +926,19 @@ unique_name_in_owner = true
wait_time = 1.5 wait_time = 1.5
one_shot = true one_shot = true
[node name="MusicFileDialog" type="FileDialog" parent="."]
unique_name_in_owner = true
title = "Musikstück laden"
size = Vector2i(780, 560)
ok_button_text = "Laden"
cancel_button_text = "Abbrechen"
file_mode = 0
access = 2
filters = PackedStringArray("*.mp3 ; MP3-Musik", "*.ogg ; OGG-Musik", "*.wav ; WAV-Audio")
[node name="MusicPlayer" type="AudioStreamPlayer" parent="."]
unique_name_in_owner = true
[node name="SaveAsDialog" type="ConfirmationDialog" parent="."] [node name="SaveAsDialog" type="ConfirmationDialog" parent="."]
unique_name_in_owner = true unique_name_in_owner = true
title = "Kür speichern unter" title = "Kür speichern unter"
@ -910,6 +962,38 @@ unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56) custom_minimum_size = Vector2(0, 56)
layout_mode = 2 layout_mode = 2
[node name="TimelineLabelDialog" type="ConfirmationDialog" parent="."]
unique_name_in_owner = true
title = "Timeline-Label"
size = Vector2i(480, 250)
ok_button_text = "Übernehmen"
cancel_button_text = "Abbrechen"
[node name="TimelineLabelBox" type="VBoxContainer" parent="TimelineLabelDialog"]
offset_left = 8.0
offset_top = 8.0
offset_right = 472.0
offset_bottom = 150.0
theme_override_constants/separation = 8
[node name="TimelineLabelTimeLabel" type="Label" parent="TimelineLabelDialog/TimelineLabelBox"]
unique_name_in_owner = true
layout_mode = 2
text = "Zeitpunkt: 0,0 s"
[node name="TimelineLabelEdit" type="LineEdit" parent="TimelineLabelDialog/TimelineLabelBox"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
max_length = 60
placeholder_text = "Beschriftung"
[node name="TimelineLabelDeleteButton" type="Button" parent="TimelineLabelDialog/TimelineLabelBox"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Label löschen"
[node name="OpenDialog" type="AcceptDialog" parent="."] [node name="OpenDialog" type="AcceptDialog" parent="."]
unique_name_in_owner = true unique_name_in_owner = true
title = "Kür öffnen" title = "Kür öffnen"
@ -993,49 +1077,128 @@ text = "Geschwindigkeit = Strecke / Zeit"
[node name="ExportDialog" type="ConfirmationDialog" parent="."] [node name="ExportDialog" type="ConfirmationDialog" parent="."]
unique_name_in_owner = true unique_name_in_owner = true
title = "Kür exportieren" title = "Kür exportieren"
size = Vector2i(480, 360) size = Vector2i(480, 520)
wrap_controls = false
ok_button_text = "Exportieren" ok_button_text = "Exportieren"
cancel_button_text = "Abbrechen" cancel_button_text = "Abbrechen"
[node name="ExportBox" type="VBoxContainer" parent="ExportDialog"] [node name="ExportScroll" type="ScrollContainer" parent="ExportDialog"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = 8.0 offset_left = 8.0
offset_top = 8.0 offset_top = 8.0
offset_right = 472.0 offset_right = -8.0
offset_bottom = 280.0 offset_bottom = -64.0
grow_horizontal = 2
grow_vertical = 2
horizontal_scroll_mode = 0
follow_focus = true
[node name="ExportBox" type="VBoxContainer" parent="ExportDialog/ExportScroll"]
layout_mode = 2
size_flags_horizontal = 3
theme_override_constants/separation = 8 theme_override_constants/separation = 8
[node name="ExportNameLabel" type="Label" parent="ExportDialog/ExportBox"] [node name="ExportNameLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"]
layout_mode = 2 layout_mode = 2
text = "Dateiname" text = "Dateiname"
[node name="ExportNameEdit" type="LineEdit" parent="ExportDialog/ExportBox"] [node name="ExportNameEdit" type="LineEdit" parent="ExportDialog/ExportScroll/ExportBox"]
unique_name_in_owner = true unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56) custom_minimum_size = Vector2(0, 56)
layout_mode = 2 layout_mode = 2
[node name="ExportFormatLabel" type="Label" parent="ExportDialog/ExportBox"] [node name="ExportFormatLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"]
layout_mode = 2 layout_mode = 2
text = "Format" text = "Format"
[node name="ExportFormatOption" type="OptionButton" parent="ExportDialog/ExportBox"] [node name="ExportFormatOption" type="OptionButton" parent="ExportDialog/ExportScroll/ExportBox"]
unique_name_in_owner = true unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56) custom_minimum_size = Vector2(0, 56)
layout_mode = 2 layout_mode = 2
[node name="ExportScopeLabel" type="Label" parent="ExportDialog/ExportBox"] [node name="ExportScopeLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"]
layout_mode = 2 layout_mode = 2
text = "Umfang" text = "Umfang"
[node name="ExportScopeOption" type="OptionButton" parent="ExportDialog/ExportBox"] [node name="ExportScopeOption" type="OptionButton" parent="ExportDialog/ExportScroll/ExportBox"]
unique_name_in_owner = true unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56) custom_minimum_size = Vector2(0, 56)
layout_mode = 2 layout_mode = 2
[node name="ExportHint" type="Label" parent="ExportDialog/ExportBox"] [node name="ExportHint" type="Label" parent="ExportDialog/ExportScroll/ExportBox"]
custom_minimum_size = Vector2(0, 34)
layout_mode = 2 layout_mode = 2
theme_override_colors/font_color = Color(0.580392, 0.639216, 0.721569, 1) theme_override_colors/font_color = Color(0.580392, 0.639216, 0.721569, 1)
theme_override_font_sizes/font_size = 12 theme_override_font_sizes/font_size = 12
text = "Ziel: user://exports" text = "Ziel: export-Ordner im App-Datenverzeichnis · der absolute Pfad erscheint nach dem Export"
autowrap_mode = 3
[node name="ExportOpenAfterCheck" type="CheckBox" parent="ExportDialog/ExportScroll/ExportBox"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 44)
layout_mode = 2
button_pressed = true
text = "Nach dem Export öffnen"
tooltip_text = "Ergebnis nach dem Export mit dem Standardprogramm öffnen"
[node name="ExportDoneDialog" type="AcceptDialog" parent="."]
unique_name_in_owner = true
title = "Export abgeschlossen"
size = Vector2i(660, 320)
wrap_controls = false
ok_button_text = "Schließen"
[node name="ExportDoneBox" type="VBoxContainer" parent="ExportDoneDialog"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
offset_left = 12.0
offset_top = 12.0
offset_right = -12.0
offset_bottom = -64.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/separation = 10
[node name="ExportDoneLabel" type="RichTextLabel" parent="ExportDoneDialog/ExportDoneBox"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 96)
layout_mode = 2
size_flags_vertical = 3
bbcode_enabled = false
scroll_active = false
selection_enabled = true
autowrap_mode = 3
[node name="ExportDoneButtons" type="HFlowContainer" parent="ExportDoneDialog/ExportDoneBox"]
layout_mode = 2
theme_override_constants/h_separation = 8
theme_override_constants/v_separation = 8
[node name="ExportOpenButton" type="Button" parent="ExportDoneDialog/ExportDoneBox/ExportDoneButtons"]
unique_name_in_owner = true
custom_minimum_size = Vector2(140, 56)
layout_mode = 2
text = "Öffnen"
tooltip_text = "Datei mit dem Standardprogramm öffnen"
[node name="ExportFolderButton" type="Button" parent="ExportDoneDialog/ExportDoneBox/ExportDoneButtons"]
unique_name_in_owner = true
custom_minimum_size = Vector2(180, 56)
layout_mode = 2
text = "Ordner anzeigen"
tooltip_text = "Exportordner im Dateimanager öffnen"
[node name="ExportCopyPathButton" type="Button" parent="ExportDoneDialog/ExportDoneBox/ExportDoneButtons"]
unique_name_in_owner = true
custom_minimum_size = Vector2(170, 56)
layout_mode = 2
text = "Pfad kopieren"
tooltip_text = "Absoluten Dateipfad in die Zwischenablage kopieren"
[node name="ElementFeatureMenu" type="PopupMenu" parent="."] [node name="ElementFeatureMenu" type="PopupMenu" parent="."]
unique_name_in_owner = true unique_name_in_owner = true

View file

@ -28,6 +28,13 @@ const MAX_LABEL_LENGTH := 40
const MAX_ELEMENT_CODE_LENGTH := 24 const MAX_ELEMENT_CODE_LENGTH := 24
const MAX_FEATURES := 16 const MAX_FEATURES := 16
const MAX_COMBINATION_JUMPS := 2 const MAX_COMBINATION_JUMPS := 2
const MAX_MUSIC_FILE_LENGTH := 160
const MAX_TIMELINE_LABELS := 200
const MAX_TIMELINE_LABEL_LENGTH := 60
## Audio files that may belong to a routine. They live next to the routine
## JSON in `user://routines/` and are transferred by the routine sync.
const AUDIO_EXTENSIONS := [".mp3", ".ogg", ".wav"]
## Only the model resources may be referenced by a legacy `.tres`. The list is ## 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. ## deliberately small; it contains no script with an `_init` side effect.
@ -58,6 +65,33 @@ static func is_routine_path(path: String) -> bool:
return lower.ends_with(JSON_EXTENSION) or lower.ends_with(LEGACY_EXTENSION) return lower.ends_with(JSON_EXTENSION) or lower.ends_with(LEGACY_EXTENSION)
static func is_audio_file(name: String) -> bool:
var lower := name.to_lower()
for extension: String in AUDIO_EXTENSIONS:
if lower.ends_with(extension):
return true
return false
## Accepts only a plain audio file name: no directories, no drive letters and
## no traversal. The sync stores all routine attachments flat in one folder.
static func safe_music_file_name(value: String) -> String:
var cleaned := value.strip_edges()
if cleaned.is_empty() or cleaned.length() > MAX_MUSIC_FILE_LENGTH:
return ""
if (
cleaned.contains("/")
or cleaned.contains("\\")
or cleaned.contains(":")
or cleaned.contains("..")
or cleaned.begins_with(".")
):
return ""
if not is_audio_file(cleaned):
return ""
return cleaned
## Saves [param routine] atomically at [param path]. Returns an empty string on ## Saves [param routine] atomically at [param path]. Returns an empty string on
## success, or a user-facing error message. ## success, or a user-facing error message.
static func save(routine: Routine, path: String) -> String: static func save(routine: Routine, path: String) -> String:
@ -135,6 +169,7 @@ static func decode_json(text: String) -> Dictionary:
routine.routine_id = _text(data, "routine_id", "routine").left(MAX_TEXT_LENGTH) routine.routine_id = _text(data, "routine_id", "routine").left(MAX_TEXT_LENGTH)
routine.title = _text(data, "title", "").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.skater_name = _text(data, "skater_name", "").left(MAX_TEXT_LENGTH)
routine.music_file = safe_music_file_name(_text(data, "music_file", ""))
routine.adult_category = ( routine.adult_category = (
_text(data, "adult_category", "").left(MAX_TEXT_LENGTH) _text(data, "adult_category", "").left(MAX_TEXT_LENGTH)
) )
@ -148,6 +183,12 @@ static func decode_json(text: String) -> Dictionary:
0, 0,
9999 9999
) )
var labels_result := _decode_timeline_labels(
data.get("timeline_labels", [])
)
if not str(labels_result["error"]).is_empty():
return labels_result
routine.timeline_labels.assign(labels_result["labels"])
var rink_data: Variant = data.get("rink", {}) var rink_data: Variant = data.get("rink", {})
if not rink_data is Dictionary: if not rink_data is Dictionary:
@ -198,9 +239,11 @@ static func encode(routine: Routine) -> String:
"routine_id": routine.routine_id, "routine_id": routine.routine_id,
"title": routine.title, "title": routine.title,
"skater_name": routine.skater_name, "skater_name": routine.skater_name,
"music_file": safe_music_file_name(routine.music_file),
"adult_category": routine.adult_category, "adult_category": routine.adult_category,
"assumed_pcs_average": routine.assumed_pcs_average, "assumed_pcs_average": routine.assumed_pcs_average,
"assumed_falls": routine.assumed_falls, "assumed_falls": routine.assumed_falls,
"timeline_labels": _encode_timeline_labels(routine.timeline_labels),
"rink": { "rink": {
"length_m": routine.rink.length_m if routine.rink != null else 60.0, "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, "width_m": routine.rink.width_m if routine.rink != null else 30.0,
@ -218,6 +261,27 @@ static func encode(routine: Routine) -> String:
return JSON.stringify(data, "\t", false, true) return JSON.stringify(data, "\t", false, true)
static func _encode_timeline_labels(labels: Array[Dictionary]) -> Array:
var result: Array = []
for entry: Dictionary in labels:
var text := str(entry.get("text", "")).strip_edges().left(
MAX_TIMELINE_LABEL_LENGTH
)
if text.is_empty():
continue
result.append({
"time_seconds": clampf(
_number(entry, "time_seconds", 0.0),
0.0,
86400.0
),
"text": text,
})
if result.size() >= MAX_TIMELINE_LABELS:
break
return result
static func _encode_section(section: RoutineSection) -> Dictionary: static func _encode_section(section: RoutineSection) -> Dictionary:
var segments: Array = [] var segments: Array = []
for segment: PathSegment in section.segments: for segment: PathSegment in section.segments:
@ -282,6 +346,37 @@ static func _encode_segment(segment: PathSegment) -> Dictionary:
} }
static func _decode_timeline_labels(value: Variant) -> Dictionary:
if not value is Array:
return _error("Die Timeline-Labels sind ungültig.")
if value.size() > MAX_TIMELINE_LABELS:
return _error("Die Kür enthält zu viele Timeline-Labels.")
var labels: Array[Dictionary] = []
for entry: Variant in value:
if not entry is Dictionary:
return _error("Ein Timeline-Label ist ungültig.")
var data: Dictionary = entry
var text := _text(data, "text", "").strip_edges().left(
MAX_TIMELINE_LABEL_LENGTH
)
if text.is_empty():
continue
labels.append({
"time_seconds": clampf(
_number(data, "time_seconds", 0.0),
0.0,
86400.0
),
"text": text,
})
labels.sort_custom(
func(a: Dictionary, b: Dictionary) -> bool:
return float(a["time_seconds"]) < float(b["time_seconds"])
)
return {"labels": labels, "error": ""}
static func _decode_section(data: Dictionary) -> Dictionary: static func _decode_section(data: Dictionary) -> Dictionary:
var section := RoutineSection.new() var section := RoutineSection.new()
section.section_id = _text(data, "section_id", "").left(MAX_TEXT_LENGTH) section.section_id = _text(data, "section_id", "").left(MAX_TEXT_LENGTH)

View file

@ -4,12 +4,18 @@ extends Resource
## Root aggregate of a choreography. Pure data: no rendering, no input, no ## Root aggregate of a choreography. Pure data: no rendering, no input, no
## timing state. The whiteboard view and the future 3D layer both consume it. ## timing state. The whiteboard view and the future 3D layer both consume it.
const CURRENT_SCHEMA_VERSION := 2 const CURRENT_SCHEMA_VERSION := 4
@export var schema_version: int = CURRENT_SCHEMA_VERSION @export var schema_version: int = CURRENT_SCHEMA_VERSION
@export var routine_id: String = "" @export var routine_id: String = ""
@export var title: String = "" @export var title: String = ""
@export var skater_name: String = "" @export var skater_name: String = ""
## File name of the music track inside `user://routines/`. The file is kept
## next to the routine JSON so the routine sync transfers it with the routine.
@export var music_file: String = ""
## Free annotations on the playback timeline. Each entry is
## `{"time_seconds": float, "text": String}` and is independent of segments.
@export var timeline_labels: Array[Dictionary] = []
## Adult competition category code (e.g. "gold", "silver", "bronze"). Empty ## Adult competition category code (e.g. "gold", "silver", "bronze"). Empty
## means no category-specific validation. ## means no category-specific validation.
@export var adult_category: String = "" @export var adult_category: String = ""
@ -29,6 +35,10 @@ func get_duration_seconds() -> float:
return total return total
func has_music() -> bool:
return not music_file.strip_edges().is_empty()
func get_length_m() -> float: func get_length_m() -> float:
var total := 0.0 var total := 0.0
for section: RoutineSection in sections: for section: RoutineSection in sections:
@ -69,6 +79,12 @@ func validate() -> PackedStringArray:
errors.append("assumed_pcs_average must be between 0 and 10") errors.append("assumed_pcs_average must be between 0 and 10")
if assumed_falls < 0: if assumed_falls < 0:
errors.append("assumed_falls must not be negative") errors.append("assumed_falls must not be negative")
for entry: Dictionary in timeline_labels:
var text := str(entry.get("text", "")).strip_edges()
if text.is_empty():
errors.append("timeline label must not be empty")
if float(entry.get("time_seconds", -1.0)) < 0.0:
errors.append("timeline label time must not be negative")
var seen_section_ids: Dictionary[String, bool] = {} var seen_section_ids: Dictionary[String, bool] = {}
var seen_orders: Dictionary[int, bool] = {} var seen_orders: Dictionary[int, bool] = {}

View file

@ -10,8 +10,15 @@ const STATE_PATH := "user://sync_state.cfg"
const TEMP_SUFFIX := ".part" const TEMP_SUFFIX := ".part"
const UPLOAD_SUFFIX := ".uploading" const UPLOAD_SUFFIX := ".uploading"
## New routines are JSON; legacy `.tres` files stay in the sync so existing ## New routines are JSON; legacy `.tres` files stay in the sync so existing
## installations do not lose their server copies. ## installations do not lose their server copies. Audio attachments (the music
const ROUTINE_EXTENSIONS := [".json", ".tres"] ## of a routine) live in the same folder and are synced like the routine files.
const SYNC_EXTENSIONS := [
".json",
".tres",
".mp3",
".ogg",
".wav",
]
var progress: String = "" var progress: String = ""
var error: String = "" var error: String = ""
@ -273,19 +280,24 @@ func _save_state(client: FtpClient, state: Dictionary) -> void:
save_state(STATE_PATH, state) save_state(STATE_PATH, state)
static func is_routine_file(name: String) -> bool: static func is_synced_file(name: String) -> bool:
var lower := name.to_lower() var lower := name.to_lower()
for extension: String in ROUTINE_EXTENSIONS: for extension: String in SYNC_EXTENSIONS:
if lower.ends_with(extension): if lower.ends_with(extension):
return true return true
return false return false
## Backwards-compatible name for callers that only think about routine files.
static func is_routine_file(name: String) -> bool:
return is_synced_file(name)
func _remote_files(client: FtpClient) -> Dictionary: func _remote_files(client: FtpClient) -> Dictionary:
var files: Dictionary = {} var files: Dictionary = {}
for entry: Dictionary in client.list_files(): for entry: Dictionary in client.list_files():
var name := str(entry.get("name", "")) var name := str(entry.get("name", ""))
if not is_routine_file(name): if not is_synced_file(name):
continue continue
files[name] = { files[name] = {
"modify": int(entry.get("modify", 0)), "modify": int(entry.get("modify", 0)),
@ -302,7 +314,7 @@ static func local_files(directory: String = LOCAL_DIR) -> Dictionary:
dir.list_dir_begin() dir.list_dir_begin()
var name := dir.get_next() var name := dir.get_next()
while not name.is_empty(): while not name.is_empty():
if not dir.current_is_dir() and is_routine_file(name): if not dir.current_is_dir() and is_synced_file(name):
var path := directory.path_join(name) var path := directory.path_join(name)
files[name] = { files[name] = {
"mtime": FileAccess.get_modified_time(path), "mtime": FileAccess.get_modified_time(path),

View file

@ -18,6 +18,7 @@ enum FileAction {
SAVE, SAVE,
SAVE_AS, SAVE_AS,
EXPORT, EXPORT,
OPEN_EXPORTS,
SYNC_NOW, SYNC_NOW,
SYNC_SETTINGS, SYNC_SETTINGS,
} }
@ -66,6 +67,10 @@ const SYNC_SETTINGS_PATH := "user://sync.cfg"
const AUTOSAVE_DELAY_SECONDS := 1.5 const AUTOSAVE_DELAY_SECONDS := 1.5
const MAX_HISTORY := 50 const MAX_HISTORY := 50
const COMPACT_LAYOUT_WIDTH := 1280.0 const COMPACT_LAYOUT_WIDTH := 1280.0
## Music playback and the routine timeline share one clock. Tiny differences
## are normal (output latency, dropped frames); only larger drift is corrected.
const MUSIC_DRIFT_TOLERANCE_SECONDS := 0.35
const MAX_MUSIC_FILE_BYTES := 64 * 1024 * 1024
## Tests disable these before adding the scene to the tree. ## Tests disable these before adding the scene to the tree.
@export var restore_autosave: bool = true @export var restore_autosave: bool = true
@ -116,6 +121,16 @@ const COMPACT_LAYOUT_WIDTH := 1280.0
@onready var playback_time_label: Label = %PlaybackTimeLabel @onready var playback_time_label: Label = %PlaybackTimeLabel
@onready var playback_timeline: HSlider = %PlaybackTimeline @onready var playback_timeline: HSlider = %PlaybackTimeline
@onready var speed_option: OptionButton = %SpeedOption @onready var speed_option: OptionButton = %SpeedOption
@onready var music_button: Button = %MusicButton
@onready var music_label: Label = %MusicLabel
@onready var music_clear_button: Button = %MusicClearButton
@onready var music_file_dialog: FileDialog = %MusicFileDialog
@onready var music_player: AudioStreamPlayer = %MusicPlayer
@onready var timeline_label_lane: TimelineLabelLane = %TimelineLabelLane
@onready var timeline_label_dialog: ConfirmationDialog = %TimelineLabelDialog
@onready var timeline_label_time_label: Label = %TimelineLabelTimeLabel
@onready var timeline_label_edit: LineEdit = %TimelineLabelEdit
@onready var timeline_label_delete_button: Button = %TimelineLabelDeleteButton
@onready var timing_selection_label: Label = %TimingSelectionLabel @onready var timing_selection_label: Label = %TimingSelectionLabel
@onready var label_button: Button = %LabelButton @onready var label_button: Button = %LabelButton
@onready var labels_toggle: Button = %LabelsToggle @onready var labels_toggle: Button = %LabelsToggle
@ -174,6 +189,12 @@ const COMPACT_LAYOUT_WIDTH := 1280.0
@onready var export_name_edit: LineEdit = %ExportNameEdit @onready var export_name_edit: LineEdit = %ExportNameEdit
@onready var export_format_option: OptionButton = %ExportFormatOption @onready var export_format_option: OptionButton = %ExportFormatOption
@onready var export_scope_option: OptionButton = %ExportScopeOption @onready var export_scope_option: OptionButton = %ExportScopeOption
@onready var export_open_after_check: CheckBox = %ExportOpenAfterCheck
@onready var export_done_dialog: AcceptDialog = %ExportDoneDialog
@onready var export_done_label: RichTextLabel = %ExportDoneLabel
@onready var export_open_button: Button = %ExportOpenButton
@onready var export_folder_button: Button = %ExportFolderButton
@onready var export_copy_path_button: Button = %ExportCopyPathButton
var _routine: Routine var _routine: Routine
var _active_section: RoutineSection var _active_section: RoutineSection
@ -197,6 +218,7 @@ var _show_score_info: bool = false
var _show_score_assumptions: bool = false var _show_score_assumptions: bool = false
var _preset_speed: float = DEFAULT_SPEED_MPS var _preset_speed: float = DEFAULT_SPEED_MPS
var _current_path: String = "" var _current_path: String = ""
var _last_export_path: String = ""
var _dirty: bool = false var _dirty: bool = false
var _pending_action: Callable var _pending_action: Callable
var _undo_stack: Array[HistoryEntry] = [] var _undo_stack: Array[HistoryEntry] = []
@ -213,6 +235,8 @@ var _playback_segment_id: String = ""
var _playback_position: Vector2 = Vector2.ZERO var _playback_position: Vector2 = Vector2.ZERO
var _playback_heading: Vector2 = Vector2.RIGHT var _playback_heading: Vector2 = Vector2.RIGHT
var _updating_timeline: bool = false var _updating_timeline: bool = false
var _timeline_label_edit_index: int = -1
var _pending_timeline_label_time: float = 0.0
var _sync_thread: Thread var _sync_thread: Thread
var _sync_job: RoutineSync var _sync_job: RoutineSync
var _sync_running: bool = false var _sync_running: bool = false
@ -290,6 +314,19 @@ func _ready() -> void:
reset_playback_button.pressed.connect(reset_playback) reset_playback_button.pressed.connect(reset_playback)
playback_timeline.value_changed.connect(_on_timeline_changed) playback_timeline.value_changed.connect(_on_timeline_changed)
speed_option.item_selected.connect(_on_speed_selected) speed_option.item_selected.connect(_on_speed_selected)
music_button.pressed.connect(_open_music_dialog)
music_clear_button.pressed.connect(_clear_music)
music_file_dialog.file_selected.connect(_on_music_file_selected)
timeline_label_lane.add_label_requested.connect(
_on_timeline_label_add_requested
)
timeline_label_lane.edit_label_requested.connect(
_on_timeline_label_edit_requested
)
timeline_label_dialog.confirmed.connect(_on_timeline_label_confirmed)
timeline_label_delete_button.pressed.connect(
_on_timeline_label_delete_pressed
)
duration_minus_button.pressed.connect(_change_selected_duration.bind(-1)) duration_minus_button.pressed.connect(_change_selected_duration.bind(-1))
duration_plus_button.pressed.connect(_change_selected_duration.bind(1)) duration_plus_button.pressed.connect(_change_selected_duration.bind(1))
speed_minus_button.pressed.connect(_change_selected_speed.bind(-1)) speed_minus_button.pressed.connect(_change_selected_speed.bind(-1))
@ -299,6 +336,9 @@ func _ready() -> void:
reset_timing_button.pressed.connect(_reset_selected_timing) reset_timing_button.pressed.connect(_reset_selected_timing)
calibration_dialog.confirmed.connect(_on_calibration_confirmed) calibration_dialog.confirmed.connect(_on_calibration_confirmed)
export_dialog.confirmed.connect(_on_export_confirmed) export_dialog.confirmed.connect(_on_export_confirmed)
export_open_button.pressed.connect(_on_export_open_pressed)
export_folder_button.pressed.connect(_on_export_folder_pressed)
export_copy_path_button.pressed.connect(_on_export_copy_path_pressed)
sync_settings_dialog.confirmed.connect(_on_sync_settings_confirmed) sync_settings_dialog.confirmed.connect(_on_sync_settings_confirmed)
label_button.pressed.connect(_open_label_dialog) label_button.pressed.connect(_open_label_dialog)
labels_toggle.toggled.connect(_on_labels_toggled) labels_toggle.toggled.connect(_on_labels_toggled)
@ -2010,9 +2050,10 @@ func set_active_section(section_id: String) -> void:
if section == null: if section == null:
return return
if _playing or not _playback_section_id.is_empty(): if _playing:
reset_playback() pause()
var start_time := get_section_start_time(section_id)
rink_canvas.cancel_interaction() rink_canvas.cancel_interaction()
_active_section = section _active_section = section
_selected_segment_id = "" _selected_segment_id = ""
@ -2020,6 +2061,28 @@ func set_active_section(section_id: String) -> void:
rink_canvas.set_active_section(section.section_id) rink_canvas.set_active_section(section.section_id)
_update_section_buttons() _update_section_buttons()
_update_status() _update_status()
seek_playback(start_time)
## Start time of [param section_id] on the complete playback timeline. Empty or
## zero-duration segments do not shift the following section.
func get_section_start_time(section_id: String) -> float:
if _routine == null:
return 0.0
var total := 0.0
for section: RoutineSection in _routine.sections:
if section == null:
continue
if section.section_id == section_id:
return total
for segment: PathSegment in section.segments:
if segment != null:
total += maxf(
segment.get_effective_duration_seconds(),
0.0
)
return 0.0
func rename_section(section_id: String, new_title: String) -> bool: func rename_section(section_id: String, new_title: String) -> bool:
@ -2204,6 +2267,8 @@ func _clone_routine(source: Routine) -> Routine:
clone.routine_id = source.routine_id clone.routine_id = source.routine_id
clone.title = source.title clone.title = source.title
clone.skater_name = source.skater_name clone.skater_name = source.skater_name
clone.music_file = source.music_file
clone.timeline_labels.assign(source.timeline_labels.duplicate(true))
clone.adult_category = source.adult_category clone.adult_category = source.adult_category
clone.assumed_pcs_average = source.assumed_pcs_average clone.assumed_pcs_average = source.assumed_pcs_average
clone.assumed_falls = source.assumed_falls clone.assumed_falls = source.assumed_falls
@ -2699,6 +2764,7 @@ func play() -> void:
rink_canvas.set_selected_segment("") rink_canvas.set_selected_segment("")
_playing = true _playing = true
_update_playback_state(0.0, true) _update_playback_state(0.0, true)
_start_music()
_update_play_button() _update_play_button()
_update_playback_ui() _update_playback_ui()
_update_status() _update_status()
@ -2709,6 +2775,7 @@ func pause() -> void:
if not _playing: if not _playing:
return return
_playing = false _playing = false
_stop_music()
_update_play_button() _update_play_button()
_update_playback_ui() _update_playback_ui()
_sync_trail_fade() _sync_trail_fade()
@ -2719,6 +2786,7 @@ func reset_playback() -> void:
_playback_time = 0.0 _playback_time = 0.0
_playback_section_id = "" _playback_section_id = ""
_playback_segment_id = "" _playback_segment_id = ""
_stop_music()
_update_play_button() _update_play_button()
rink_canvas.clear_playback_state() rink_canvas.clear_playback_state()
if _view_3d_active and _presentation_3d != null: if _view_3d_active and _presentation_3d != null:
@ -2733,6 +2801,8 @@ func seek_playback(time: float) -> void:
rink_canvas.clear_playback_state() rink_canvas.clear_playback_state()
else: else:
_update_playback_state(0.0, true) _update_playback_state(0.0, true)
if _playing:
_seek_music(_playback_time)
_update_playback_ui() _update_playback_ui()
_sync_trail_fade() _sync_trail_fade()
@ -2750,6 +2820,7 @@ func advance_playback(delta: float) -> void:
_playback_time = _playback_total_duration _playback_time = _playback_total_duration
_update_playback_state(0.0, true) _update_playback_state(0.0, true)
_playing = false _playing = false
_stop_music()
_update_play_button() _update_play_button()
_update_playback_ui() _update_playback_ui()
_sync_trail_fade() _sync_trail_fade()
@ -2760,6 +2831,7 @@ func advance_playback(delta: float) -> void:
func _process(delta: float) -> void: func _process(delta: float) -> void:
advance_playback(delta) advance_playback(delta)
_sync_music_to_playback()
_poll_sync_thread() _poll_sync_thread()
if _sync_running and _sync_job != null and not _sync_job.progress.is_empty(): if _sync_running and _sync_job != null and not _sync_job.progress.is_empty():
@ -2782,6 +2854,14 @@ func _setup_playback_controls() -> void:
playback_timeline.editable = false playback_timeline.editable = false
play_button.disabled = true play_button.disabled = true
reset_playback_button.disabled = true reset_playback_button.disabled = true
music_file_dialog.filters = PackedStringArray([
"*.mp3 ; MP3-Musik",
"*.ogg ; OGG-Musik",
"*.wav ; WAV-Audio",
])
music_player.pitch_scale = 1.0
timeline_label_edit.max_length = RoutineFile.MAX_TIMELINE_LABEL_LENGTH
_update_music_ui()
_update_play_button() _update_play_button()
@ -2794,6 +2874,11 @@ func _toggle_playback() -> void:
func _on_speed_selected(index: int) -> void: func _on_speed_selected(index: int) -> void:
_playback_speed = float(speed_option.get_item_id(index)) / 100.0 _playback_speed = float(speed_option.get_item_id(index)) / 100.0
# The audio follows the routine clock. Changing the pitch also changes the
# playback rate, so the music stays aligned at every speed.
music_player.pitch_scale = _playback_speed
if _playing and music_player.stream != null:
_seek_music(_playback_time)
func _on_timeline_changed(value: float) -> void: func _on_timeline_changed(value: float) -> void:
@ -2828,10 +2913,12 @@ func _refresh_playback_timeline() -> void:
_playback_entries = entries _playback_entries = entries
_playback_total_duration = total _playback_total_duration = total
_refresh_timeline_labels()
if total <= 0.0: if total <= 0.0:
_playback_time = 0.0 _playback_time = 0.0
_playing = false _playing = false
_stop_music()
_playback_section_id = "" _playback_section_id = ""
_playback_segment_id = "" _playback_segment_id = ""
rink_canvas.clear_playback_state() rink_canvas.clear_playback_state()
@ -2841,6 +2928,7 @@ func _refresh_playback_timeline() -> void:
_playback_time = clampf(_playback_time, 0.0, total) _playback_time = clampf(_playback_time, 0.0, total)
if _playing and _playback_time >= total: if _playing and _playback_time >= total:
_playing = false _playing = false
_stop_music()
_update_play_button() _update_play_button()
_update_playback_ui() _update_playback_ui()
@ -2974,6 +3062,8 @@ func _update_playback_ui() -> void:
) )
_updating_timeline = false _updating_timeline = false
timeline_label_lane.set_playhead(_playback_time)
playback_time_label.text = "%s / %s s" % [ playback_time_label.text = "%s / %s s" % [
_format_seconds(_playback_time), _format_seconds(_playback_time),
_format_seconds(_playback_total_duration), _format_seconds(_playback_total_duration),
@ -2990,6 +3080,404 @@ func _update_play_button() -> void:
play_button.tooltip_text = "Pause" if _playing else "Abspielen" play_button.tooltip_text = "Pause" if _playing else "Abspielen"
## --- Timeline-Labels ------------------------------------------------------
func get_timeline_labels() -> Array[Dictionary]:
var result: Array[Dictionary] = []
if _routine == null:
return result
for entry: Dictionary in _routine.timeline_labels:
result.append(entry.duplicate(true))
return result
func add_timeline_label(time_seconds: float, text: String) -> bool:
if _routine == null:
return false
var cleaned := text.strip_edges().left(RoutineFile.MAX_TIMELINE_LABEL_LENGTH)
if cleaned.is_empty():
return false
if _routine.timeline_labels.size() >= RoutineFile.MAX_TIMELINE_LABELS:
_show_message("Es sind höchstens %d Timeline-Labels möglich." % RoutineFile.MAX_TIMELINE_LABELS)
return false
_record_undo()
_routine.timeline_labels.append({
"time_seconds": clampf(
time_seconds,
0.0,
maxf(_playback_total_duration, 0.0)
),
"text": cleaned,
})
_sort_timeline_labels()
_mark_dirty()
_update_status()
return true
func update_timeline_label(index: int, text: String) -> bool:
if _routine == null or index < 0 or index >= _routine.timeline_labels.size():
return false
var cleaned := text.strip_edges().left(RoutineFile.MAX_TIMELINE_LABEL_LENGTH)
if cleaned.is_empty():
return false
if str(_routine.timeline_labels[index].get("text", "")) == cleaned:
return true
_record_undo()
_routine.timeline_labels[index]["text"] = cleaned
_mark_dirty()
_update_status()
return true
func remove_timeline_label(index: int) -> bool:
if _routine == null or index < 0 or index >= _routine.timeline_labels.size():
return false
_record_undo()
_routine.timeline_labels.remove_at(index)
_mark_dirty()
_update_status()
return true
func _sort_timeline_labels() -> void:
if _routine == null:
return
_routine.timeline_labels.sort_custom(
func(a: Dictionary, b: Dictionary) -> bool:
return (
float(a.get("time_seconds", 0.0))
< float(b.get("time_seconds", 0.0))
)
)
func _refresh_timeline_labels() -> void:
if timeline_label_lane == null:
return
# Walk the authored routine like the playback timeline does. Using the
# segments directly (instead of only the timed playback entries) also
# keeps element markers with zero stand time visible.
var element_labels: Array[Dictionary] = []
var total := 0.0
if _routine != null:
for section: RoutineSection in _routine.sections:
if section == null:
continue
for segment: PathSegment in section.segments:
if segment == null:
continue
var text := segment.label.strip_edges()
if text.is_empty() and segment.is_element():
text = segment.get_element_caption().strip_edges()
if not text.is_empty():
element_labels.append({
"time_seconds": total,
"text": text,
})
total += maxf(
segment.get_effective_duration_seconds(),
0.0
)
var custom_labels: Array[Dictionary] = []
if _routine != null:
for entry: Dictionary in _routine.timeline_labels:
var text := str(entry.get("text", "")).strip_edges()
if text.is_empty():
continue
custom_labels.append({
"time_seconds": float(entry.get("time_seconds", 0.0)),
"text": text,
})
timeline_label_lane.set_timeline(
element_labels,
custom_labels,
_playback_total_duration
)
func _on_timeline_label_add_requested(time_seconds: float) -> void:
if _routine == null or _playback_total_duration <= 0.0:
return
_timeline_label_edit_index = -1
_pending_timeline_label_time = clampf(
time_seconds,
0.0,
_playback_total_duration
)
timeline_label_dialog.title = "Timeline-Label hinzufügen"
timeline_label_time_label.text = "Zeitpunkt: %s s" % _format_seconds(
_pending_timeline_label_time
)
timeline_label_edit.text = ""
timeline_label_delete_button.visible = false
timeline_label_dialog.popup_centered(Vector2i(480, 250))
timeline_label_edit.grab_focus()
func _on_timeline_label_edit_requested(index: int) -> void:
if _routine == null or index < 0 or index >= _routine.timeline_labels.size():
return
var entry: Dictionary = _routine.timeline_labels[index]
_timeline_label_edit_index = index
_pending_timeline_label_time = float(entry.get("time_seconds", 0.0))
timeline_label_dialog.title = "Timeline-Label bearbeiten"
timeline_label_time_label.text = "Zeitpunkt: %s s" % _format_seconds(
_pending_timeline_label_time
)
timeline_label_edit.text = str(entry.get("text", ""))
timeline_label_delete_button.visible = true
timeline_label_dialog.popup_centered(Vector2i(480, 250))
timeline_label_edit.grab_focus()
timeline_label_edit.select_all()
func _on_timeline_label_confirmed() -> void:
var changed := false
if _timeline_label_edit_index >= 0:
changed = update_timeline_label(
_timeline_label_edit_index,
timeline_label_edit.text
)
else:
changed = add_timeline_label(
_pending_timeline_label_time,
timeline_label_edit.text
)
if not changed:
_show_message("Bitte eine Beschriftung eingeben.")
_timeline_label_edit_index = -1
func _on_timeline_label_delete_pressed() -> void:
if _timeline_label_edit_index >= 0:
remove_timeline_label(_timeline_label_edit_index)
_timeline_label_edit_index = -1
timeline_label_dialog.hide()
## --- Musik ----------------------------------------------------------------
func get_music_file_name() -> String:
return _routine.music_file if _routine != null else ""
func has_music_stream() -> bool:
return music_player.stream != null
func _open_music_dialog() -> void:
if _routine == null:
return
music_file_dialog.popup_centered(Vector2i(780, 560))
func _on_music_file_selected(path: String) -> void:
load_music_from_path(path)
## Copies the selected track into the routines folder and references it from
## the routine. Keeping the file next to the JSON makes it part of the sync.
func load_music_from_path(path: String) -> bool:
if _routine == null:
return false
var source := path.strip_edges()
if not RoutineFile.is_audio_file(source):
_show_message("Bitte eine MP3-, OGG- oder WAV-Datei auswählen.")
return false
var absolute_source := ProjectSettings.globalize_path(source)
if not FileAccess.file_exists(absolute_source):
_show_message("Die Musikdatei wurde nicht gefunden:\n%s" % source)
return false
var file := FileAccess.open(absolute_source, FileAccess.READ)
if file == null:
_show_message("Die Musikdatei ist nicht lesbar:\n%s" % source)
return false
var size := file.get_length()
file.close()
if size <= 0:
_show_message("Die Musikdatei ist leer:\n%s" % source)
return false
if size > MAX_MUSIC_FILE_BYTES:
_show_message("Die Musikdatei ist zu groß (max. 64 MB).")
return false
_ensure_routines_dir()
var file_name := RoutineFile.safe_music_file_name(source.get_file())
if file_name.is_empty():
_show_message("Der Dateiname der Musikdatei ist ungültig.")
return false
var routines_absolute := ProjectSettings.globalize_path(ROUTINES_DIR)
if absolute_source.get_base_dir() != routines_absolute:
file_name = _unique_music_file_name(file_name)
var target := ProjectSettings.globalize_path(ROUTINES_DIR.path_join(file_name))
var copy_error := DirAccess.copy_absolute(absolute_source, target)
if copy_error != OK:
_show_message(
"Die Musikdatei konnte nicht kopiert werden (Fehler %d)."
% copy_error
)
return false
_routine.music_file = file_name
_load_music_stream()
_mark_dirty()
_update_music_ui()
if _playing:
_start_music()
return true
func _clear_music() -> void:
if _routine == null or not _routine.has_music():
return
_stop_music()
music_player.stream = null
_routine.music_file = ""
_mark_dirty()
_update_music_ui()
func _unique_music_file_name(file_name: String) -> String:
if not FileAccess.file_exists(ROUTINES_DIR.path_join(file_name)):
return file_name
var base := file_name.get_basename()
var extension := "." + file_name.get_extension()
var index := 2
while true:
var candidate := "%s %d%s" % [base, index, extension]
if not FileAccess.file_exists(ROUTINES_DIR.path_join(candidate)):
return candidate
index += 1
return file_name
func _load_music_stream() -> bool:
_stop_music()
music_player.stream = null
if _routine == null or not _routine.has_music():
return false
var path := ROUTINES_DIR.path_join(_routine.music_file)
if not FileAccess.file_exists(path):
return false
var stream := _read_audio_stream(path)
if stream == null:
return false
music_player.stream = stream
music_player.pitch_scale = _playback_speed
return true
func _read_audio_stream(path: String) -> AudioStream:
match path.get_extension().to_lower():
"mp3":
var file := FileAccess.open(path, FileAccess.READ)
if file == null:
return null
var data := file.get_buffer(file.get_length())
file.close()
var stream := AudioStreamMP3.new()
stream.data = data
return stream
"ogg":
return AudioStreamOggVorbis.load_from_file(path)
"wav":
return AudioStreamWAV.load_from_file(path)
return null
func _start_music() -> void:
if music_player.stream == null:
return
music_player.pitch_scale = _playback_speed
var length := music_player.stream.get_length()
if length > 0.0 and _playback_time >= length:
music_player.stop()
return
music_player.play(_playback_time)
func _stop_music() -> void:
if music_player != null:
music_player.stop()
func _seek_music(time: float) -> void:
if music_player.stream == null:
return
var length := music_player.stream.get_length()
var target := time
if length > 0.0:
if target >= length:
music_player.stop()
return
target = clampf(target, 0.0, length)
if not music_player.playing:
music_player.play(target)
return
music_player.seek(target)
## The timeline is authoritative. Correct only larger drift, e.g. after a long
## frame hitch, so normal playback never stutters from tiny offsets.
func _sync_music_to_playback() -> void:
if (
not _playing
or music_player.stream == null
or not music_player.playing
):
return
var length := music_player.stream.get_length()
if length <= 0.0:
return
var mixed := (
music_player.get_playback_position()
+ AudioServer.get_time_since_last_mix()
- AudioServer.get_output_latency()
)
var actual := clampf(mixed, 0.0, length)
var expected := clampf(_playback_time, 0.0, length)
if absf(actual - expected) > MUSIC_DRIFT_TOLERANCE_SECONDS:
music_player.seek(expected)
func _update_music_ui() -> void:
if music_label == null:
return
var file_name := get_music_file_name()
music_clear_button.disabled = file_name.is_empty()
music_button.disabled = _routine == null
if file_name.is_empty():
music_label.text = "Keine Musik"
music_label.tooltip_text = "MP3-Musik für diese Kür laden"
return
var path := ROUTINES_DIR.path_join(file_name)
if FileAccess.file_exists(path):
music_label.text = "♪ " + file_name
music_label.tooltip_text = "Musik: %s\n%s" % [file_name, path]
else:
music_label.text = "♪ " + file_name + " (fehlt)"
music_label.tooltip_text = (
"Musikdatei fehlt in %s. Beim nächsten Sync wird sie geladen."
% ROUTINES_DIR
)
## --- 3D-Vorschau ----------------------------------------------------------- ## --- 3D-Vorschau -----------------------------------------------------------
@ -3389,6 +3877,7 @@ func _setup_file_menu() -> void:
popup.add_item("Speichern unter…", FileAction.SAVE_AS) popup.add_item("Speichern unter…", FileAction.SAVE_AS)
popup.add_separator() popup.add_separator()
popup.add_item("Exportieren…", FileAction.EXPORT) popup.add_item("Exportieren…", FileAction.EXPORT)
popup.add_item("Exportordner öffnen", FileAction.OPEN_EXPORTS)
popup.add_separator() popup.add_separator()
popup.add_item("Jetzt synchronisieren", FileAction.SYNC_NOW) popup.add_item("Jetzt synchronisieren", FileAction.SYNC_NOW)
popup.add_item("Sync-Einstellungen…", FileAction.SYNC_SETTINGS) popup.add_item("Sync-Einstellungen…", FileAction.SYNC_SETTINGS)
@ -3407,6 +3896,8 @@ func _on_file_menu_pressed(action: int) -> void:
_open_save_as_dialog() _open_save_as_dialog()
FileAction.EXPORT: FileAction.EXPORT:
_open_export_dialog() _open_export_dialog()
FileAction.OPEN_EXPORTS:
_open_exports_folder()
FileAction.SYNC_NOW: FileAction.SYNC_NOW:
start_sync() start_sync()
FileAction.SYNC_SETTINGS: FileAction.SYNC_SETTINGS:
@ -3441,6 +3932,8 @@ func _install_routine(
_playback_time = 0.0 _playback_time = 0.0
_playback_section_id = "" _playback_section_id = ""
_playback_segment_id = "" _playback_segment_id = ""
_stop_music()
music_player.stream = null
rink_canvas.clear_playback_state() rink_canvas.clear_playback_state()
rink_canvas.cancel_interaction() rink_canvas.cancel_interaction()
@ -3461,6 +3954,8 @@ func _install_routine(
valid_sections.append(section) valid_sections.append(section)
_routine.sections = valid_sections _routine.sections = valid_sections
_migrate_routine(_routine) _migrate_routine(_routine)
_load_music_stream()
_update_music_ui()
if _routine.sections.is_empty(): if _routine.sections.is_empty():
var fallback := RoutineSection.new() var fallback := RoutineSection.new()
@ -3491,6 +3986,9 @@ func _migrate_routine(routine: Routine) -> void:
if routine.schema_version >= Routine.CURRENT_SCHEMA_VERSION: if routine.schema_version >= Routine.CURRENT_SCHEMA_VERSION:
return return
# Schema 1 stored only a duration per segment. Later schemas already use
# speed/timing_mode, so only migrate the old shape.
if routine.schema_version < 2:
for section: RoutineSection in routine.sections: for section: RoutineSection in routine.sections:
if section == null: if section == null:
continue continue
@ -3734,6 +4232,7 @@ func _setup_export_controls() -> void:
export_format_option.clear() export_format_option.clear()
export_format_option.add_item("SVG (Vektor)", 0) export_format_option.add_item("SVG (Vektor)", 0)
export_format_option.add_item("PNG (hochauflösend)", 1) export_format_option.add_item("PNG (hochauflösend)", 1)
export_format_option.add_item("PDF (Laufwege mit Zeit)", 2)
export_scope_option.clear() export_scope_option.clear()
export_scope_option.add_item("Gesamte Kür", 0) export_scope_option.add_item("Gesamte Kür", 0)
export_scope_option.add_item("Aktiver Abschnitt", 1) export_scope_option.add_item("Aktiver Abschnitt", 1)
@ -3779,6 +4278,9 @@ func _apply_responsive_layout() -> void:
calibrate_button.custom_minimum_size.x = 80.0 if compact else 100.0 calibrate_button.custom_minimum_size.x = 80.0 if compact else 100.0
timing_selection_label.custom_minimum_size.x = 120.0 if compact else 170.0 timing_selection_label.custom_minimum_size.x = 120.0 if compact else 170.0
profile_option.custom_minimum_size.x = 120.0 if compact else 140.0 profile_option.custom_minimum_size.x = 120.0 if compact else 140.0
music_button.text = "♪" if compact else "Musik…"
music_button.custom_minimum_size.x = 56.0 if compact else 96.0
music_label.visible = not compact
func load_sync_settings() -> Dictionary: func load_sync_settings() -> Dictionary:
@ -3927,14 +4429,17 @@ func _format_sync_summary(result: Dictionary) -> String:
func _reload_after_sync(result: Dictionary) -> void: func _reload_after_sync(result: Dictionary) -> void:
if _current_path.is_empty(): if _current_path.is_empty():
_refresh_synced_music(result)
return return
var current_name := _current_path.get_file() var current_name := _current_path.get_file()
var downloaded: Array = result.get("downloaded", []) var downloaded: Array = result.get("downloaded", [])
var adopted: Array = result.get("adopted", []) var adopted: Array = result.get("adopted", [])
if not downloaded.has(current_name) and not adopted.has(current_name): if not downloaded.has(current_name) and not adopted.has(current_name):
_refresh_synced_music(result)
return return
if is_dirty(): if is_dirty():
_refresh_synced_music(result)
_show_message( _show_message(
"Die geöffnete Kür wurde vom Server aktualisiert, hat aber " "Die geöffnete Kür wurde vom Server aktualisiert, hat aber "
+ "ungespeicherte Änderungen. Bitte manuell speichern oder neu laden." + "ungespeicherte Änderungen. Bitte manuell speichern oder neu laden."
@ -3943,6 +4448,22 @@ func _reload_after_sync(result: Dictionary) -> void:
load_from_path(_current_path) load_from_path(_current_path)
## Picks up a music file that arrived by sync while its routine is already
## open. Without this the player would keep the old stream until a reload.
func _refresh_synced_music(result: Dictionary) -> void:
if _routine == null or not _routine.has_music():
return
var music_name := _routine.music_file
var downloaded: Array = result.get("downloaded", [])
var adopted: Array = result.get("adopted", [])
if not downloaded.has(music_name) and not adopted.has(music_name):
return
_load_music_stream()
_update_music_ui()
if _playing:
_start_music()
func _exit_tree() -> void: func _exit_tree() -> void:
if _sync_thread != null: if _sync_thread != null:
_sync_thread.wait_to_finish() _sync_thread.wait_to_finish()
@ -3958,11 +4479,27 @@ func _open_export_dialog() -> void:
export_name_edit.text = "kuer" export_name_edit.text = "kuer"
export_format_option.select(0) export_format_option.select(0)
export_scope_option.select(0) export_scope_option.select(0)
export_dialog.popup_centered(Vector2i(480, 360)) var dialog_size := _fit_dialog_size(Vector2i(480, 520))
export_dialog.popup_centered(dialog_size)
# AcceptDialog shrinks to its content minimum on popup; restore the target
# size so the scroll area has room. popup_centered already centered it for
# the requested size.
export_dialog.size = dialog_size
export_name_edit.grab_focus() export_name_edit.grab_focus()
export_name_edit.select_all() export_name_edit.select_all()
## Keeps dialogs inside the visible viewport (important on Android portrait).
func _fit_dialog_size(preferred: Vector2i) -> Vector2i:
var viewport := get_viewport_rect().size
if viewport.x <= 0.0 or viewport.y <= 0.0:
return preferred
return Vector2i(
mini(preferred.x, int(viewport.x * 0.92)),
mini(preferred.y, int(viewport.y * 0.88))
)
func _on_export_confirmed() -> void: func _on_export_confirmed() -> void:
var name := export_name_edit.text.strip_edges() var name := export_name_edit.text.strip_edges()
if name.is_empty(): if name.is_empty():
@ -3979,37 +4516,100 @@ func _on_export_confirmed() -> void:
scope_section_id = _active_section.section_id scope_section_id = _active_section.section_id
scope_suffix = "_" + _normalize_file_stem(_active_section.title) scope_suffix = "_" + _normalize_file_stem(_active_section.title)
var is_svg := export_format_option.selected == 0 var format := export_format_option.get_item_id(
var extension := "svg" if is_svg else "png" export_format_option.selected
)
var extension := "svg"
if format == 1:
extension = "png"
elif format == 2:
extension = "pdf"
var path := EXPORTS_DIR.path_join(stem + scope_suffix + "." + extension) var path := EXPORTS_DIR.path_join(stem + scope_suffix + "." + extension)
if FileAccess.file_exists(path): if FileAccess.file_exists(path):
_confirm_overwrite( _confirm_overwrite(
path, path,
_perform_export.bind(path, is_svg, scope_section_id) _perform_export.bind(path, format, scope_section_id)
) )
return return
await _perform_export(path, is_svg, scope_section_id) await _perform_export(path, format, scope_section_id)
func _perform_export( func _perform_export(
path: String, path: String,
is_svg: bool, format: int,
scope_section_id: String scope_section_id: String
) -> void: ) -> void:
_ensure_exports_dir() _ensure_exports_dir()
var success := false var success := false
if is_svg: match format:
0:
success = export_svg_to_path(path, scope_section_id) success = export_svg_to_path(path, scope_section_id)
else: 1:
success = await export_png_to_path(path, scope_section_id) success = await export_png_to_path(path, scope_section_id)
2:
success = export_pdf_to_path(path, scope_section_id)
if success: if success:
_show_message("Exportiert nach:\n%s" % path) _last_export_path = ProjectSettings.globalize_path(path)
_show_export_done()
if export_open_after_check.button_pressed:
_open_path_externally(_last_export_path)
else: else:
_show_message("Export fehlgeschlagen.") _show_message("Export fehlgeschlagen.")
func _show_export_done() -> void:
export_done_label.text = (
"Exportiert nach:\n%s\n\n"
+ "Du kannst die Datei direkt öffnen oder den Ordner anzeigen."
) % _last_export_path
export_open_button.disabled = not FileAccess.file_exists(_last_export_path)
export_folder_button.disabled = _last_export_path.is_empty()
export_copy_path_button.text = "Pfad kopieren"
var dialog_size := _fit_dialog_size(Vector2i(660, 320))
export_done_dialog.popup_centered(dialog_size)
export_done_dialog.size = dialog_size
func _open_path_externally(path: String) -> Error:
if path.is_empty() or not FileAccess.file_exists(path):
return ERR_FILE_NOT_FOUND
return OS.shell_open(path)
func _on_export_open_pressed() -> void:
var error := _open_path_externally(_last_export_path)
if error != OK:
_show_message(
"Datei konnte nicht geöffnet werden (Fehler %d).\n\n%s"
% [error, _last_export_path]
)
func _on_export_folder_pressed() -> void:
if _last_export_path.is_empty():
return
var folder := _last_export_path.get_base_dir()
var error := OS.shell_show_in_file_manager(_last_export_path)
if error != OK:
error = OS.shell_show_in_file_manager(folder)
if error != OK:
error = OS.shell_open(folder)
if error != OK:
_show_message(
"Ordner konnte nicht geöffnet werden (Fehler %d).\n\n%s"
% [error, folder]
)
func _on_export_copy_path_pressed() -> void:
if _last_export_path.is_empty():
return
DisplayServer.clipboard_set(_last_export_path)
export_copy_path_button.text = "Kopiert"
func export_svg_to_path(path: String, section_id: String = "") -> bool: func export_svg_to_path(path: String, section_id: String = "") -> bool:
if _routine == null: if _routine == null:
return false return false
@ -4025,6 +4625,21 @@ func export_svg_to_path(path: String, section_id: String = "") -> bool:
return true return true
func export_pdf_to_path(path: String, section_id: String = "") -> bool:
if _routine == null:
return false
var pdf := RoutinePdfExporter.build(_routine, section_id)
if pdf.is_empty():
return false
var file := FileAccess.open(path, FileAccess.WRITE)
if file == null:
return false
file.store_buffer(pdf)
file.close()
return true
func export_png_to_path(path: String, section_id: String = "") -> bool: func export_png_to_path(path: String, section_id: String = "") -> bool:
if _routine == null: if _routine == null:
return false return false
@ -4057,6 +4672,19 @@ func _ensure_exports_dir() -> void:
DirAccess.make_dir_recursive_absolute(EXPORTS_DIR) DirAccess.make_dir_recursive_absolute(EXPORTS_DIR)
func _open_exports_folder() -> void:
_ensure_exports_dir()
var folder := ProjectSettings.globalize_path(EXPORTS_DIR)
var error := OS.shell_show_in_file_manager(folder)
if error != OK:
error = OS.shell_open(folder)
if error != OK:
_show_message(
"Exportordner konnte nicht geöffnet werden (Fehler %d).\n\n%s"
% [error, folder]
)
func _open_open_dialog() -> void: func _open_open_dialog() -> void:
_refresh_open_list() _refresh_open_list()
open_dialog.popup_centered(Vector2i(520, 460)) open_dialog.popup_centered(Vector2i(520, 460))

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,282 @@
class_name TimelineLabelLane
extends Control
## Slanted label strip above the playback slider. Element labels from the
## routine are shown read-only; a click on empty space creates a custom label,
## a click on a custom label opens it for editing.
signal add_label_requested(time_seconds: float)
signal edit_label_requested(index: int)
const SIDE_INSET := 10.0
const ROTATION := -0.32
const FONT_SIZE := 11
const MAX_DISPLAY_CHARS := 20
const ROW_HEIGHT := 16.0
const ELEMENT_COLOR := Color(0.65, 0.78, 0.92, 0.95)
const CUSTOM_COLOR := Color(0.98, 0.76, 0.32, 1.0)
const CUSTOM_HOVER_COLOR := Color(1.0, 0.9, 0.55, 1.0)
const PLAYHEAD_COLOR := Color(1.0, 1.0, 1.0, 0.28)
const BASELINE_COLOR := Color(1.0, 1.0, 1.0, 0.08)
var _duration: float = 0.0
var _playback_time: float = 0.0
var _element_labels: Array[Dictionary] = []
var _custom_labels: Array[Dictionary] = []
var _items: Array[Dictionary] = []
var _hover_index: int = -1
func _ready() -> void:
mouse_filter = Control.MOUSE_FILTER_STOP
clip_contents = true
mouse_default_cursor_shape = Control.CURSOR_ARROW
tooltip_text = (
"Klick: Timeline-Label hinzufügen · "
+ "Klick auf ein goldenes Label: bearbeiten"
)
resized.connect(_rebuild_items)
_rebuild_items()
func set_timeline(
element_labels: Array[Dictionary],
custom_labels: Array[Dictionary],
duration: float
) -> void:
_element_labels.clear()
_element_labels.assign(element_labels)
_custom_labels.clear()
_custom_labels.assign(custom_labels)
_duration = maxf(duration, 0.0)
_rebuild_items()
func set_playhead(time_seconds: float) -> void:
var clamped := maxf(time_seconds, 0.0)
if is_equal_approx(clamped, _playback_time):
return
_playback_time = clamped
queue_redraw()
func get_element_label_count() -> int:
return _element_labels.size()
func get_custom_label_count() -> int:
return _custom_labels.size()
## Exposed for tests: the resolved draw items with time, text and row.
func get_display_items() -> Array[Dictionary]:
var result: Array[Dictionary] = []
for item: Dictionary in _items:
result.append(item.duplicate(true))
return result
func _rebuild_items() -> void:
_items.clear()
if _duration <= 0.0:
queue_redraw()
return
var font := ThemeDB.fallback_font
for index: int in range(_custom_labels.size()):
var entry: Dictionary = _custom_labels[index]
var text := str(entry.get("text", "")).strip_edges()
if text.is_empty():
continue
_append_item(
float(entry.get("time_seconds", 0.0)),
text,
index,
true,
font
)
for entry: Dictionary in _element_labels:
var text := str(entry.get("text", "")).strip_edges()
if text.is_empty():
continue
_append_item(
float(entry.get("time_seconds", 0.0)),
text,
-1,
false,
font
)
_items.sort_custom(
func(a: Dictionary, b: Dictionary) -> bool:
return float(a["time_seconds"]) < float(b["time_seconds"])
)
# Two staggered rows keep nearby labels readable. A third overlapping
# label falls back to the first row instead of disappearing.
var row_right := [-100000.0, -100000.0]
for item: Dictionary in _items:
var x := float(item["x"])
var width := float(item["width"])
var row := 0
if x < float(row_right[0]) + 4.0:
row = 1
if row == 1 and x < float(row_right[1]) + 4.0:
row = 0
row_right[row] = maxf(float(row_right[row]), x + width)
item["row"] = row
queue_redraw()
func _append_item(
time_seconds: float,
text: String,
custom_index: int,
is_custom: bool,
font: Font
) -> void:
var x := _time_to_x(time_seconds)
var display := _display_text(text)
var width := minf(
font.get_string_size(
display,
HORIZONTAL_ALIGNMENT_LEFT,
-1,
FONT_SIZE
).x * 0.9,
180.0
)
_items.append({
"time_seconds": time_seconds,
"text": text,
"display": display,
"x": x,
"width": width,
"row": 0,
"custom": is_custom,
"index": custom_index,
})
func _draw() -> void:
var font := ThemeDB.fallback_font
draw_line(
Vector2(0.0, size.y - 1.0),
Vector2(size.x, size.y - 1.0),
BASELINE_COLOR,
1.0
)
if _duration > 0.0:
var playhead_x := _time_to_x(_playback_time)
draw_line(
Vector2(playhead_x, size.y - 1.0),
Vector2(playhead_x, 2.0),
PLAYHEAD_COLOR,
1.0
)
for item: Dictionary in _items:
var is_custom := bool(item["custom"])
var color := CUSTOM_COLOR if is_custom else ELEMENT_COLOR
if is_custom and int(item["index"]) == _hover_index:
color = CUSTOM_HOVER_COLOR
var x := float(item["x"])
var row := int(item["row"])
var baseline := size.y - 5.0 - float(row) * ROW_HEIGHT
draw_line(
Vector2(x, size.y - 1.0),
Vector2(x, size.y - 6.0),
color,
1.5
)
draw_set_transform(
Vector2(x + 2.0, baseline),
ROTATION,
Vector2.ONE
)
draw_string(
font,
Vector2.ZERO,
str(item["display"]),
HORIZONTAL_ALIGNMENT_LEFT,
-1,
FONT_SIZE,
color
)
draw_set_transform(Vector2.ZERO, 0.0, Vector2.ONE)
func _gui_input(event: InputEvent) -> void:
if event is InputEventMouseMotion:
var hovered := _custom_index_at(event.position.x)
if hovered != _hover_index:
_hover_index = hovered
mouse_default_cursor_shape = (
Control.CURSOR_POINTING_HAND
if hovered >= 0
else Control.CURSOR_ARROW
)
queue_redraw()
return
if not (event is InputEventMouseButton) or not event.pressed:
return
var mouse := event as InputEventMouseButton
var hit := _custom_index_at(mouse.position.x)
if mouse.button_index == MOUSE_BUTTON_LEFT:
if hit >= 0:
edit_label_requested.emit(hit)
elif _duration > 0.0:
add_label_requested.emit(_time_at_x(mouse.position.x))
accept_event()
elif mouse.button_index == MOUSE_BUTTON_RIGHT and hit >= 0:
edit_label_requested.emit(hit)
accept_event()
func _notification(what: int) -> void:
if what == NOTIFICATION_MOUSE_EXIT and _hover_index >= 0:
_hover_index = -1
mouse_default_cursor_shape = Control.CURSOR_ARROW
queue_redraw()
func _custom_index_at(x: float) -> int:
var best_index := -1
var best_distance := 100000.0
for item: Dictionary in _items:
if not bool(item["custom"]):
continue
var start := float(item["x"])
var end := start + float(item["width"])
if x < start - 4.0 or x > end:
continue
var distance := absf(x - start)
if distance < best_distance:
best_distance = distance
best_index = int(item["index"])
return best_index
func _time_to_x(time_seconds: float) -> float:
if _duration <= 0.0:
return SIDE_INSET
var usable := maxf(size.x - SIDE_INSET * 2.0, 1.0)
var fraction := clampf(time_seconds / _duration, 0.0, 1.0)
return SIDE_INSET + fraction * usable
func _time_at_x(x: float) -> float:
var usable := maxf(size.x - SIDE_INSET * 2.0, 1.0)
var fraction := clampf((x - SIDE_INSET) / usable, 0.0, 1.0)
return fraction * _duration
func _display_text(text: String) -> String:
var cleaned := text.strip_edges().replace("\n", " ")
if cleaned.length() <= MAX_DISPLAY_CHARS:
return cleaned
return cleaned.left(MAX_DISPLAY_CHARS - 1) + "…"

View file

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

View file

@ -102,6 +102,81 @@ func _run() -> void:
"the second section excludes the spin of section one" "the second section excludes the spin of section one"
) )
var pdf := RoutinePdfExporter.build(routine)
var pdf_text := pdf.get_string_from_ascii()
_check(pdf.size() > 1000, "PDF export produces data")
_check(
pdf_text.begins_with("%PDF-1.4"),
"PDF export has a PDF header"
)
_check(
pdf_text.contains("/Type /Catalog") and pdf_text.contains("/Type /Pages"),
"PDF export has catalog and page tree"
)
_check(
_count(pdf_text, "/Type /Page ") == 3,
"PDF export contains overview and two section pages"
)
_check(
pdf_text.contains("/Count 3"),
"PDF page tree counts all pages"
)
_check(
pdf_text.contains("/BaseFont /Helvetica")
and pdf_text.contains("/Encoding /WinAnsiEncoding"),
"PDF export embeds the built-in fonts with WinAnsi"
)
_check(
pdf_text.contains("Test & <K\\374r>"),
"PDF export encodes umlauts as WinAnsi escapes"
)
_check(
pdf_text.contains(" c") or pdf_text.contains(" l"),
"PDF export contains vector path operators"
)
_check(
pdf_text.contains("Start") and pdf_text.contains("Ziel"),
"PDF overview marks start and finish"
)
_check(
pdf_text.contains("Timeline-Labels")
and pdf_text.contains("Musikstart"),
"PDF overview lists custom timeline labels"
)
var section_pdf := RoutinePdfExporter.build(routine, "section-1")
var section_pdf_text := section_pdf.get_string_from_ascii()
_check(
_count(section_pdf_text, "/Type /Page ") == 1,
"PDF section export writes a single page"
)
_check(
section_pdf_text.contains("/Count 1"),
"PDF section export page tree counts one page"
)
var long_routine := _make_routine()
var long_section := RoutineSection.new()
long_section.section_id = "section-long"
long_section.title = "Langer Abschnitt"
long_section.sequence_order = 2
for index: int in range(30):
long_section.segments.append(
_make_segment(
"seg-long-%d" % index,
Vector2(-20.0 + float(index) * 0.5, -10.0),
Vector2(-19.5 + float(index) * 0.5, -10.0),
PathSegment.Direction.FORWARD,
PathSegment.Edge.OUTSIDE
)
)
long_routine.sections.append(long_section)
var long_pdf := RoutinePdfExporter.build(long_routine, "section-long")
_check(
_count(long_pdf.get_string_from_ascii(), "/Type /Page ") == 2,
"long PDF section continues on a second page"
)
var scene := WhiteboardScene.instantiate() var scene := WhiteboardScene.instantiate()
var controller := scene as WhiteboardController var controller := scene as WhiteboardController
if controller != null: if controller != null:
@ -115,6 +190,49 @@ func _run() -> void:
_finish() _finish()
return return
_check(
controller.export_format_option.item_count == 3
and controller.export_format_option.get_item_text(2).contains("PDF"),
"export dialog offers the PDF format"
)
_check(
controller.export_open_after_check.button_pressed,
"export dialog opens the result by default"
)
# Small viewport: the dialog must stay inside the screen and keep its
# confirm button reachable, with the form scrolling instead.
get_root().size = Vector2i(800, 400)
await process_frame
controller._open_export_dialog()
await process_frame
var export_dialog := controller.export_dialog
var scroll := export_dialog.get_node("ExportScroll") as ScrollContainer
var ok_button := export_dialog.get_ok_button()
_check(
export_dialog.size.y <= 400,
"export dialog fits a short viewport"
)
_check(
ok_button.global_position.y + ok_button.size.y
<= export_dialog.position.y + export_dialog.size.y,
"export dialog confirm button stays reachable"
)
_check(
scroll.get_v_scroll_bar().visible,
"export dialog form scrolls on a short viewport"
)
export_dialog.hide()
get_root().size = Vector2i(1440, 900)
await process_frame
var file_popup := controller.file_menu_button.get_popup()
var has_export_folder := false
for index: int in range(file_popup.item_count):
if file_popup.get_item_text(index).contains("Exportordner"):
has_export_folder = true
_check(has_export_folder, "file menu offers the exports folder")
controller.add_segment( controller.add_segment(
Vector2(-10.0, 0.0), Vector2(-10.0, 0.0),
Vector2(0.0, 0.0), Vector2(0.0, 0.0),
@ -134,6 +252,46 @@ func _run() -> void:
_check(content.contains("<svg "), "exported SVG file has SVG content") _check(content.contains("<svg "), "exported SVG file has SVG content")
DirAccess.remove_absolute(export_path) DirAccess.remove_absolute(export_path)
var pdf_path := "user://test_export.pdf"
_check(
controller.export_pdf_to_path(pdf_path),
"controller writes a PDF file"
)
_check(FileAccess.file_exists(pdf_path), "exported PDF exists on disk")
if FileAccess.file_exists(pdf_path):
var file := FileAccess.open(pdf_path, FileAccess.READ)
var bytes := file.get_buffer(file.get_length())
file.close()
_check(
bytes.get_string_from_ascii().begins_with("%PDF-1.4"),
"exported PDF file has PDF content"
)
controller._last_export_path = ProjectSettings.globalize_path(pdf_path)
controller._show_export_done()
_check(
controller.export_done_dialog.visible,
"export completion dialog opens"
)
_check(
controller.export_done_label.text.contains(
ProjectSettings.globalize_path(pdf_path)
),
"export completion dialog shows the absolute path"
)
_check(
not controller.export_open_button.disabled
and not controller.export_folder_button.disabled,
"export completion dialog enables open and folder buttons"
)
controller.export_done_dialog.hide()
DirAccess.remove_absolute(pdf_path)
_check(
controller._open_path_externally("user://missing_export.pdf")
== ERR_FILE_NOT_FOUND,
"missing export files are not passed to the shell"
)
scene.queue_free() scene.queue_free()
await process_frame await process_frame
_finish() _finish()
@ -143,6 +301,9 @@ func _make_routine() -> Routine:
var routine := Routine.new() var routine := Routine.new()
routine.routine_id = "export-test" routine.routine_id = "export-test"
routine.title = "Test & <Kür>" routine.title = "Test & <Kür>"
routine.timeline_labels = [
{"time_seconds": 2.5, "text": "Musikstart"},
]
routine.rink = RinkDimensions.new() routine.rink = RinkDimensions.new()
var section_one := RoutineSection.new() var section_one := RoutineSection.new()

View file

@ -51,6 +51,22 @@ func _test_json_roundtrip() -> void:
_check(loaded.routine_id == routine.routine_id, "routine id survives") _check(loaded.routine_id == routine.routine_id, "routine id survives")
_check(loaded.title == routine.title, "title survives") _check(loaded.title == routine.title, "title survives")
_check(loaded.skater_name == routine.skater_name, "skater name survives") _check(loaded.skater_name == routine.skater_name, "skater name survives")
_check(loaded.music_file == routine.music_file, "music file survives")
_check(loaded.timeline_labels.size() == 2, "timeline labels survive")
if loaded.timeline_labels.size() == 2:
_check(
loaded.timeline_labels[0]["text"] == "Dreh",
"timeline labels are sorted by time"
)
_check_approx(
float(loaded.timeline_labels[0]["time_seconds"]),
1.25,
"timeline label time survives"
)
_check(
loaded.timeline_labels[1]["text"] == "Finale",
"second timeline label survives"
)
_check(loaded.adult_category == routine.adult_category, "category survives") _check(loaded.adult_category == routine.adult_category, "category survives")
_check_approx( _check_approx(
loaded.assumed_pcs_average, loaded.assumed_pcs_average,
@ -149,6 +165,56 @@ func _test_json_rejects() -> void:
"paths without extension get .json" "paths without extension get .json"
) )
_check(
RoutineFile.safe_music_file_name("kür.mp3") == "kür.mp3",
"plain music file names are accepted"
)
_check(
RoutineFile.safe_music_file_name("../song.mp3").is_empty(),
"music paths with traversal are rejected"
)
_check(
RoutineFile.safe_music_file_name("/tmp/song.mp3").is_empty(),
"absolute music paths are rejected"
)
_check(
RoutineFile.safe_music_file_name("song.exe").is_empty(),
"non-audio attachments are rejected"
)
_check(
RoutineFile.is_audio_file("song.MP3")
and RoutineFile.is_audio_file("song.ogg")
and RoutineFile.is_audio_file("song.wav"),
"audio extensions are recognised case-insensitively"
)
var unsafe_music := encoded.replace(
"\"music_file\": \"kuer.mp3\"",
"\"music_file\": \"../kuer.mp3\""
)
var unsafe_result := RoutineFile.decode_json(unsafe_music)
_check(
str(unsafe_result["error"]).is_empty()
and (unsafe_result["routine"] as Routine).music_file.is_empty(),
"unsafe music references are dropped while the routine still loads"
)
var empty_label := encoded.replace("\"text\": \"Dreh\"", "\"text\": \"\"")
var empty_result := RoutineFile.decode_json(empty_label)
_check(
str(empty_result["error"]).is_empty()
and (empty_result["routine"] as Routine).timeline_labels.size() == 1,
"empty timeline labels are dropped"
)
var label_data: Dictionary = JSON.parse_string(encoded)
label_data["timeline_labels"] = "kaputt"
var bad_labels := RoutineFile.decode_json(JSON.stringify(label_data))
_check(
not str(bad_labels["error"]).is_empty(),
"invalid timeline label data is rejected"
)
func _test_atomic_write() -> void: func _test_atomic_write() -> void:
var routine := _make_routine() var routine := _make_routine()
@ -224,6 +290,11 @@ func _make_routine() -> Routine:
routine.routine_id = "format-test" routine.routine_id = "format-test"
routine.title = "Format Test" routine.title = "Format Test"
routine.skater_name = "Erika" routine.skater_name = "Erika"
routine.music_file = "kuer.mp3"
routine.timeline_labels = [
{"time_seconds": 4.5, "text": "Finale"},
{"time_seconds": 1.25, "text": "Dreh"},
]
routine.adult_category = "gold" routine.adult_category = "gold"
routine.assumed_pcs_average = 4.75 routine.assumed_pcs_average = 4.75
routine.assumed_falls = 1 routine.assumed_falls = 1

View file

@ -68,6 +68,48 @@ func _run() -> void:
"timeline covers the whole routine" "timeline covers the whole routine"
) )
controller.play()
controller.advance_playback(0.2)
controller.set_active_section(section_two.section_id)
_check(not controller.is_playing(), "section change stops active playback")
_check_approx(
controller.get_playback_time(),
4.0,
"selecting a section moves the playback to its start"
)
_check_approx(
controller.playback_timeline.value,
4.0,
"timeline slider jumps to the section start"
)
_check(
controller.get_playback_section_id() == section_two.section_id,
"playback reports the newly selected section"
)
_check_vec(
controller.get_playback_position(),
Vector2(4.0, 0.0),
"playback marker sits at the section start"
)
controller.set_active_section(section_one.section_id)
_check_approx(
controller.get_playback_time(),
0.0,
"switching back moves the playback to the first section"
)
_check_approx(
controller.playback_timeline.value,
0.0,
"timeline slider returns to the first section"
)
_check(
controller.get_playback_section_id() == section_one.section_id,
"playback reports the first section again"
)
# Keep the original active section for the marker tests below.
controller.set_active_section(section_two.section_id)
controller.seek_playback(1.0) controller.seek_playback(1.0)
_check(not controller.is_playing(), "seeking does not start playback") _check(not controller.is_playing(), "seeking does not start playback")
_check_vec( _check_vec(
@ -202,6 +244,17 @@ func _run() -> void:
8.0, 8.0,
"spin marker gets a default stand time" "spin marker gets a default stand time"
) )
var zero_marker := controller.add_element_marker(
Vector2(24.0, 3.0),
PathSegment.ElementType.SEQUENCE,
"StSq",
0
)
_check_approx(
zero_marker.element_duration_seconds,
0.0,
"sequence marker can have no stand time"
)
controller._update_status() controller._update_status()
_check_approx( _check_approx(
controller.get_playback_duration(), controller.get_playback_duration(),
@ -235,11 +288,217 @@ func _run() -> void:
"spin marker rotates the playback dot in place" "spin marker rotates the playback dot in place"
) )
# Timeline labels: element labels are drawn read-only and a click on the
# lane creates an editable custom label at that time.
forward.label = "Auftakt"
last.label = "Finale"
controller._update_status()
_check(
controller.timeline_label_lane.get_element_label_count() == 5,
"labelled segments and element captions appear on the timeline"
)
var has_element_label := false
var has_jump_caption := false
var has_spin_caption := false
var has_zero_caption := false
for item: Dictionary in controller.timeline_label_lane.get_display_items():
if bool(item["custom"]):
continue
var item_text := str(item["text"])
if item_text == "Auftakt":
has_element_label = true
elif item_text == "3Lz":
has_jump_caption = true
elif item_text.begins_with("CCoSp"):
has_spin_caption = true
elif item_text == "StSq":
has_zero_caption = true
_check(has_element_label, "element label is part of the timeline drawing")
_check(has_jump_caption, "jump caption appears without a free-text label")
_check(has_spin_caption, "spin caption appears without a free-text label")
_check(has_zero_caption, "zero-duration element stays on the timeline")
_check(
controller.add_timeline_label(5.0, "Musikstart"),
"custom timeline label is added"
)
var custom_labels := controller.get_timeline_labels()
_check(custom_labels.size() == 1, "routine stores the custom timeline label")
if custom_labels.size() == 1:
_check(custom_labels[0]["text"] == "Musikstart", "custom label text survives")
_check_approx(
float(custom_labels[0]["time_seconds"]),
5.0,
"custom label keeps its time"
)
_check(
controller.timeline_label_lane.get_custom_label_count() == 1,
"custom label is shown on the lane"
)
controller.timeline_label_lane.size = Vector2(600.0, 44.0)
controller.timeline_label_lane._rebuild_items()
var lane_click := InputEventMouseButton.new()
lane_click.button_index = MOUSE_BUTTON_LEFT
lane_click.pressed = true
lane_click.position = Vector2(100.0, 20.0)
controller.timeline_label_lane._gui_input(lane_click)
_check(
controller.timeline_label_dialog.visible,
"clicking the empty lane opens the label dialog"
)
controller.timeline_label_dialog.hide()
var label_click := InputEventMouseButton.new()
label_click.button_index = MOUSE_BUTTON_LEFT
label_click.pressed = true
label_click.position = Vector2(
controller.timeline_label_lane._time_to_x(5.0) + 2.0,
20.0
)
controller.timeline_label_lane._gui_input(label_click)
_check(
controller.timeline_label_dialog.visible
and controller.timeline_label_edit.text == "Musikstart",
"clicking a custom label opens it for editing"
)
controller.timeline_label_dialog.hide()
_check(
controller.update_timeline_label(0, "Sprung"),
"custom timeline label can be edited"
)
_check(
controller.get_timeline_labels()[0]["text"] == "Sprung",
"edited label text is stored"
)
_check(controller.undo(), "timeline label edit can be undone")
_check(
controller.get_timeline_labels()[0]["text"] == "Musikstart",
"undo restores the previous label text"
)
_check(controller.redo(), "timeline label edit can be redone")
_check(
controller.get_timeline_labels()[0]["text"] == "Sprung",
"redo restores the edited label text"
)
_check(
controller.remove_timeline_label(0),
"custom timeline label can be removed"
)
_check(
controller.get_timeline_labels().is_empty(),
"removed label is gone from the routine"
)
_check(
controller.timeline_label_lane.get_custom_label_count() == 0,
"removed label disappears from the lane"
)
forward.label = ""
last.label = ""
controller._update_status()
# Music: loading copies the track into the routine folder, the player
# follows the routine clock and the reference is cleared again on removal.
var music_source := "user://test_music.wav"
for old_path: String in [music_source, "user://routines/test_music.wav"]:
if FileAccess.file_exists(old_path):
DirAccess.remove_absolute(ProjectSettings.globalize_path(old_path))
_write_test_wav(music_source)
_check(
controller.load_music_from_path(music_source),
"music file is loaded into the routine"
)
_check(
controller.get_music_file_name() == "test_music.wav",
"routine references the copied music file"
)
_check(
FileAccess.file_exists("user://routines/test_music.wav"),
"music is stored next to the routine JSON"
)
_check(controller.has_music_stream(), "player has an audio stream")
_check(
controller.music_label.text.contains("test_music.wav"),
"playback bar shows the music file"
)
controller.seek_playback(0.5)
controller.play()
_check(controller.music_player.playing, "music starts with routine playback")
_check_approx(
controller.music_player.pitch_scale,
1.0,
"music plays at normal speed at 1x"
)
controller.seek_playback(3.0)
_check_approx(
controller.get_playback_time(),
3.0,
"scrubbing moves the routine clock"
)
controller.speed_option.item_selected.emit(4)
_check_approx(
controller.music_player.pitch_scale,
2.0,
"music follows the selected playback speed"
)
controller.speed_option.item_selected.emit(2)
controller.reset_playback()
_check(not controller.music_player.playing, "reset stops the music")
_check_approx(
controller.music_player.pitch_scale,
1.0,
"reset restores normal music speed"
)
controller._clear_music()
_check(controller.get_music_file_name().is_empty(), "music reference is cleared")
_check(not controller.has_music_stream(), "cleared music has no stream")
_check(
FileAccess.file_exists("user://routines/test_music.wav"),
"clearing keeps the file for other routines"
)
DirAccess.remove_absolute(
ProjectSettings.globalize_path("user://routines/test_music.wav")
)
DirAccess.remove_absolute(ProjectSettings.globalize_path(music_source))
scene.queue_free() scene.queue_free()
await process_frame await process_frame
# Give the audio thread one real-time slice so its playback objects are
# released before ObjectDB checks for leaks at exit.
OS.delay_msec(300)
await process_frame
await process_frame
_finish() _finish()
func _write_test_wav(path: String) -> void:
const SAMPLE_RATE := 8000
const DATA_SIZE := SAMPLE_RATE * 2
var file := FileAccess.open(path, FileAccess.WRITE)
if file == null:
return
file.store_buffer("RIFF".to_ascii_buffer())
file.store_32(36 + DATA_SIZE)
file.store_buffer("WAVE".to_ascii_buffer())
file.store_buffer("fmt ".to_ascii_buffer())
file.store_32(16)
file.store_16(1)
file.store_16(1)
file.store_32(SAMPLE_RATE)
file.store_32(SAMPLE_RATE * 2)
file.store_16(2)
file.store_16(16)
file.store_buffer("data".to_ascii_buffer())
file.store_32(DATA_SIZE)
var silence := PackedByteArray()
silence.resize(DATA_SIZE)
file.store_buffer(silence)
file.close()
func _check(condition: bool, message: String) -> void: func _check(condition: bool, message: String) -> void:
_assertions += 1 _assertions += 1
if not condition: if not condition:

View file

@ -121,6 +121,18 @@ func _test_naming() -> void:
and not RoutineSync.is_routine_file("sync.cfg"), and not RoutineSync.is_routine_file("sync.cfg"),
"der Sync akzeptiert JSON und Legacy-.tres" "der Sync akzeptiert JSON und Legacy-.tres"
) )
_check(
RoutineSync.is_synced_file("kuer.mp3")
and RoutineSync.is_synced_file("kuer.ogg")
and RoutineSync.is_synced_file("kuer.wav")
and not RoutineSync.is_synced_file("notizen.txt"),
"der Sync akzeptiert Musikdateien der Kür"
)
_check(
SyncPlan.conflict_file_name("kuer.mp3", "2026-10-30 1050")
== "kuer (Server 2026-10-30 1050).mp3",
"Konfliktnamen behalten die Audio-Endung"
)
var label := SyncPlan.timestamp_label(0) var label := SyncPlan.timestamp_label(0)
_check( _check(
label.length() == 15 and label.contains("-") and label.contains(" "), label.length() == 15 and label.contains("-") and label.contains(" "),
@ -168,6 +180,24 @@ func _test_state_roundtrip() -> void:
var files := RoutineSync.local_files("user://does_not_exist") var files := RoutineSync.local_files("user://does_not_exist")
_check(files.is_empty(), "fehlendes Verzeichnis liefert keine Dateien") _check(files.is_empty(), "fehlendes Verzeichnis liefert keine Dateien")
var local_dir := "user://test_sync_files"
DirAccess.make_dir_recursive_absolute(ProjectSettings.globalize_path(local_dir))
for name: String in ["kuer.json", "kuer.mp3", "notizen.txt"]:
var file := FileAccess.open(local_dir.path_join(name), FileAccess.WRITE)
file.store_string("x")
file.close()
var listed := RoutineSync.local_files(local_dir)
_check(
listed.has("kuer.json") and listed.has("kuer.mp3"),
"lokale Dateiliste enthält Kür und Musik"
)
_check(not listed.has("notizen.txt"), "lokale Dateiliste ignoriert Fremddateien")
for name: String in ["kuer.json", "kuer.mp3", "notizen.txt"]:
DirAccess.remove_absolute(
ProjectSettings.globalize_path(local_dir.path_join(name))
)
DirAccess.remove_absolute(ProjectSettings.globalize_path(local_dir))
func _test_controller_wiring() -> void: func _test_controller_wiring() -> void:
var scene := WhiteboardScene.instantiate() var scene := WhiteboardScene.instantiate()