From 533a12ef1a455b3bf6ae4305924943222f78f258 Mon Sep 17 00:00:00 2001 From: torsten Date: Wed, 4 Nov 2026 13:37:12 +0100 Subject: [PATCH] feat: Musik, Timeline-Labels, Abschnittssprung, PDF-Export und responsive Dialoge --- docs/architecture.md | 40 +- docs/manual.md | 57 + docs/roadmap.md | 15 +- docs/sync.md | 11 +- rinkplanner/scenes/whiteboard/whiteboard.tscn | 197 +- rinkplanner/src/core/io/routine_file.gd | 95 + rinkplanner/src/core/model/routine.gd | 18 +- rinkplanner/src/core/sync/routine_sync.gd | 24 +- .../whiteboard/ctrl/whiteboard_controller.gd | 680 ++++++- .../src/whiteboard/io/routine_pdf_exporter.gd | 1601 +++++++++++++++++ .../whiteboard/io/routine_pdf_exporter.gd.uid | 1 + .../whiteboard/view/timeline_label_lane.gd | 282 +++ .../view/timeline_label_lane.gd.uid | 1 + rinkplanner/tests/run_export_tests.gd | 161 ++ rinkplanner/tests/run_file_format_tests.gd | 71 + rinkplanner/tests/run_playback_tests.gd | 259 +++ rinkplanner/tests/run_sync_tests.gd | 30 + 17 files changed, 3483 insertions(+), 60 deletions(-) create mode 100644 rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd create mode 100644 rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd.uid create mode 100644 rinkplanner/src/whiteboard/view/timeline_label_lane.gd create mode 100644 rinkplanner/src/whiteboard/view/timeline_label_lane.gd.uid diff --git a/docs/architecture.md b/docs/architecture.md index bb8a885..bffa560 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -340,7 +340,18 @@ Fahrtrichtung. den Marker während der Standzeit mit 1,5 Umdrehungen pro Sekunde. Während des Playbacks wird die aktuelle Section hervorgehoben, 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 Element-Standzeit. Nicht verbundene Segmente 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. - **Umfang:** Gesamte Kür oder aktiver Abschnitt; Dateien landen unter `user://exports/`. -- **PDF** ist nicht nativ in Godot. Erste Stufe: Browser-Druck aus SVG; - eine echte PDF-Ausgabe ist ein separates Arbeitspaket. +- **PDF** erzeugt `RoutinePdfExporter` direkt als Vektordokument über einen + 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/` (`RoutineFile`, Format `rinkplanner.routine`). Die Datei enthält - `schema_version` (aktuell 2); neuere Schemata werden abgelehnt, - Schema-1-Dateien beim Laden migriert. Die Elementfelder kamen additiv mit - Defaults hinzu, deshalb bleibt das Schema bei 2. Legacy-`.tres`-Dateien + `schema_version` (aktuell 4); neuere Schemata werden abgelehnt, + ältere Dateien beim Laden migriert (Schema 1: Dauer→Tempo, Schema 2→3: + 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 Whitelist (nur die vier Modellskripte, kein eingebettetes GDScript, keine 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 Öffnen-Dialog zeigt `.json` und Legacy-`.tres`, wobei eine vorhandene `.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 Änderungen nach `user://autosave.json`; beim Speichern oder Öffnen einer 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 und eine noch genauere Profilpflege aus eigenen Messungen. 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. diff --git a/docs/manual.md b/docs/manual.md index 56ce852..ac04abd 100644 --- a/docs/manual.md +++ b/docs/manual.md @@ -63,6 +63,63 @@ die 2D-Funktionen sind davon nicht betroffen. nicht. - 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 - Das **Kürzel** bezeichnet die Elementfamilie, z. B. `3Lz`, `CCoSp` oder diff --git a/docs/roadmap.md b/docs/roadmap.md index 80eee4c..eecbdc3 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -29,6 +29,13 @@ Voraussetzung für Phase 1. Session-Restore (Legacy-`.tres` lesbar) - [x] Playback-Dot mit Blickrichtung, Timeline, Play/Pause/Reset und 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] 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] Export der aktiven Section und des gesamten Programms - [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-Dialog mit Dateiname, Format und Umfang @@ -260,8 +271,8 @@ Schritte. ## Bewusst nicht jetzt -- Audio-Synchronisation (laut Definition in Phase 1 zurückgestellt) -- Native PDF-Ausgabe +- Native PDF-Ausgabe mit Bildern/Screenshots (die aktuelle PDF-Ausgabe ist + vektorbasiert und enthält keine Fotos) - Vollständiges ISU-Regelwerk vor dem stabilen Planungs-Workflow - Sync-Komfort und visuelles UI-Refactoring (erst nach dem PoC) - 3D-Produktionsreife diff --git a/docs/sync.md b/docs/sync.md index 80ec128..a3b9292 100644 --- a/docs/sync.md +++ b/docs/sync.md @@ -24,7 +24,9 @@ Danach **Datei → Jetzt synchronisieren**. ## Was passiert - 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 ihre Serverkopien nicht verlieren; neue Speicherungen schreiben `.json`. 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. - Neue Speicherungen sind JSON; der Sync akzeptiert weiterhin `.tres`, damit 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 Android ist das der interne App-Speicher, auf dem Desktop `~/.local/share/godot/app_userdata/Rinkplanner/`. diff --git a/rinkplanner/scenes/whiteboard/whiteboard.tscn b/rinkplanner/scenes/whiteboard/whiteboard.tscn index 382a9bc..6c0735f 100644 --- a/rinkplanner/scenes/whiteboard/whiteboard.tscn +++ b/rinkplanner/scenes/whiteboard/whiteboard.tscn @@ -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/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_edge"] @@ -454,7 +455,7 @@ text = "Labels" tooltip_text = "Beschriftungen ein- oder ausblenden" [node name="PlaybackBar" type="PanelContainer" parent="Layout"] -custom_minimum_size = Vector2(0, 72) +custom_minimum_size = Vector2(0, 124) layout_mode = 2 theme_override_styles/panel = SubResource("StyleBoxFlat_playback") @@ -490,11 +491,22 @@ text = "0,0 / 0,0 s" horizontal_alignment = 1 vertical_alignment = 1 -[node name="PlaybackTimeline" type="HSlider" parent="Layout/PlaybackBar/PlaybackContent"] -unique_name_in_owner = true -custom_minimum_size = Vector2(0, 56) +[node name="PlaybackTimelineArea" type="VBoxContainer" parent="Layout/PlaybackBar/PlaybackContent"] +custom_minimum_size = Vector2(0, 100) layout_mode = 2 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 step = 0.01 editable = false @@ -506,6 +518,33 @@ layout_mode = 2 theme_override_font_sizes/font_size = 15 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"] custom_minimum_size = Vector2(0, 64) layout_mode = 2 @@ -887,6 +926,19 @@ unique_name_in_owner = true wait_time = 1.5 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="."] unique_name_in_owner = true title = "Kür speichern unter" @@ -910,6 +962,38 @@ unique_name_in_owner = true custom_minimum_size = Vector2(0, 56) 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="."] unique_name_in_owner = true title = "Kür öffnen" @@ -993,49 +1077,128 @@ text = "Geschwindigkeit = Strecke / Zeit" [node name="ExportDialog" type="ConfirmationDialog" parent="."] unique_name_in_owner = true title = "Kür exportieren" -size = Vector2i(480, 360) +size = Vector2i(480, 520) +wrap_controls = false ok_button_text = "Exportieren" 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_top = 8.0 -offset_right = 472.0 -offset_bottom = 280.0 +offset_right = -8.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 -[node name="ExportNameLabel" type="Label" parent="ExportDialog/ExportBox"] +[node name="ExportNameLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"] layout_mode = 2 text = "Dateiname" -[node name="ExportNameEdit" type="LineEdit" parent="ExportDialog/ExportBox"] +[node name="ExportNameEdit" type="LineEdit" parent="ExportDialog/ExportScroll/ExportBox"] unique_name_in_owner = true custom_minimum_size = Vector2(0, 56) layout_mode = 2 -[node name="ExportFormatLabel" type="Label" parent="ExportDialog/ExportBox"] +[node name="ExportFormatLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"] layout_mode = 2 text = "Format" -[node name="ExportFormatOption" type="OptionButton" parent="ExportDialog/ExportBox"] +[node name="ExportFormatOption" type="OptionButton" parent="ExportDialog/ExportScroll/ExportBox"] unique_name_in_owner = true custom_minimum_size = Vector2(0, 56) layout_mode = 2 -[node name="ExportScopeLabel" type="Label" parent="ExportDialog/ExportBox"] +[node name="ExportScopeLabel" type="Label" parent="ExportDialog/ExportScroll/ExportBox"] layout_mode = 2 text = "Umfang" -[node name="ExportScopeOption" type="OptionButton" parent="ExportDialog/ExportBox"] +[node name="ExportScopeOption" type="OptionButton" parent="ExportDialog/ExportScroll/ExportBox"] unique_name_in_owner = true custom_minimum_size = Vector2(0, 56) 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 theme_override_colors/font_color = Color(0.580392, 0.639216, 0.721569, 1) 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="."] unique_name_in_owner = true diff --git a/rinkplanner/src/core/io/routine_file.gd b/rinkplanner/src/core/io/routine_file.gd index 7f22131..48261fa 100644 --- a/rinkplanner/src/core/io/routine_file.gd +++ b/rinkplanner/src/core/io/routine_file.gd @@ -28,6 +28,13 @@ const MAX_LABEL_LENGTH := 40 const MAX_ELEMENT_CODE_LENGTH := 24 const MAX_FEATURES := 16 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 ## 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) +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 ## success, or a user-facing error message. 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.title = _text(data, "title", "").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 = ( _text(data, "adult_category", "").left(MAX_TEXT_LENGTH) ) @@ -148,6 +183,12 @@ static func decode_json(text: String) -> Dictionary: 0, 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", {}) if not rink_data is Dictionary: @@ -198,9 +239,11 @@ static func encode(routine: Routine) -> String: "routine_id": routine.routine_id, "title": routine.title, "skater_name": routine.skater_name, + "music_file": safe_music_file_name(routine.music_file), "adult_category": routine.adult_category, "assumed_pcs_average": routine.assumed_pcs_average, "assumed_falls": routine.assumed_falls, + "timeline_labels": _encode_timeline_labels(routine.timeline_labels), "rink": { "length_m": routine.rink.length_m if routine.rink != null else 60.0, "width_m": routine.rink.width_m if routine.rink != null else 30.0, @@ -218,6 +261,27 @@ static func encode(routine: Routine) -> String: 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: var segments: Array = [] 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: var section := RoutineSection.new() section.section_id = _text(data, "section_id", "").left(MAX_TEXT_LENGTH) diff --git a/rinkplanner/src/core/model/routine.gd b/rinkplanner/src/core/model/routine.gd index a390571..90fb4c4 100644 --- a/rinkplanner/src/core/model/routine.gd +++ b/rinkplanner/src/core/model/routine.gd @@ -4,12 +4,18 @@ extends Resource ## 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. -const CURRENT_SCHEMA_VERSION := 2 +const CURRENT_SCHEMA_VERSION := 4 @export var schema_version: int = CURRENT_SCHEMA_VERSION @export var routine_id: String = "" @export var title: 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 ## means no category-specific validation. @export var adult_category: String = "" @@ -29,6 +35,10 @@ func get_duration_seconds() -> float: return total +func has_music() -> bool: + return not music_file.strip_edges().is_empty() + + func get_length_m() -> float: var total := 0.0 for section: RoutineSection in sections: @@ -69,6 +79,12 @@ func validate() -> PackedStringArray: errors.append("assumed_pcs_average must be between 0 and 10") if assumed_falls < 0: 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_orders: Dictionary[int, bool] = {} diff --git a/rinkplanner/src/core/sync/routine_sync.gd b/rinkplanner/src/core/sync/routine_sync.gd index b2246b9..982e565 100644 --- a/rinkplanner/src/core/sync/routine_sync.gd +++ b/rinkplanner/src/core/sync/routine_sync.gd @@ -10,8 +10,15 @@ const STATE_PATH := "user://sync_state.cfg" const TEMP_SUFFIX := ".part" const UPLOAD_SUFFIX := ".uploading" ## New routines are JSON; legacy `.tres` files stay in the sync so existing -## installations do not lose their server copies. -const ROUTINE_EXTENSIONS := [".json", ".tres"] +## installations do not lose their server copies. Audio attachments (the music +## 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 error: String = "" @@ -273,19 +280,24 @@ func _save_state(client: FtpClient, state: Dictionary) -> void: 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() - for extension: String in ROUTINE_EXTENSIONS: + for extension: String in SYNC_EXTENSIONS: if lower.ends_with(extension): return true 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: var files: Dictionary = {} for entry: Dictionary in client.list_files(): var name := str(entry.get("name", "")) - if not is_routine_file(name): + if not is_synced_file(name): continue files[name] = { "modify": int(entry.get("modify", 0)), @@ -302,7 +314,7 @@ static func local_files(directory: String = LOCAL_DIR) -> Dictionary: dir.list_dir_begin() var name := dir.get_next() while not name.is_empty(): - if not dir.current_is_dir() and is_routine_file(name): + if not dir.current_is_dir() and is_synced_file(name): var path := directory.path_join(name) files[name] = { "mtime": FileAccess.get_modified_time(path), diff --git a/rinkplanner/src/whiteboard/ctrl/whiteboard_controller.gd b/rinkplanner/src/whiteboard/ctrl/whiteboard_controller.gd index 26bc929..9cb6b17 100644 --- a/rinkplanner/src/whiteboard/ctrl/whiteboard_controller.gd +++ b/rinkplanner/src/whiteboard/ctrl/whiteboard_controller.gd @@ -18,6 +18,7 @@ enum FileAction { SAVE, SAVE_AS, EXPORT, + OPEN_EXPORTS, SYNC_NOW, SYNC_SETTINGS, } @@ -66,6 +67,10 @@ const SYNC_SETTINGS_PATH := "user://sync.cfg" const AUTOSAVE_DELAY_SECONDS := 1.5 const MAX_HISTORY := 50 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. @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_timeline: HSlider = %PlaybackTimeline @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 label_button: Button = %LabelButton @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_format_option: OptionButton = %ExportFormatOption @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 _active_section: RoutineSection @@ -197,6 +218,7 @@ var _show_score_info: bool = false var _show_score_assumptions: bool = false var _preset_speed: float = DEFAULT_SPEED_MPS var _current_path: String = "" +var _last_export_path: String = "" var _dirty: bool = false var _pending_action: Callable var _undo_stack: Array[HistoryEntry] = [] @@ -213,6 +235,8 @@ var _playback_segment_id: String = "" var _playback_position: Vector2 = Vector2.ZERO var _playback_heading: Vector2 = Vector2.RIGHT 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_job: RoutineSync var _sync_running: bool = false @@ -290,6 +314,19 @@ func _ready() -> void: reset_playback_button.pressed.connect(reset_playback) playback_timeline.value_changed.connect(_on_timeline_changed) 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_plus_button.pressed.connect(_change_selected_duration.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) calibration_dialog.confirmed.connect(_on_calibration_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) label_button.pressed.connect(_open_label_dialog) labels_toggle.toggled.connect(_on_labels_toggled) @@ -2010,9 +2050,10 @@ func set_active_section(section_id: String) -> void: if section == null: return - if _playing or not _playback_section_id.is_empty(): - reset_playback() + if _playing: + pause() + var start_time := get_section_start_time(section_id) rink_canvas.cancel_interaction() _active_section = section _selected_segment_id = "" @@ -2020,6 +2061,28 @@ func set_active_section(section_id: String) -> void: rink_canvas.set_active_section(section.section_id) _update_section_buttons() _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: @@ -2204,6 +2267,8 @@ func _clone_routine(source: Routine) -> Routine: clone.routine_id = source.routine_id clone.title = source.title 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.assumed_pcs_average = source.assumed_pcs_average clone.assumed_falls = source.assumed_falls @@ -2699,6 +2764,7 @@ func play() -> void: rink_canvas.set_selected_segment("") _playing = true _update_playback_state(0.0, true) + _start_music() _update_play_button() _update_playback_ui() _update_status() @@ -2709,6 +2775,7 @@ func pause() -> void: if not _playing: return _playing = false + _stop_music() _update_play_button() _update_playback_ui() _sync_trail_fade() @@ -2719,6 +2786,7 @@ func reset_playback() -> void: _playback_time = 0.0 _playback_section_id = "" _playback_segment_id = "" + _stop_music() _update_play_button() rink_canvas.clear_playback_state() if _view_3d_active and _presentation_3d != null: @@ -2733,6 +2801,8 @@ func seek_playback(time: float) -> void: rink_canvas.clear_playback_state() else: _update_playback_state(0.0, true) + if _playing: + _seek_music(_playback_time) _update_playback_ui() _sync_trail_fade() @@ -2750,6 +2820,7 @@ func advance_playback(delta: float) -> void: _playback_time = _playback_total_duration _update_playback_state(0.0, true) _playing = false + _stop_music() _update_play_button() _update_playback_ui() _sync_trail_fade() @@ -2760,6 +2831,7 @@ func advance_playback(delta: float) -> void: func _process(delta: float) -> void: advance_playback(delta) + _sync_music_to_playback() _poll_sync_thread() 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 play_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() @@ -2794,6 +2874,11 @@ func _toggle_playback() -> void: func _on_speed_selected(index: int) -> void: _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: @@ -2828,10 +2913,12 @@ func _refresh_playback_timeline() -> void: _playback_entries = entries _playback_total_duration = total + _refresh_timeline_labels() if total <= 0.0: _playback_time = 0.0 _playing = false + _stop_music() _playback_section_id = "" _playback_segment_id = "" rink_canvas.clear_playback_state() @@ -2841,6 +2928,7 @@ func _refresh_playback_timeline() -> void: _playback_time = clampf(_playback_time, 0.0, total) if _playing and _playback_time >= total: _playing = false + _stop_music() _update_play_button() _update_playback_ui() @@ -2974,6 +3062,8 @@ func _update_playback_ui() -> void: ) _updating_timeline = false + timeline_label_lane.set_playhead(_playback_time) + playback_time_label.text = "%s / %s s" % [ _format_seconds(_playback_time), _format_seconds(_playback_total_duration), @@ -2990,6 +3080,404 @@ func _update_play_button() -> void: 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 ----------------------------------------------------------- @@ -3389,6 +3877,7 @@ func _setup_file_menu() -> void: popup.add_item("Speichern unter…", FileAction.SAVE_AS) popup.add_separator() popup.add_item("Exportieren…", FileAction.EXPORT) + popup.add_item("Exportordner öffnen", FileAction.OPEN_EXPORTS) popup.add_separator() popup.add_item("Jetzt synchronisieren", FileAction.SYNC_NOW) popup.add_item("Sync-Einstellungen…", FileAction.SYNC_SETTINGS) @@ -3407,6 +3896,8 @@ func _on_file_menu_pressed(action: int) -> void: _open_save_as_dialog() FileAction.EXPORT: _open_export_dialog() + FileAction.OPEN_EXPORTS: + _open_exports_folder() FileAction.SYNC_NOW: start_sync() FileAction.SYNC_SETTINGS: @@ -3441,6 +3932,8 @@ func _install_routine( _playback_time = 0.0 _playback_section_id = "" _playback_segment_id = "" + _stop_music() + music_player.stream = null rink_canvas.clear_playback_state() rink_canvas.cancel_interaction() @@ -3461,6 +3954,8 @@ func _install_routine( valid_sections.append(section) _routine.sections = valid_sections _migrate_routine(_routine) + _load_music_stream() + _update_music_ui() if _routine.sections.is_empty(): var fallback := RoutineSection.new() @@ -3491,20 +3986,23 @@ func _migrate_routine(routine: Routine) -> void: if routine.schema_version >= Routine.CURRENT_SCHEMA_VERSION: return - for section: RoutineSection in routine.sections: - if section == null: - continue - for segment: PathSegment in section.segments: - if segment == null: + # 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: + if section == null: continue - var length := segment.get_length_m() - if length > 0.0 and segment.duration_seconds > 0.0: - segment.speed_mps = length / segment.duration_seconds - segment.timing_mode = PathSegment.TimingMode.DURATION - else: - segment.speed_mps = DEFAULT_SPEED_MPS - segment.timing_mode = PathSegment.TimingMode.SPEED - segment.apply_geometry_length(length) + for segment: PathSegment in section.segments: + if segment == null: + continue + var length := segment.get_length_m() + if length > 0.0 and segment.duration_seconds > 0.0: + segment.speed_mps = length / segment.duration_seconds + segment.timing_mode = PathSegment.TimingMode.DURATION + else: + segment.speed_mps = DEFAULT_SPEED_MPS + segment.timing_mode = PathSegment.TimingMode.SPEED + segment.apply_geometry_length(length) routine.schema_version = Routine.CURRENT_SCHEMA_VERSION @@ -3734,6 +4232,7 @@ func _setup_export_controls() -> void: export_format_option.clear() export_format_option.add_item("SVG (Vektor)", 0) 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.add_item("Gesamte Kür", 0) 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 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 + 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: @@ -3927,14 +4429,17 @@ func _format_sync_summary(result: Dictionary) -> String: func _reload_after_sync(result: Dictionary) -> void: if _current_path.is_empty(): + _refresh_synced_music(result) return var current_name := _current_path.get_file() var downloaded: Array = result.get("downloaded", []) var adopted: Array = result.get("adopted", []) if not downloaded.has(current_name) and not adopted.has(current_name): + _refresh_synced_music(result) return if is_dirty(): + _refresh_synced_music(result) _show_message( "Die geöffnete Kür wurde vom Server aktualisiert, hat aber " + "ungespeicherte Änderungen. Bitte manuell speichern oder neu laden." @@ -3943,6 +4448,22 @@ func _reload_after_sync(result: Dictionary) -> void: 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: if _sync_thread != null: _sync_thread.wait_to_finish() @@ -3958,11 +4479,27 @@ func _open_export_dialog() -> void: export_name_edit.text = "kuer" export_format_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.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: var name := export_name_edit.text.strip_edges() if name.is_empty(): @@ -3979,37 +4516,100 @@ func _on_export_confirmed() -> void: scope_section_id = _active_section.section_id scope_suffix = "_" + _normalize_file_stem(_active_section.title) - var is_svg := export_format_option.selected == 0 - var extension := "svg" if is_svg else "png" + var format := export_format_option.get_item_id( + 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) if FileAccess.file_exists(path): _confirm_overwrite( path, - _perform_export.bind(path, is_svg, scope_section_id) + _perform_export.bind(path, format, scope_section_id) ) return - await _perform_export(path, is_svg, scope_section_id) + await _perform_export(path, format, scope_section_id) func _perform_export( path: String, - is_svg: bool, + format: int, scope_section_id: String ) -> void: _ensure_exports_dir() var success := false - if is_svg: - success = export_svg_to_path(path, scope_section_id) - else: - success = await export_png_to_path(path, scope_section_id) + match format: + 0: + success = export_svg_to_path(path, scope_section_id) + 1: + success = await export_png_to_path(path, scope_section_id) + 2: + success = export_pdf_to_path(path, scope_section_id) 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: _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: if _routine == null: return false @@ -4025,6 +4625,21 @@ func export_svg_to_path(path: String, section_id: String = "") -> bool: 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: if _routine == null: return false @@ -4057,6 +4672,19 @@ func _ensure_exports_dir() -> void: 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: _refresh_open_list() open_dialog.popup_centered(Vector2i(520, 460)) diff --git a/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd b/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd new file mode 100644 index 0000000..05fcf9e --- /dev/null +++ b/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd @@ -0,0 +1,1601 @@ +class_name RoutinePdfExporter +extends RefCounted + +## Builds a printable PDF directly from the routine model. Every page contains +## vector paths (no screenshots): an overview with all sections, then one page +## per section with numbered paths and a table of start/end times, duration and +## element label. Long sections continue on additional pages. +## +## The PDF uses the built-in Helvetica fonts and WinAnsi text encoding, so it +## needs no external library and works on every export platform. + +const PAGE_WIDTH := 842.0 +const PAGE_HEIGHT := 595.0 +const MARGIN := 36.0 +const CONTENT_TOP := 104.0 +const FOOTER_RULE_Y := 566.0 + +const OVERVIEW_DIAGRAM_WIDTH := 500.0 +const OVERVIEW_DIAGRAM_HEIGHT := 268.0 +const SECTION_DIAGRAM_WIDTH := 470.0 +const SECTION_DIAGRAM_HEIGHT := 250.0 +const TABLE_X := 530.0 +const TABLE_WIDTH := 276.0 +const OVERVIEW_TABLE_X := 566.0 +const OVERVIEW_TABLE_WIDTH := 240.0 +const ROW_HEIGHT := 18.0 +const TABLE_HEADER_HEIGHT := 18.0 +const SECTION_ROWS_PER_PAGE := 23 +const OVERVIEW_ROWS_PER_PAGE := 24 + +const ICE_COLOR := Color(0.933, 0.965, 0.984) +const BOARDS_COLOR := Color(0.118, 0.161, 0.220) +const OUTSIDE_COLOR := Color(0.863, 0.149, 0.149) +const INSIDE_COLOR := Color(0.145, 0.388, 0.922) +const TEXT_COLOR := Color(0.059, 0.090, 0.165) +const MUTED_COLOR := Color(0.392, 0.455, 0.545) +const RULE_COLOR := Color(0.820, 0.855, 0.898) +const ROW_COLOR := Color(0.965, 0.975, 0.985) +const JUMP_COLOR := Color(0.961, 0.620, 0.043) +const SPIN_COLOR := Color(0.545, 0.361, 0.965) +const SEQUENCE_COLOR := Color(0.063, 0.725, 0.506) +const START_COLOR := Color(0.086, 0.639, 0.290) +const BADGE_COLOR := Color(0.059, 0.090, 0.165) + + +static func build(routine: Routine, section_id: String = "") -> PackedByteArray: + if routine == null: + return PackedByteArray() + + var sections := _collect_sections(routine) + if sections.is_empty(): + return PackedByteArray() + + var pages: Array[String] = [] + if section_id.is_empty(): + _append_overview_pages(pages, routine, sections) + for entry: Dictionary in sections: + _append_section_pages(pages, routine, entry) + else: + var found := false + for entry: Dictionary in sections: + var section: RoutineSection = entry["section"] + if section.section_id == section_id: + _append_section_pages(pages, routine, entry) + found = true + if not found: + return PackedByteArray() + + var title := _routine_title(routine) + for index: int in range(pages.size()): + pages[index] += "\n" + _build_footer(index + 1, pages.size(), title) + + return _assemble_pdf(pages) + + +## --- Page structure ------------------------------------------------------- + + +static func _append_overview_pages( + pages: Array[String], + routine: Routine, + sections: Array[Dictionary] +) -> void: + var index := 0 + var first := true + while first or index < sections.size(): + var chunk := sections.slice( + index, + mini(index + OVERVIEW_ROWS_PER_PAGE, sections.size()) + ) + if first: + pages.append(_build_overview_page(routine, sections, chunk)) + else: + pages.append( + _build_overview_continuation_page( + routine, + chunk, + index, + sections.size() + ) + ) + index += chunk.size() + first = false + + +static func _append_section_pages( + pages: Array[String], + routine: Routine, + entry: Dictionary +) -> void: + var rows: Array[Dictionary] = entry["rows"] + var index := 0 + var first := true + while first or index < rows.size(): + var chunk := rows.slice( + index, + mini(index + SECTION_ROWS_PER_PAGE, rows.size()) + ) + pages.append( + _build_section_page(routine, entry, chunk, first) + ) + index += chunk.size() + first = false + + +static func _build_overview_page( + routine: Routine, + sections: Array[Dictionary], + table_sections: Array[Dictionary] +) -> String: + var title := _routine_title(routine) + var lines := _begin_page( + title, + _routine_subtitle(routine, sections.size()) + ) + + var rink: RinkDimensions = _safe_rink(routine) + var diagram := Rect2( + MARGIN, + CONTENT_TOP, + OVERVIEW_DIAGRAM_WIDTH, + OVERVIEW_DIAGRAM_HEIGHT + ) + lines.append("q") + _clip_rect(lines, diagram) + var mapping := _draw_rink(lines, rink, diagram) + for entry: Dictionary in sections: + _draw_section_paths(lines, entry, mapping, false) + _draw_start_end_markers(lines, sections, mapping) + for index: int in range(sections.size()): + _draw_section_badge(lines, sections[index], mapping, index + 1) + lines.append("Q") + + _draw_legend(lines, MARGIN, diagram.end.y + 24.0) + _draw_timeline_notes(lines, routine, MARGIN, diagram.end.y + 76.0) + _draw_section_table( + lines, + table_sections, + OVERVIEW_TABLE_X, + CONTENT_TOP, + OVERVIEW_TABLE_WIDTH, + 0 + ) + return "\n".join(lines) + + +static func _build_overview_continuation_page( + routine: Routine, + table_sections: Array[Dictionary], + start_number: int, + total_sections: int +) -> String: + var lines := _begin_page( + "Ablauf (Fortsetzung)", + _routine_subtitle(routine, total_sections) + ) + _draw_section_table( + lines, + table_sections, + MARGIN, + CONTENT_TOP, + PAGE_WIDTH - 2.0 * MARGIN, + start_number + ) + return "\n".join(lines) + + +static func _build_section_page( + routine: Routine, + entry: Dictionary, + rows: Array[Dictionary], + first_page: bool +) -> String: + var section: RoutineSection = entry["section"] + var number := int(entry["number"]) + var title := "%d. %s" % [number, _section_title(section)] + if not first_page: + title += " · Fortsetzung" + var all_rows: Array[Dictionary] = entry["rows"] + var lines := _begin_page( + title, + _section_subtitle(entry, all_rows.size()) + ) + + if first_page: + var rink: RinkDimensions = _safe_rink(routine) + var diagram := Rect2( + MARGIN, + CONTENT_TOP, + SECTION_DIAGRAM_WIDTH, + SECTION_DIAGRAM_HEIGHT + ) + lines.append("q") + _clip_rect(lines, diagram) + var mapping := _draw_rink(lines, rink, diagram) + _draw_section_paths(lines, entry, mapping, true) + _draw_section_start_end(lines, all_rows, mapping) + lines.append("Q") + _draw_legend(lines, MARGIN, diagram.end.y + 22.0) + _draw_note( + lines, + MARGIN, + diagram.end.y + 78.0, + SECTION_DIAGRAM_WIDTH, + "Die Zahlen im Rink entsprechen der Reihenfolge in der Tabelle. " + + "Die Tabelle nennt Start, Ende, Dauer und Element bzw. Label." + ) + _draw_segment_table(lines, rows, TABLE_X, CONTENT_TOP, TABLE_WIDTH) + else: + # Continuation pages use the full width for the remaining rows. + _draw_segment_table( + lines, + rows, + MARGIN, + CONTENT_TOP, + PAGE_WIDTH - 2.0 * MARGIN + ) + return "\n".join(lines) + + +## --- Model collection ----------------------------------------------------- + + +static func _collect_sections(routine: Routine) -> Array[Dictionary]: + var result: Array[Dictionary] = [] + var total := 0.0 + for section: RoutineSection in routine.sections: + if section == null: + continue + var section_start := total + var rows: Array[Dictionary] = [] + var index := 0 + for segment: PathSegment in section.segments: + if segment == null: + continue + index += 1 + var duration := maxf( + segment.get_effective_duration_seconds(), + 0.0 + ) + rows.append({ + "index": index, + "start": total, + "end": total + duration, + "duration": duration, + "text": _segment_text(segment), + "segment": segment, + }) + total += duration + result.append({ + "number": result.size() + 1, + "section": section, + "start": section_start, + "end": total, + "duration": total - section_start, + "rows": rows, + }) + return result + + +static func _segment_text(segment: PathSegment) -> String: + var text := segment.label.strip_edges() + if text.is_empty() and segment.is_element(): + text = segment.get_element_caption().strip_edges() + if text.is_empty(): + if segment.is_arc(): + text = "Bogen links" if segment.arc_bulge_left else "Bogen rechts" + else: + text = "Linie" + + if not segment.is_element_marker(): + var details := PackedStringArray() + if segment.direction == PathSegment.Direction.BACKWARD: + details.append("rückwärts") + if segment.edge == PathSegment.Edge.INSIDE: + details.append("innen") + if not details.is_empty(): + text += " · " + ", ".join(details) + return text + + +static func _routine_title(routine: Routine) -> String: + var title := routine.title.strip_edges() + return title if not title.is_empty() else "Unbenannte Kür" + + +static func _section_title(section: RoutineSection) -> String: + var title := section.title.strip_edges() + return title if not title.is_empty() else "Abschnitt" + + +static func _routine_subtitle(routine: Routine, section_count: int) -> String: + var parts := PackedStringArray() + var skater := routine.skater_name.strip_edges() + if not skater.is_empty(): + parts.append(skater) + var category := routine.adult_category.strip_edges() + if not category.is_empty(): + parts.append("Kategorie: %s" % category.capitalize()) + parts.append("%d Abschnitte" % section_count) + parts.append("Gesamt %s" % _fmt_clock(routine.get_duration_seconds())) + if routine.has_music(): + parts.append("Musik: %s" % routine.music_file) + return " · ".join(parts) + + +static func _section_subtitle(entry: Dictionary, row_count: int) -> String: + var section: RoutineSection = entry["section"] + return "Zeit %s–%s · Dauer %s · %d Segmente" % [ + _fmt_clock(float(entry["start"])), + _fmt_clock(float(entry["end"])), + _fmt_clock(float(entry["duration"])), + row_count, + ] + + +static func _safe_rink(routine: Routine) -> RinkDimensions: + if routine.rink != null and routine.rink.is_valid(): + return routine.rink + return RinkDimensions.new() + + +## --- Drawing: page frame and text ----------------------------------------- + + +static func _begin_page(title: String, subtitle: String) -> PackedStringArray: + var lines := PackedStringArray() + lines.append("1 1 1 rg 0 0 %s %s re f" % [_n(PAGE_WIDTH), _n(PAGE_HEIGHT)]) + lines.append("1 J 1 j") + _text( + lines, + _fit_text(title, 18.0, PAGE_WIDTH - 2.0 * MARGIN), + MARGIN, + 48.0, + 18.0, + true, + TEXT_COLOR + ) + _text( + lines, + _fit_text(subtitle, 9.5, PAGE_WIDTH - 2.0 * MARGIN), + MARGIN, + 68.0, + 9.5, + false, + MUTED_COLOR + ) + _line(lines, MARGIN, 84.0, PAGE_WIDTH - MARGIN, 84.0, RULE_COLOR, 0.8) + return lines + + +static func _build_footer( + page_number: int, + page_count: int, + title: String +) -> String: + var lines := PackedStringArray() + _line( + lines, + MARGIN, + FOOTER_RULE_Y, + PAGE_WIDTH - MARGIN, + FOOTER_RULE_Y, + RULE_COLOR, + 0.6 + ) + _text( + lines, + _fit_text( + "Rinkplanner · %s" % title, + 8.0, + PAGE_WIDTH - 2.0 * MARGIN - 40.0 + ), + MARGIN, + FOOTER_RULE_Y + 12.0, + 8.0, + false, + MUTED_COLOR + ) + _text_right( + lines, + "%d / %d" % [page_number, page_count], + PAGE_WIDTH - MARGIN, + FOOTER_RULE_Y + 12.0, + 8.0, + false, + MUTED_COLOR + ) + return "\n".join(lines) + + +static func _text( + lines: PackedStringArray, + text: String, + x: float, + top: float, + size: float, + bold: bool = false, + color: Color = TEXT_COLOR +) -> void: + if text.is_empty(): + return + lines.append( + "BT /%s %s Tf %s %s %s rg %s %s Td %s Tj ET" + % [ + "F2" if bold else "F1", + _n(size), + _n(color.r), + _n(color.g), + _n(color.b), + _n(x), + _n(_y(top)), + _pdf_literal(text), + ] + ) + + +static func _text_right( + lines: PackedStringArray, + text: String, + right_x: float, + top: float, + size: float, + bold: bool = false, + color: Color = TEXT_COLOR +) -> void: + _text( + lines, + text, + right_x - _text_width(text, size), + top, + size, + bold, + color + ) + + +static func _text_centered( + lines: PackedStringArray, + text: String, + center_x: float, + top: float, + size: float, + bold: bool = false, + color: Color = TEXT_COLOR +) -> void: + _text( + lines, + text, + center_x - _text_width(text, size) * 0.5, + top, + size, + bold, + color + ) + + +static func _text_width(text: String, size: float) -> float: + # Good enough for centering short labels and page numbers. + return float(text.length()) * size * 0.52 + + +static func _fit_text(text: String, size: float, max_width: float) -> String: + var cleaned := text.replace("\n", " ").replace("\r", " ").strip_edges() + var max_chars := int(max_width / maxf(size * 0.52, 0.1)) + if max_chars <= 1: + return "" + if cleaned.length() <= max_chars: + return cleaned + return cleaned.left(max_chars - 1) + "…" + + +## --- Drawing: shapes ------------------------------------------------------ + + +static func _line( + lines: PackedStringArray, + x1: float, + top1: float, + x2: float, + top2: float, + color: Color, + width: float +) -> void: + _set_stroke(lines, color, width) + lines.append( + "%s %s m %s %s l S" + % [_n(x1), _n(_y(top1)), _n(x2), _n(_y(top2))] + ) + + +static func _rect( + lines: PackedStringArray, + x: float, + top: float, + width: float, + height: float, + fill: Color, + stroke: Color = Color.TRANSPARENT, + stroke_width: float = 0.0 +) -> void: + lines.append( + "%s %s %s %s re" + % [_n(x), _n(_y(top + height)), _n(width), _n(height)] + ) + var has_fill := fill.a > 0.0 + var has_stroke := stroke.a > 0.0 and stroke_width > 0.0 + if has_fill: + _set_fill(lines, fill) + if has_stroke: + _set_stroke(lines, stroke, stroke_width) + if has_fill and has_stroke: + lines.append("B") + elif has_fill: + lines.append("f") + elif has_stroke: + lines.append("S") + else: + lines.append("n") + + +static func _clip_rect(lines: PackedStringArray, area: Rect2) -> void: + lines.append( + "%s %s %s %s re W n" + % [ + _n(area.position.x - 8.0), + _n(_y(area.end.y + 8.0)), + _n(area.size.x + 16.0), + _n(area.size.y + 16.0), + ] + ) + + +static func _polygon( + lines: PackedStringArray, + points: PackedVector2Array, + fill: Color, + stroke: Color, + stroke_width: float +) -> void: + if points.size() < 3: + return + lines.append("%s %s m" % [_n(points[0].x), _n(_y(points[0].y))]) + for index: int in range(1, points.size()): + lines.append( + "%s %s l" % [_n(points[index].x), _n(_y(points[index].y))] + ) + lines.append("h") + var has_fill := fill.a > 0.0 + var has_stroke := stroke.a > 0.0 and stroke_width > 0.0 + if has_fill: + _set_fill(lines, fill) + if has_stroke: + _set_stroke(lines, stroke, stroke_width) + if has_fill and has_stroke: + lines.append("B") + elif has_fill: + lines.append("f") + elif has_stroke: + lines.append("S") + else: + lines.append("n") + + +static func _circle( + lines: PackedStringArray, + center_x: float, + center_top: float, + radius: float, + fill: Color, + stroke: Color = Color.TRANSPARENT, + stroke_width: float = 0.0 +) -> void: + var k := 0.5522847498 * radius + var cy := _y(center_top) + lines.append("%s %s m" % [_n(center_x + radius), _n(cy)]) + lines.append( + "%s %s %s %s %s %s c" + % [ + _n(center_x + radius), + _n(cy + k), + _n(center_x + k), + _n(cy + radius), + _n(center_x), + _n(cy + radius), + ] + ) + lines.append( + "%s %s %s %s %s %s c" + % [ + _n(center_x - k), + _n(cy + radius), + _n(center_x - radius), + _n(cy + k), + _n(center_x - radius), + _n(cy), + ] + ) + lines.append( + "%s %s %s %s %s %s c" + % [ + _n(center_x - radius), + _n(cy - k), + _n(center_x - k), + _n(cy - radius), + _n(center_x), + _n(cy - radius), + ] + ) + lines.append( + "%s %s %s %s %s %s c" + % [ + _n(center_x + k), + _n(cy - radius), + _n(center_x + radius), + _n(cy - k), + _n(center_x + radius), + _n(cy), + ] + ) + lines.append("h") + var has_fill := fill.a > 0.0 + var has_stroke := stroke.a > 0.0 and stroke_width > 0.0 + if has_fill: + _set_fill(lines, fill) + if has_stroke: + _set_stroke(lines, stroke, stroke_width) + if has_fill and has_stroke: + lines.append("B") + elif has_fill: + lines.append("f") + elif has_stroke: + lines.append("S") + else: + lines.append("n") + + +static func _set_fill(lines: PackedStringArray, color: Color) -> void: + lines.append("%s %s %s rg" % [_n(color.r), _n(color.g), _n(color.b)]) + + +static func _set_stroke( + lines: PackedStringArray, + color: Color, + width: float +) -> void: + lines.append( + "%s %s %s RG %s w" + % [_n(color.r), _n(color.g), _n(color.b), _n(width)] + ) + + +static func _set_dash( + lines: PackedStringArray, + dash: float, + gap: float +) -> void: + lines.append("[%s %s] 0 d" % [_n(dash), _n(gap)]) + + +static func _reset_dash(lines: PackedStringArray) -> void: + lines.append("[] 0 d") + + +## --- Drawing: rink and paths ---------------------------------------------- + + +static func _draw_rink( + lines: PackedStringArray, + rink: RinkDimensions, + area: Rect2 +) -> Dictionary: + var scale := minf( + area.size.x / maxf(rink.length_m, 0.001), + area.size.y / maxf(rink.width_m, 0.001) + ) + var center_left := area.position.x + area.size.x * 0.5 + var center_top := area.position.y + area.size.y * 0.5 + var outline := rink.get_outline_points(18) + var screen_points := PackedVector2Array() + screen_points.resize(outline.size()) + for index: int in range(outline.size()): + screen_points[index] = Vector2( + center_left + outline[index].x * scale, + center_top + outline[index].y * scale + ) + _polygon( + lines, + screen_points, + ICE_COLOR, + BOARDS_COLOR, + maxf(1.0, 0.14 * scale) + ) + + var half_width := rink.get_half_width() + var center_line_color := OUTSIDE_COLOR.lerp(Color.WHITE, 0.55) + _line( + lines, + center_left, + center_top - half_width * scale, + center_left, + center_top + half_width * scale, + center_line_color, + maxf(0.8, 0.07 * scale) + ) + _circle( + lines, + center_left, + center_top, + 4.5 * scale, + Color.TRANSPARENT, + Color(0.58, 0.65, 0.73), + maxf(0.7, 0.05 * scale) + ) + return { + "scale": scale, + "center_left": center_left, + "center_top": center_top, + } + + +static func _map_point(point: Vector2, mapping: Dictionary) -> Vector2: + var scale := float(mapping["scale"]) + return Vector2( + float(mapping["center_left"]) + point.x * scale, + float(mapping["center_top"]) + point.y * scale + ) + + +static func _draw_section_paths( + lines: PackedStringArray, + entry: Dictionary, + mapping: Dictionary, + with_badges: bool +) -> void: + var rows: Array[Dictionary] = entry["rows"] + for row: Dictionary in rows: + var segment: PathSegment = row["segment"] + _draw_segment( + lines, + segment, + mapping, + int(row["index"]), + with_badges + ) + + +static func _draw_segment( + lines: PackedStringArray, + segment: PathSegment, + mapping: Dictionary, + number: int, + with_badge: bool +) -> void: + if segment == null or segment.curve == null: + return + if segment.curve.point_count == 0: + return + + if segment.is_element_marker(): + var point := _map_point(segment.curve.get_point_position(0), mapping) + _draw_element_marker(lines, segment, point) + if with_badge: + _draw_badge(lines, number, point + Vector2(10.0, 9.0)) + return + + var length := segment.curve.get_baked_length() + if length <= 0.0: + if segment.curve.point_count > 0: + var point := _map_point( + segment.curve.get_point_position(0), + mapping + ) + if with_badge: + _draw_badge(lines, number, point + Vector2(8.0, -8.0)) + return + + var color := _edge_color(segment) + var width := maxf(1.2, 0.12 * float(mapping["scale"])) + _set_stroke(lines, color, width) + if segment.direction == PathSegment.Direction.BACKWARD: + _set_dash(lines, maxf(5.0, 0.35 * float(mapping["scale"])), 4.0) + else: + _reset_dash(lines) + + var curve := segment.curve + var first := _map_point(curve.get_point_position(0), mapping) + lines.append("%s %s m" % [_n(first.x), _n(_y(first.y))]) + for index: int in range(curve.point_count - 1): + var start := curve.get_point_position(index) + var end := curve.get_point_position(index + 1) + var out_handle := curve.get_point_out(index) + var in_handle := curve.get_point_in(index + 1) + var mapped_end := _map_point(end, mapping) + if ( + out_handle.length_squared() <= 0.0000001 + and in_handle.length_squared() <= 0.0000001 + ): + lines.append("%s %s l" % [_n(mapped_end.x), _n(_y(mapped_end.y))]) + else: + var control_a := _map_point(start + out_handle, mapping) + var control_b := _map_point(end + in_handle, mapping) + lines.append( + "%s %s %s %s %s %s c" + % [ + _n(control_a.x), + _n(_y(control_a.y)), + _n(control_b.x), + _n(_y(control_b.y)), + _n(mapped_end.x), + _n(_y(mapped_end.y)), + ] + ) + lines.append("S") + _reset_dash(lines) + _draw_arrow_head(lines, segment, mapping, color, width) + + if with_badge: + var mid := curve.sample_baked(length * 0.5) + var before := curve.sample_baked(maxf(0.0, length * 0.5 - 0.5)) + var after := curve.sample_baked(minf(length, length * 0.5 + 0.5)) + var tangent := (after - before) + if tangent.length_squared() <= 0.0000001: + tangent = Vector2.RIGHT + tangent = tangent.normalized() + var normal := Vector2(-tangent.y, tangent.x) + var badge := _map_point(mid, mapping) + normal * 9.0 + _draw_badge(lines, number, badge) + + +static func _draw_arrow_head( + lines: PackedStringArray, + segment: PathSegment, + mapping: Dictionary, + color: Color, + width: float +) -> void: + var curve := segment.curve + if curve == null or curve.point_count < 2: + return + var end := curve.get_point_position(curve.point_count - 1) + var before := curve.get_point_position(curve.point_count - 2) + var tangent := end - before + if tangent.length_squared() <= 0.0000001: + return + tangent = tangent.normalized() + if segment.direction == PathSegment.Direction.BACKWARD: + tangent = -tangent + var tip := _map_point(end, mapping) + var direction := Vector2(tangent.x, tangent.y).normalized() + var normal := Vector2(-direction.y, direction.x) + var base := tip - direction * 7.0 + _set_stroke(lines, color, width) + lines.append( + "%s %s m %s %s l S" + % [ + _n(tip.x), + _n(_y(tip.y)), + _n(base.x + normal.x * 3.2), + _n(_y(base.y + normal.y * 3.2)), + ] + ) + lines.append( + "%s %s m %s %s l S" + % [ + _n(tip.x), + _n(_y(tip.y)), + _n(base.x - normal.x * 3.2), + _n(_y(base.y - normal.y * 3.2)), + ] + ) + + +static func _draw_element_marker( + lines: PackedStringArray, + segment: PathSegment, + point: Vector2 +) -> void: + var radius := 6.0 + var color := _element_color(segment.element_type) + match segment.element_type: + PathSegment.ElementType.JUMP: + _polygon( + lines, + PackedVector2Array([ + Vector2(point.x, point.y - radius), + Vector2(point.x + radius, point.y), + Vector2(point.x, point.y + radius), + Vector2(point.x - radius, point.y), + ]), + color, + TEXT_COLOR, + 1.0 + ) + PathSegment.ElementType.SEQUENCE: + _rect( + lines, + point.x - radius, + point.y - radius, + radius * 2.0, + radius * 2.0, + color, + TEXT_COLOR, + 1.0 + ) + _: + _circle(lines, point.x, point.y, radius, color, TEXT_COLOR, 1.0) + + var caption := segment.get_element_caption().strip_edges() + if not caption.is_empty(): + _text_centered( + lines, + _fit_text(caption, 7.0, 90.0), + point.x, + point.y - 10.0, + 7.0, + true, + TEXT_COLOR + ) + + +static func _draw_badge( + lines: PackedStringArray, + number: int, + point: Vector2 +) -> void: + _circle(lines, point.x, point.y, 6.5, BADGE_COLOR, Color.WHITE, 1.0) + _text_centered( + lines, + str(number), + point.x, + point.y + 2.7, + 7.0, + true, + Color.WHITE + ) + + +static func _draw_section_badge( + lines: PackedStringArray, + entry: Dictionary, + mapping: Dictionary, + number: int +) -> void: + var rows: Array[Dictionary] = entry["rows"] + for row: Dictionary in rows: + var segment: PathSegment = row["segment"] + if segment == null or segment.curve == null: + continue + if segment.curve.point_count == 0: + continue + var point := _map_point(segment.curve.get_point_position(0), mapping) + _circle(lines, point.x, point.y, 8.0, BADGE_COLOR, Color.WHITE, 1.2) + _text_centered( + lines, + str(number), + point.x, + point.y + 3.2, + 8.0, + true, + Color.WHITE + ) + return + + +static func _draw_start_end_markers( + lines: PackedStringArray, + sections: Array[Dictionary], + mapping: Dictionary +) -> void: + var start_point := Vector2.INF + var end_point := Vector2.INF + for entry: Dictionary in sections: + var rows: Array[Dictionary] = entry["rows"] + for row: Dictionary in rows: + var segment: PathSegment = row["segment"] + if segment == null or segment.curve == null: + continue + if segment.curve.point_count == 0: + continue + if start_point == Vector2.INF: + start_point = _segment_start(segment, mapping) + end_point = _segment_end(segment, mapping) + if start_point == Vector2.INF or end_point == Vector2.INF: + return + + _circle(lines, start_point.x, start_point.y, 4.0, START_COLOR, Color.WHITE, 1.2) + _text_centered( + lines, + "Start", + start_point.x, + start_point.y + 15.0, + 7.5, + true, + START_COLOR + ) + _circle(lines, end_point.x, end_point.y, 4.0, BOARDS_COLOR, Color.WHITE, 1.2) + _text_centered( + lines, + "Ziel", + end_point.x, + end_point.y + 15.0, + 7.5, + true, + BOARDS_COLOR + ) + + +static func _draw_section_start_end( + lines: PackedStringArray, + rows: Array[Dictionary], + mapping: Dictionary +) -> void: + var first: PathSegment = null + var last: PathSegment = null + for row: Dictionary in rows: + var segment: PathSegment = row["segment"] + if segment == null or segment.curve == null: + continue + if segment.curve.point_count == 0: + continue + if first == null: + first = segment + last = segment + if first == null or last == null: + return + var start_point := _segment_start(first, mapping) + var end_point := _segment_end(last, mapping) + _circle(lines, start_point.x, start_point.y, 3.5, START_COLOR, Color.WHITE, 1.0) + _circle(lines, end_point.x, end_point.y, 3.5, BOARDS_COLOR, Color.WHITE, 1.0) + + +static func _segment_start( + segment: PathSegment, + mapping: Dictionary +) -> Vector2: + if segment.curve.point_count == 0: + return Vector2.ZERO + return _map_point(segment.curve.get_point_position(0), mapping) + + +static func _segment_end( + segment: PathSegment, + mapping: Dictionary +) -> Vector2: + if segment.curve.point_count == 0: + return Vector2.ZERO + var length := segment.curve.get_baked_length() + if length > 0.0: + return _map_point(segment.curve.sample_baked(length), mapping) + return _map_point( + segment.curve.get_point_position(segment.curve.point_count - 1), + mapping + ) + + +static func _edge_color(segment: PathSegment) -> Color: + return ( + OUTSIDE_COLOR + if segment.edge == PathSegment.Edge.OUTSIDE + else INSIDE_COLOR + ) + + +static func _element_color(type: PathSegment.ElementType) -> Color: + match type: + PathSegment.ElementType.JUMP: + return JUMP_COLOR + PathSegment.ElementType.SPIN: + return SPIN_COLOR + PathSegment.ElementType.SEQUENCE: + return SEQUENCE_COLOR + return MUTED_COLOR + + +## --- Drawing: tables and notes -------------------------------------------- + + +static func _draw_section_table( + lines: PackedStringArray, + sections: Array[Dictionary], + x: float, + top: float, + width: float, + start_number: int +) -> void: + var number_x := x + 2.0 + var title_x := x + maxf(18.0, width * 0.09) + var start_x := x + width * 0.63 + var duration_x := x + width * 0.84 + var title_width := start_x - title_x - 6.0 + var row_top := top + TABLE_HEADER_HEIGHT + _text(lines, "#", number_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Abschnitt", title_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Start", start_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Dauer", duration_x, top + 12.0, 8.0, true, MUTED_COLOR) + _line(lines, x, row_top, x + width, row_top, RULE_COLOR, 0.7) + + for index: int in range(sections.size()): + var entry: Dictionary = sections[index] + var section: RoutineSection = entry["section"] + var row_y := row_top + float(index) * ROW_HEIGHT + if index % 2 == 1: + _rect(lines, x, row_y, width, ROW_HEIGHT, ROW_COLOR) + var baseline := row_y + 13.0 + _text( + lines, + str(start_number + index + 1), + number_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fit_text(_section_title(section), 8.5, title_width), + title_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fmt_clock(float(entry["start"])), + start_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fmt_clock(float(entry["duration"])), + duration_x, + baseline, + 8.5, + false, + MUTED_COLOR + ) + + +static func _draw_segment_table( + lines: PackedStringArray, + rows: Array[Dictionary], + x: float, + top: float, + width: float +) -> void: + var number_x := x + 2.0 + var start_x := x + width * 0.08 + var end_x := x + width * 0.24 + var duration_x := x + width * 0.40 + var label_x := x + width * 0.52 + var label_width := width - (label_x - x) - 6.0 + var row_top := top + TABLE_HEADER_HEIGHT + _text(lines, "#", number_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Start", start_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Ende", end_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text(lines, "Dauer", duration_x, top + 12.0, 8.0, true, MUTED_COLOR) + _text( + lines, + "Element / Label", + label_x, + top + 12.0, + 8.0, + true, + MUTED_COLOR + ) + _line(lines, x, row_top, x + width, row_top, RULE_COLOR, 0.7) + + for index: int in range(rows.size()): + var row: Dictionary = rows[index] + var row_y := row_top + float(index) * ROW_HEIGHT + if index % 2 == 1: + _rect(lines, x, row_y, width, ROW_HEIGHT, ROW_COLOR) + var baseline := row_y + 13.0 + _text( + lines, + str(int(row["index"])), + number_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fmt_clock(float(row["start"])), + start_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fmt_clock(float(row["end"])), + end_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + _text( + lines, + _fmt_clock(float(row["duration"])), + duration_x, + baseline, + 8.5, + false, + MUTED_COLOR + ) + _text( + lines, + _fit_text(str(row["text"]), 8.5, label_width), + label_x, + baseline, + 8.5, + false, + TEXT_COLOR + ) + + +static func _draw_timeline_notes( + lines: PackedStringArray, + routine: Routine, + x: float, + top: float +) -> void: + var entries: Array[Dictionary] = [] + for entry: Dictionary in routine.timeline_labels: + var text := str(entry.get("text", "")).strip_edges() + if text.is_empty(): + continue + entries.append({ + "time_seconds": float(entry.get("time_seconds", 0.0)), + "text": text, + }) + if entries.is_empty(): + return + entries.sort_custom( + func(a: Dictionary, b: Dictionary) -> bool: + return float(a["time_seconds"]) < float(b["time_seconds"]) + ) + _text(lines, "Timeline-Labels", x, top, 9.5, true, TEXT_COLOR) + var visible := mini(entries.size(), 7) + for index: int in range(visible): + var entry: Dictionary = entries[index] + _text( + lines, + "%s · %s" % [ + _fmt_clock(float(entry["time_seconds"])), + _fit_text(str(entry["text"]), 8.5, 430.0), + ], + x, + top + 16.0 + float(index) * 13.0, + 8.5, + false, + MUTED_COLOR + ) + if entries.size() > visible: + _text( + lines, + "+ %d weitere" % (entries.size() - visible), + x, + top + 16.0 + float(visible) * 13.0, + 8.5, + false, + MUTED_COLOR + ) + + +static func _draw_legend( + lines: PackedStringArray, + x: float, + top: float +) -> void: + var items := [ + {"kind": "line", "color": OUTSIDE_COLOR, "text": "Außen", "dash": false}, + {"kind": "line", "color": INSIDE_COLOR, "text": "Innen", "dash": false}, + {"kind": "line", "color": OUTSIDE_COLOR, "text": "Rückwärts", "dash": true}, + {"kind": "jump", "color": JUMP_COLOR, "text": "Sprung", "dash": false}, + {"kind": "spin", "color": SPIN_COLOR, "text": "Pirouette", "dash": false}, + {"kind": "sequence", "color": SEQUENCE_COLOR, "text": "Sequenz", "dash": false}, + ] + var column_width := 155.0 + for index: int in range(items.size()): + var item: Dictionary = items[index] + var column := index % 3 + var row := index / 3 + var item_x := x + float(column) * column_width + var item_top := top + float(row) * 20.0 + var color: Color = item["color"] + if item["kind"] == "line": + _set_stroke(lines, color, 2.0) + if bool(item["dash"]): + _set_dash(lines, 6.0, 4.0) + else: + _reset_dash(lines) + lines.append( + "%s %s m %s %s l S" + % [ + _n(item_x), + _n(_y(item_top)), + _n(item_x + 18.0), + _n(_y(item_top)), + ] + ) + _reset_dash(lines) + elif item["kind"] == "jump": + _polygon( + lines, + _centered_shape(item_x + 9.0, item_top, 4.0, "jump"), + color, + TEXT_COLOR, + 0.8 + ) + elif item["kind"] == "spin": + _circle(lines, item_x + 9.0, item_top, 4.0, color, TEXT_COLOR, 0.8) + else: + _rect( + lines, + item_x + 5.0, + item_top - 4.0, + 8.0, + 8.0, + color, + TEXT_COLOR, + 0.8 + ) + _text( + lines, + str(item["text"]), + item_x + 24.0, + item_top + 3.0, + 8.5, + false, + MUTED_COLOR + ) + + +static func _centered_shape( + center_x: float, + center_top: float, + radius: float, + kind: String +) -> PackedVector2Array: + if kind == "jump": + return PackedVector2Array([ + Vector2(center_x, center_top - radius), + Vector2(center_x + radius, center_top), + Vector2(center_x, center_top + radius), + Vector2(center_x - radius, center_top), + ]) + return PackedVector2Array() + + +static func _draw_note( + lines: PackedStringArray, + x: float, + top: float, + width: float, + text: String +) -> void: + _rect(lines, x, top, width, 36.0, ROW_COLOR, RULE_COLOR, 0.5) + var wrapped := _wrap_text(text, 8.0, width - 16.0, 2) + for index: int in range(wrapped.size()): + _text( + lines, + wrapped[index], + x + 8.0, + top + 15.0 + float(index) * 13.0, + 8.0, + false, + MUTED_COLOR + ) + + +static func _wrap_text( + text: String, + size: float, + max_width: float, + max_lines: int +) -> PackedStringArray: + var result := PackedStringArray() + var words := text.replace("\n", " ").split(" ", false) + var current := "" + for word: String in words: + var candidate := word if current.is_empty() else current + " " + word + if current.is_empty() or _text_width(candidate, size) <= max_width: + current = candidate + continue + result.append(current) + if result.size() >= max_lines: + return result + current = word + if not current.is_empty() and result.size() < max_lines: + result.append(current) + return result + + +## --- Text encoding and PDF assembly --------------------------------------- + + +static func _fmt_clock(seconds: float) -> String: + var total := maxf(seconds, 0.0) + var minutes := int(total / 60.0) + var remainder := total - float(minutes) * 60.0 + if minutes > 0: + return ("%d:%04.1f" % [minutes, remainder]).replace(".", ",") + return ("%.1f" % remainder).replace(".", ",") + + +static func _n(value: float) -> String: + if absf(value) < 0.0005: + return "0" + return "%.2f" % value + + +static func _y(top: float) -> float: + return PAGE_HEIGHT - top + + +## PDF literal string in WinAnsi. Non-ASCII characters become octal escapes, +## so the complete content stream stays ASCII and its byte length is known. +static func _pdf_literal(text: String) -> String: + var result := "(" + for index: int in range(text.length()): + var codepoint := text.unicode_at(index) + if codepoint == 10 or codepoint == 13: + codepoint = 32 + var byte := _winansi_byte(codepoint) + if byte == 40 or byte == 41 or byte == 92: + result += "\\" + String.chr(byte) + elif byte >= 32 and byte <= 126: + result += String.chr(byte) + else: + result += "\\" + _octal3(byte) + return result + ")" + + +static func _octal3(value: int) -> String: + var clamped := clampi(value, 0, 255) + return "%d%d%d" % [ + (clamped >> 6) & 7, + (clamped >> 3) & 7, + clamped & 7, + ] + + +static func _winansi_byte(codepoint: int) -> int: + match codepoint: + 0x20AC: + return 0x80 + 0x201A: + return 0x82 + 0x0192: + return 0x83 + 0x201E: + return 0x84 + 0x2026: + return 0x85 + 0x2020: + return 0x86 + 0x2021: + return 0x87 + 0x02C6: + return 0x88 + 0x2030: + return 0x89 + 0x0160: + return 0x8A + 0x2039: + return 0x8B + 0x0152: + return 0x8C + 0x017D: + return 0x8E + 0x2018: + return 0x91 + 0x2019: + return 0x92 + 0x201C: + return 0x93 + 0x201D: + return 0x94 + 0x2022: + return 0x95 + 0x2013: + return 0x96 + 0x2014: + return 0x97 + 0x02DC: + return 0x98 + 0x2122: + return 0x99 + 0x0161: + return 0x9A + 0x203A: + return 0x9B + 0x0153: + return 0x9C + 0x017E: + return 0x9E + 0x0178: + return 0x9F + if codepoint >= 0 and codepoint <= 255: + return codepoint + return 63 + + +static func _assemble_pdf(pages: Array[String]) -> PackedByteArray: + var objects: Array[String] = [] + objects.resize(4) + objects[0] = "" + objects[1] = "" + objects[2] = ( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica " + + "/Encoding /WinAnsiEncoding >>" + ) + objects[3] = ( + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold " + + "/Encoding /WinAnsiEncoding >>" + ) + + var page_ids: Array[int] = [] + for content: String in pages: + var content_id := objects.size() + 1 + objects.append( + "<< /Length %d >>\nstream\n%s\nendstream" + % [content.length(), content] + ) + var page_id := objects.size() + 1 + page_ids.append(page_id) + objects.append( + ( + "<< /Type /Page /Parent 2 0 R " + + "/MediaBox [0 0 %s %s] " % [_n(PAGE_WIDTH), _n(PAGE_HEIGHT)] + + "/Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> " + + "/Contents %d 0 R >>" % content_id + ) + ) + + var kids := PackedStringArray() + for page_id: int in page_ids: + kids.append("%d 0 R" % page_id) + objects[0] = "<< /Type /Catalog /Pages 2 0 R >>" + objects[1] = ( + "<< /Type /Pages /Kids [%s] /Count %d >>" + % [" ".join(kids), page_ids.size()] + ) + + var pdf := PackedByteArray() + pdf.append_array("%PDF-1.4\n".to_ascii_buffer()) + var offsets: Array[int] = [] + offsets.resize(objects.size() + 1) + for index: int in range(objects.size()): + var object_id := index + 1 + offsets[object_id] = pdf.size() + pdf.append_array(("%d 0 obj\n" % object_id).to_ascii_buffer()) + pdf.append_array(objects[index].to_ascii_buffer()) + pdf.append_array("\nendobj\n".to_ascii_buffer()) + + var xref_offset := pdf.size() + pdf.append_array( + ("xref\n0 %d\n" % (objects.size() + 1)).to_ascii_buffer() + ) + pdf.append_array("0000000000 65535 f \n".to_ascii_buffer()) + for object_id: int in range(1, objects.size() + 1): + pdf.append_array( + ("%010d 00000 n \n" % offsets[object_id]).to_ascii_buffer() + ) + pdf.append_array( + ("trailer\n<< /Size %d /Root 1 0 R >>\n" % (objects.size() + 1)) + .to_ascii_buffer() + ) + pdf.append_array(("startxref\n%d\n" % xref_offset).to_ascii_buffer()) + pdf.append_array("%%EOF\n".to_ascii_buffer()) + return pdf diff --git a/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd.uid b/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd.uid new file mode 100644 index 0000000..a278afa --- /dev/null +++ b/rinkplanner/src/whiteboard/io/routine_pdf_exporter.gd.uid @@ -0,0 +1 @@ +uid://gcje6vj2h88i diff --git a/rinkplanner/src/whiteboard/view/timeline_label_lane.gd b/rinkplanner/src/whiteboard/view/timeline_label_lane.gd new file mode 100644 index 0000000..aa33834 --- /dev/null +++ b/rinkplanner/src/whiteboard/view/timeline_label_lane.gd @@ -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) + "…" diff --git a/rinkplanner/src/whiteboard/view/timeline_label_lane.gd.uid b/rinkplanner/src/whiteboard/view/timeline_label_lane.gd.uid new file mode 100644 index 0000000..4454be3 --- /dev/null +++ b/rinkplanner/src/whiteboard/view/timeline_label_lane.gd.uid @@ -0,0 +1 @@ +uid://bes3y8h6b6k50 diff --git a/rinkplanner/tests/run_export_tests.gd b/rinkplanner/tests/run_export_tests.gd index 9e9040f..44be76d 100644 --- a/rinkplanner/tests/run_export_tests.gd +++ b/rinkplanner/tests/run_export_tests.gd @@ -102,6 +102,81 @@ func _run() -> void: "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 & "), + "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 controller := scene as WhiteboardController if controller != null: @@ -115,6 +190,49 @@ func _run() -> void: _finish() 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( Vector2(-10.0, 0.0), Vector2(0.0, 0.0), @@ -134,6 +252,46 @@ func _run() -> void: _check(content.contains(" Routine: var routine := Routine.new() routine.routine_id = "export-test" routine.title = "Test & " + routine.timeline_labels = [ + {"time_seconds": 2.5, "text": "Musikstart"}, + ] routine.rink = RinkDimensions.new() var section_one := RoutineSection.new() diff --git a/rinkplanner/tests/run_file_format_tests.gd b/rinkplanner/tests/run_file_format_tests.gd index 480d607..76766fc 100644 --- a/rinkplanner/tests/run_file_format_tests.gd +++ b/rinkplanner/tests/run_file_format_tests.gd @@ -51,6 +51,22 @@ func _test_json_roundtrip() -> void: _check(loaded.routine_id == routine.routine_id, "routine id survives") _check(loaded.title == routine.title, "title survives") _check(loaded.skater_name == routine.skater_name, "skater name survives") + _check(loaded.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_approx( loaded.assumed_pcs_average, @@ -149,6 +165,56 @@ func _test_json_rejects() -> void: "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: var routine := _make_routine() @@ -224,6 +290,11 @@ func _make_routine() -> Routine: routine.routine_id = "format-test" routine.title = "Format Test" 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.assumed_pcs_average = 4.75 routine.assumed_falls = 1 diff --git a/rinkplanner/tests/run_playback_tests.gd b/rinkplanner/tests/run_playback_tests.gd index 0aa8d91..9553bae 100644 --- a/rinkplanner/tests/run_playback_tests.gd +++ b/rinkplanner/tests/run_playback_tests.gd @@ -68,6 +68,48 @@ func _run() -> void: "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) _check(not controller.is_playing(), "seeking does not start playback") _check_vec( @@ -202,6 +244,17 @@ func _run() -> void: 8.0, "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() _check_approx( controller.get_playback_duration(), @@ -235,11 +288,217 @@ func _run() -> void: "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() 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() +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: _assertions += 1 if not condition: diff --git a/rinkplanner/tests/run_sync_tests.gd b/rinkplanner/tests/run_sync_tests.gd index 68d0f90..a51291f 100644 --- a/rinkplanner/tests/run_sync_tests.gd +++ b/rinkplanner/tests/run_sync_tests.gd @@ -121,6 +121,18 @@ func _test_naming() -> void: and not RoutineSync.is_routine_file("sync.cfg"), "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) _check( 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") _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: var scene := WhiteboardScene.instantiate()