feat(pbs): add sprite animation and shared Studio authoring

Implement DEC-0084 with factory-only Sprite/Animator structs, complete result
lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP
authoring through shared services.

Qualify native dev/release with ordinary and optimized producers, zero-allocation
playback, private-cycle reclamation, canonical Composer pixels, installed JARs
and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
2026-11-05 15:16:07 +00:00
parent 1d8b8c2101
commit bf31184d4d
151 changed files with 4823 additions and 98 deletions
@@ -0,0 +1,4 @@
package p.studio.ui.javafx.events;
import java.nio.file.Path;
import java.util.UUID;
public record StudioAnimationOriginRequestedEvent(Path projectRoot,UUID assetUuid,String jsonPointer) implements StudioEvent {}
@@ -46,8 +46,11 @@ public final class MainView extends BorderPane {
private boolean workspaceLifecycleInitialized;
private p.studio.api.operation.OperationSubscription controlSubscription;
private p.studio.api.operation.OperationSubscription documentRegistration;
private p.studio.ui.javafx.events.StudioEventSubscription animationOrigins;
private boolean closed;
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){assetWorkspace.setAnimationService(service);}
public MainView(final ProjectSession projectSession, final Shipper shipper,
final ExecutionControllerFactory executionControllerFactory,
final I18nService i18n,
@@ -92,6 +95,10 @@ public final class MainView extends BorderPane {
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory,
tiledAssetService, sceneBankWorkflow);
animationOrigins=eventBus.subscribe(p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent.class,event->{
if(!event.projectRoot().toAbsolutePath().normalize().equals(projectReference.rootPath()))return;
javafx.application.Platform.runLater(()->{if(!closed){selectWorkspace(WorkspaceId.ASSETS);assetWorkspace.openAnimationOrigin(event.assetUuid(),event.jsonPointer());}});
});
host.register(assetWorkspace);
assetWorkspace.restoreProjectLocalState(persistedState);
assetWorkspace.setStateChangedAction(this::persistProjectLocalState);
@@ -164,6 +171,7 @@ public final class MainView extends BorderPane {
if (closed) return;
closed = true;
controlSubscription.unsubscribe();
if(animationOrigins!=null)animationOrigins.unsubscribe();
documentRegistration.unsubscribe();
playStopCoordinator.shutdown();
persistProjectLocalState();
@@ -77,6 +77,8 @@ public final class StudioWindowCoordinator implements AutoCloseable {
private Stage loadingStage;
private Stage projectStage;
private MainView mainView;
private p.studio.api.assets.animation.AnimationService animationService;
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){this.animationService=service;}
private ProjectSession projectSession;
public StudioWindowCoordinator(
@@ -266,6 +268,7 @@ public final class StudioWindowCoordinator implements AutoCloseable {
assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory,
assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow,
activityHistoryStore, connectionGuide);
if(animationService!=null)mainView.setAnimationService(animationService);
this.projectSession = projectSession;
final Scene scene = new Scene(mainView, PROJECT_WIDTH, PROJECT_HEIGHT);
scene.getStylesheets().add(theme.getDefaultTheme());
@@ -126,6 +126,9 @@ public final class AssetWorkspace extends Workspace {
this.stateChangedAction = java.util.Objects.requireNonNull(stateChangedAction, "stateChangedAction");
}
public void openAnimationOrigin(java.util.UUID bank,String pointer){detailsControl.openAnimationOrigin(bank,pointer);}
public void setAnimationService(p.studio.api.assets.animation.AnimationService service){detailsControl.setAnimationService(service);}
public p.studio.api.automation.DocumentHandoff documentHandoff() { return detailsControl.documentHandoff(); }
public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) {
@@ -78,29 +78,45 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware
private final p.studio.ui.javafx.utilities.i18n.I18nService i18n;
private final p.studio.ui.javafx.utilities.ThemeService theme;
private final AssetCommands assetCommands;
private AssetCatalog animationCatalog;
private java.util.UUID originBank;private String originPointer;
private final AssetDetails assetDetails;
private AssetWorkspaceDetailsViewState viewState = AssetDetailsViewStateFactory.empty();
private p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl animationEditor;
private boolean readyMounted;
private boolean actionRunning;
private String actionFeedbackMessage;
public void openAnimationOrigin(java.util.UUID bank,String pointer){
originBank=bank;originPointer=pointer;
executor.execute(()->{var asset=animationCatalog.list(projectReference,false).stream().filter(a->bank.toString().equals(a.assetUuid())).findFirst();
Platform.runLater(()->asset.ifPresent(a->{loadSelection(a.reference());detailsScroll.setVvalue(1.0);}));});
}
public void setAnimationService(p.studio.api.assets.animation.AnimationService service) {
if(animationEditor!=null)animationEditor.close();
animationEditor=new p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl(projectReference,service,executor);
readyMounted=false;render();
}
public p.studio.api.automation.DocumentHandoff documentHandoff() {
return new p.studio.api.automation.DocumentHandoff() {
private volatile boolean disposed;
private final java.util.Set<java.util.concurrent.CompletableFuture<Void>> pending = java.util.concurrent.ConcurrentHashMap.newKeySet();
@Override public void close() {
disposed = true;
if(animationEditor!=null)onFx(()->{animationEditor.close();return null;});
pending.forEach(future -> future.complete(null));
pending.clear();
}
@Override public java.util.concurrent.CompletionStage<Boolean> hasUnsavedChanges() {
return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft));
return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft))
.thenCompose(formsDirty->animationEditor==null?java.util.concurrent.CompletableFuture.completedFuture(formsDirty):animationEditor.hasUnsavedChanges().thenApply(animationDirty->formsDirty||animationDirty));
}
@Override public java.util.concurrent.CompletionStage<Void> saveAll() {
return onFx(() -> {
java.util.concurrent.CompletionStage<Void> saved = java.util.concurrent.CompletableFuture.completedFuture(null);
for (var form : handoffForms()) saved = saved.thenCompose(v -> form.saveForHandoff());
if(animationEditor!=null)saved=saved.thenCompose(v->animationEditor.saveAll());
return saved;
}).thenCompose(saved -> saved);
}
@@ -112,13 +128,14 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware
onFx(() -> {
if (disposed) { refreshed.complete(null); return null; }
handoffForms().forEach(p.studio.ui.javafx.controls.forms.StudioFormSection::discardDraftForHandoff);
var animationRefresh = animationEditor == null ? java.util.concurrent.CompletableFuture.<Void>completedFuture(null) : animationEditor.refreshFromDisk();
var selected = viewState.selectedAssetReference();
if (selected == null) { refreshed.complete(null); return refreshed; }
if (selected == null) { animationRefresh.whenComplete((v,f)->{if(f==null)refreshed.complete(null);else refreshed.completeExceptionally(f);}); return refreshed; }
long generation = loadGeneration.incrementAndGet();
executor.execute(() -> {
try {
var details = mapDetails(assetDetails.get(projectReference, selected));
Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); refreshed.complete(null); });
Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); animationRefresh.whenComplete((v,f)->{if(f==null)refreshed.complete(null);else refreshed.completeExceptionally(f);}); });
} catch (RuntimeException failure) {
Platform.runLater(() -> { if (!disposed) applyLoadFailure(generation, selected, failure); refreshed.completeExceptionally(failure); });
}
@@ -162,7 +179,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware
this.executor = Objects.requireNonNull(executor, "executor");
this.i18n = Objects.requireNonNull(i18n, "i18n");
this.theme = Objects.requireNonNull(theme, "theme");
this.assetCommands = Objects.requireNonNull(assetCommands, "assetCommands");
this.assetCommands = Objects.requireNonNull(assetCommands, "assetCommands");this.animationCatalog=assetCatalog;
this.assetDetails = Objects.requireNonNull(assetDetails, "assetDetails");
this.studioMetadataService = Objects.requireNonNull(assetMetadataService, "assetMetadataService");
this.tiledGenerationService = Objects.requireNonNull(tiledAssetService, "tiledAssetService");
@@ -365,6 +382,11 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware
sections.add(colorSchemaGroupsControl);
}
sections.add(paletteOverhaulingControl);
if(animationEditor!=null&&viewState.selectedAssetDetails().summary().assetFamily()==AssetFamily.GLYPH_BANK) {
var uuid=viewState.selectedAssetDetails().summary().assetUuid();
boolean bound=animationEditor.bind(uuid==null?null:java.util.UUID.fromString(uuid));sections.add(animationEditor);
if(bound&&uuid!=null&&originBank!=null&&uuid.equals(originBank.toString())){animationEditor.openOrigin(originPointer);originBank=null;originPointer=null;}
}
return sections.toArray(Node[]::new);
}
@@ -778,7 +800,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware
studioMetadata.glyphSpecialization(),
baseSummary.assetRoot(),
baseSummary.preload(),
baseSummary.hasDiagnostics());
baseSummary.hasDiagnostics(), baseSummary.assetUuid());
final AssetWorkspaceBankCompositionDetails bankComposition = mapBankComposition(details.bankComposition());
final var availableCodecs = details.availableOutputCodecs();
final var codecFields = details.codecConfigurationFieldsByCodec();
@@ -21,6 +21,6 @@ public final class AssetListMappings {
AssetStudioGlyphSpecialization.NONE,
summary.root(),
summary.preload(),
summary.hasDiagnostics());
summary.hasDiagnostics(), summary.assetUuid());
}
}
@@ -0,0 +1,127 @@
package p.studio.ui.javafx.workspaces.assets.details.animation;
import javafx.application.Platform;
import javafx.animation.*;
import javafx.util.Duration;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import p.animation.*;
import p.studio.api.assets.animation.AnimationService;
import p.studio.api.automation.DocumentHandoff;
import p.studio.api.project.ProjectReference;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import static p.animation.AnimationDocument.*;
/** Draft editing only. Validation, preview, revision conflicts and writes belong to shared services. */
public final class AnimationEditorControl extends VBox implements DocumentHandoff {
private final ProjectReference project; private final AnimationService service;private final Executor executor;
private final ComboBox<String> animators=new ComboBox<>(),clips=new ComboBox<>(),mode=new ComboBox<>();
private final TextField animatorName=new TextField(),clipName=new TextField(),duration=new TextField("1"),ticks=new TextField("0"),palette=new TextField("0");
private final ComboBox<Binding> glyphs=new ComboBox<>();private final ListView<Frame> frames=new ListView<>();
private final TextArea json=new TextArea(),diagnostics=new TextArea(),rebindDiff=new TextArea();
private final Label status=new Label("Choose a registered glyph bank");private final ImageView image=new ImageView();
private final Spinner<Integer> rate=new Spinner<>(1,60,10);private final ToggleButton play=new ToggleButton("Play");
private final Timeline clock=new Timeline();private final Button save=new Button("Save"),applyRebind=new Button("Apply rebind");
private UUID bank;private AnimationService.View saved;private AnimationDocument draft;private AnimationRebind.Proposal proposal;
private boolean projecting,closed,busy;private long generation;private String cleanText="";private String pendingOrigin;
private CompletionStage<Void> pending=CompletableFuture.completedFuture(null);
public AnimationEditorControl(ProjectReference project,AnimationService service,Executor executor){
super(8);this.project=project;this.service=service;this.executor=executor;
getStyleClass().add("studio-section");setId("animation-editor");
animatorName.setId("animation-id");clipName.setId("animation-clip-name");duration.setId("animation-duration");ticks.setId("animation-ticks");palette.setId("animation-palette");glyphs.setId("animation-glyph");mode.setId("animation-mode");status.setId("animation-status");image.setId("animation-image");json.setId("animation-json");
var title=new Label("Animations");title.getStyleClass().add("assets-workspace-pane-title");
animatorName.setPromptText("Animator ID");clipName.setPromptText("Clip name");mode.getItems().setAll("once","loop");mode.setValue("loop");
animators.setPromptText("Animator");clips.setPromptText("Clip");glyphs.setPromptText("Glyph from this bank");
glyphs.setConverter(new javafx.util.StringConverter<>(){
@Override public String toString(Binding b){return b==null?"":"#"+b.glyphId()+" · "+b.artifactId();}
@Override public Binding fromString(String s){return null;}
});
frames.setPrefHeight(130);frames.setCellFactory(ignored->new ListCell<>(){@Override protected void updateItem(Frame f,boolean empty){super.updateItem(f,empty);setText(empty||f==null?null:f.artifactId()+" · "+f.durationTicks()+" ticks");}});
frames.getSelectionModel().selectedItemProperty().addListener((o,b,f)->{if(f!=null){duration.setText(Long.toString(f.durationTicks()));glyphs.getItems().stream().filter(g->g.artifactId().equals(f.artifactId())).findFirst().ifPresent(glyphs::setValue);}});
animators.valueProperty().addListener((o,b,a)->{if(!projecting)showAnimator();});clips.valueProperty().addListener((o,b,c)->{if(!projecting)showClip();});
mode.valueProperty().addListener((o,b,m)->{if(!projecting&&selectedClip()!=null)editClip(c->new Clip(c.name(),m,c.frames()));});
json.setPrefRowCount(6);json.setWrapText(false);diagnostics.setPrefRowCount(3);diagnostics.setEditable(false);diagnostics.setWrapText(true);
rebindDiff.setPrefRowCount(3);rebindDiff.setEditable(false);
image.setFitWidth(160);image.setFitHeight(160);image.setPreserveRatio(true);image.setSmooth(false);
var animRow=row(animators,animatorName,button("New animator",this::addAnimator),button("Rename",this::renameAnimator),button("Delete",this::deleteAnimator));
var clipRow=row(clips,clipName,mode,button("New clip",this::addClip),button("Rename",this::renameClip),button("Delete",this::deleteClip),button("Use as initial",this::setInitial));
var frameRow=row(glyphs,new Label("Ticks"),duration,button("Add frame",()->putFrame(false)),button("Update",()->putFrame(true)),button("Remove",this::removeFrame),button("Up",()->moveFrame(-1)),button("Down",()->moveFrame(1)));
save.setOnAction(e->saveAll().exceptionally(failure->{Platform.runLater(()->report(failure));return null;}));applyRebind.setOnAction(e->applyRebind());applyRebind.setDisable(true);
var documentRow=row(save,button("Validate draft",this::validateDraft),button("Reload",this::refreshFromDisk),button("Read JSON draft",this::readJsonDraft),status);
var previewRow=row(play,button("Step",()->step(1)),new Label("Elapsed ticks"),ticks,new Label("Palette"),palette,new Label("Preview ticks/s"),rate,button("Preview",this::preview));
play.setOnAction(e->{if(play.isSelected()){clock.getKeyFrames().setAll(new KeyFrame(Duration.millis(1000.0/rate.getValue()),event->step(1)));clock.setCycleCount(Animation.INDEFINITE);clock.play();}else clock.stop();});
disabledProperty().addListener((o,b,disabled)->{if(disabled){clock.stop();play.setSelected(false);}});
getChildren().setAll(title,animRow,clipRow,frames,frameRow,previewRow,image,documentRow,diagnostics,new TitledPane("Canonical JSON / repair",json),row(button("Prepare rebind",this::prepareRebind),applyRebind),rebindDiff);
setDisable(true);
}
private static FlowPane row(javafx.scene.Node... nodes) {
var row = new FlowPane(6, 6, nodes);
for (var node : nodes) {
if (node instanceof TextField field) field.setPrefColumnCount(10);
if (node instanceof ComboBox<?> combo) combo.setPrefWidth(180);
}
return row;
}
private Button button(String text,Runnable action){var b=new Button(text);b.setOnAction(e->{try{if(!busy)action.run();}catch(RuntimeException failure){report(failure);}});return b;}
public boolean bind(UUID next){
if(Objects.equals(bank,next)&&saved!=null)return true;
if(busy){status.setText("Wait for the current bank operation before changing banks");return false;}
if(hasDraft()){status.setText("Save or reload the animation draft for "+bank+" before changing banks");return false;}
clock.stop();play.setSelected(false);generation++;bank=next;saved=null;draft=null;cleanText="";projecting=true;json.clear();projecting=false;
setDisable(next==null);if(next!=null)refreshFromDisk();return true;
}
private boolean hasDraft(){return !json.getText().equals(cleanText);}
private Animator selectedAnimator(){return draft==null?null:draft.animators().stream().filter(a->a.id().equals(animators.getValue())).findFirst().orElse(null);}
private Clip selectedClip(){var a=selectedAnimator();return a==null?null:a.clips().stream().filter(c->c.name().equals(clips.getValue())).findFirst().orElse(null);}
private void showAnimator(){var a=selectedAnimator();projecting=true;String old=clips.getValue();clips.getItems().setAll(a==null?List.of():a.clips().stream().map(Clip::name).toList());if(a!=null){animatorName.setText(a.id());clips.setValue(clips.getItems().contains(old)?old:a.initialClip());}projecting=false;showClip();}
private void showClip(){var c=selectedClip();projecting=true;frames.getItems().setAll(c==null?List.of():c.frames());if(c!=null){clipName.setText(c.name());mode.setValue(c.mode());}projecting=false;}
private void changed(){json.setText(new AnimationCodec().encode(draft));status.setText("Unsaved draft");proposal=null;applyRebind.setDisable(true);}
private void replaceAnimator(Animator before,Animator after){var values=new ArrayList<>(draft.animators());int i=values.indexOf(before);if(i>=0)values.set(i,after);else values.add(after);draft=new AnimationDocument(1,draft.bankAssetUuid(),draft.bindings(),values);projecting=true;animators.getItems().setAll(values.stream().map(Animator::id).toList());animators.setValue(after.id());projecting=false;changed();showAnimator();}
private void editClip(UnaryOperator<Clip> edit){var a=selectedAnimator();var old=selectedClip();if(a==null||old==null)return;var next=edit.apply(old);var values=new ArrayList<>(a.clips());values.set(values.indexOf(old),next);String initial=a.initialClip().equals(old.name())?next.name():a.initialClip();replaceAnimator(a,new Animator(a.id(),initial,values));clips.setValue(next.name());}
private void addAnimator(){if(draft==null)return;replaceAnimator(null,new Animator(animatorName.getText(),"idle",List.of(new Clip("idle","loop",List.of()))));}
private void renameAnimator(){var a=selectedAnimator();if(a!=null)replaceAnimator(a,new Animator(animatorName.getText(),a.initialClip(),a.clips()));}
private void deleteAnimator(){var a=selectedAnimator();if(a==null)return;var values=new ArrayList<>(draft.animators());values.remove(a);draft=new AnimationDocument(1,draft.bankAssetUuid(),draft.bindings(),values);projecting=true;animators.getItems().setAll(values.stream().map(Animator::id).toList());animators.setValue(values.isEmpty()?null:values.getFirst().id());projecting=false;changed();showAnimator();}
private void addClip(){var a=selectedAnimator();if(a==null)return;var values=new ArrayList<>(a.clips());values.add(new Clip(clipName.getText(),mode.getValue(),List.of()));replaceAnimator(a,new Animator(a.id(),a.initialClip(),values));clips.setValue(clipName.getText());}
private void renameClip(){editClip(c->new Clip(clipName.getText(),c.mode(),c.frames()));}
private void deleteClip(){var a=selectedAnimator();var c=selectedClip();if(a==null||c==null)return;var values=new ArrayList<>(a.clips());values.remove(c);replaceAnimator(a,new Animator(a.id(),a.initialClip(),values));}
private void setInitial(){var a=selectedAnimator();if(a!=null&&clips.getValue()!=null)replaceAnimator(a,new Animator(a.id(),clips.getValue(),a.clips()));}
private void putFrame(boolean update){var glyph=glyphs.getValue();if(glyph==null)return;long value=Long.parseLong(duration.getText());int index=frames.getSelectionModel().getSelectedIndex();editClip(c->{var values=new ArrayList<>(c.frames());var next=new Frame(glyph.artifactId(),value);if(update&&index>=0)values.set(index,next);else values.add(next);return new Clip(c.name(),c.mode(),values);});}
private void removeFrame(){int index=frames.getSelectionModel().getSelectedIndex();if(index>=0)editClip(c->{var values=new ArrayList<>(c.frames());values.remove(index);return new Clip(c.name(),c.mode(),values);});}
private void moveFrame(int delta){int index=frames.getSelectionModel().getSelectedIndex();var c=selectedClip();if(c==null||index<0||index+delta<0||index+delta>=c.frames().size())return;editClip(old->{var values=new ArrayList<>(old.frames());Collections.swap(values,index,index+delta);return new Clip(old.name(),old.mode(),values);});frames.getSelectionModel().select(index+delta);}
private void readJsonDraft(){draft=new AnimationCodec().decode(json.getText());String selected=animators.getValue();projecting=true;animators.getItems().setAll(draft.animators().stream().map(Animator::id).toList());animators.setValue(animators.getItems().contains(selected)?selected:animators.getItems().stream().findFirst().orElse(null));projecting=false;showAnimator();validateDraft();}
private AnimationService.Request request(AnimationService.Operation operation,AnimationDocument doc){return new AnimationService.Request(operation,project,bank,animators.getValue(),clips.getValue(),operation==AnimationService.Operation.PREVIEW?Long.parseLong(ticks.getText()):null,operation==AnimationService.Operation.PREVIEW?Integer.parseInt(palette.getText()):null,saved==null?null:saved.revision(),doc,proposal==null?null:proposal.proposalHash(),proposal==null?null:proposal.bankRevision());}
private void validateDraft(){call(request(AnimationService.Operation.VALIDATE,new AnimationCodec().decode(json.getText())),response->showDiagnostics(response.diagnostics()));}
private void preview(){if(bank==null||busy)return;call(request(AnimationService.Operation.PREVIEW,new AnimationCodec().decode(json.getText())),response->{if(response.preview()!=null){image.setImage(new Image(new java.io.ByteArrayInputStream(response.preview().image().png())));status.setText(response.preview().observation().state()+" · glyph "+response.preview().observation().glyphId()+" · phase "+response.preview().observation().phase());}showDiagnostics(response.diagnostics());});}
private void step(int value){if(busy)return;try{ticks.setText(Long.toString(Math.addExact(Long.parseLong(ticks.getText()),value)));preview();}catch(RuntimeException failure){clock.stop();play.setSelected(false);report(failure);}}
private void prepareRebind(){if(hasDraft()){status.setText("Save or reload the draft before preparing rebind");return;}call(request(AnimationService.Operation.PREPARE_REBIND,null),response->{proposal=response.proposal();rebindDiff.setText(proposal==null?"":proposal.differences().toString());applyRebind.setDisable(proposal==null||!response.diagnostics().isEmpty());showDiagnostics(response.diagnostics());});}
private void applyRebind(){if(proposal!=null)call(request(AnimationService.Operation.APPLY_REBIND,proposal.document()),response->loaded(response.view()));}
private void loaded(AnimationService.View view){
if(view==null)return;saved=view;draft=view.document();glyphs.getItems().setAll(view.availableBindings());
if(draft==null&&view.revision()==null)draft=new AnimationDocument(1,bank.toString(),view.availableBindings(),List.of());
String source=view.document()==null&&view.revision()!=null?view.json():new AnimationCodec().encode(draft);
json.setText(source);cleanText=source;projecting=true;animators.getItems().setAll(draft==null?List.of():draft.animators().stream().map(Animator::id).toList());animators.getSelectionModel().selectFirst();projecting=false;showAnimator();showDiagnostics(view.diagnostics());status.setText(view.revision()==null?"New definition":"Saved definition");if(pendingOrigin!=null){String pointer=pendingOrigin;pendingOrigin=null;openOrigin(pointer);}
}
private void showDiagnostics(List<AnimationDiagnostic> values){diagnostics.setText(values.stream().map(d->d.pointer()+" · "+d.message()).collect(java.util.stream.Collectors.joining("\n")));}
private void report(Throwable failure){diagnostics.setText(failure.getMessage());status.setText("Draft retained; operation failed");}
private CompletionStage<Void> call(AnimationService.Request request,Consumer<AnimationService.Response> apply){
long version=generation;busy=true;save.setDisable(true);var done=new CompletableFuture<Void>();pending=done;
CompletableFuture.supplyAsync(()->service.execute(request),executor).whenComplete((response,failure)->Platform.runLater(()->{
if(closed||version!=generation){done.complete(null);return;}busy=false;save.setDisable(false);
if(failure!=null){var cause=failure instanceof CompletionException?failure.getCause():failure;report(cause);done.completeExceptionally(cause);}
else{try{apply.accept(response);done.complete(null);}catch(RuntimeException error){report(error);done.completeExceptionally(error);}}
}));return done;
}
private static <T> CompletionStage<T> fx(Supplier<T> action){var result=new CompletableFuture<T>();Runnable run=()->{try{result.complete(action.get());}catch(Throwable error){result.completeExceptionally(error);}};if(Platform.isFxApplicationThread())run.run();else Platform.runLater(run);return result;}
@Override public CompletionStage<Boolean> hasUnsavedChanges(){return fx(this::hasDraft);}
@Override public CompletionStage<Void> saveAll(){if(busy)return pending.thenCompose(v->saveAll());return fx(()->{if(bank==null||!hasDraft())return CompletableFuture.<Void>completedFuture(null);var doc=new AnimationCodec().decode(json.getText());String submitted=json.getText();return call(AnimationService.Request.save(project,bank,saved==null?null:saved.revision(),doc),response->{
if(json.getText().equals(submitted))loaded(response.view());
else{saved=response.view();cleanText=saved.json();status.setText("Saved earlier draft; current edits retained");}
});}).thenCompose(v->v);}
@Override public CompletionStage<Void> refreshFromDisk(){return fx(()->{if(busy)return pending.thenCompose(v->refreshFromDisk());if(bank==null)return CompletableFuture.<Void>completedFuture(null);clock.stop();play.setSelected(false);return call(AnimationService.Request.get(project,bank),response->loaded(response.view()));}).thenCompose(v->v);}
public void openOrigin(String pointer){if(draft==null){pendingOrigin=pointer;return;}String[] parts=pointer.split("/");try{if(parts.length>2){animators.setValue(draft.animators().get(Integer.parseInt(parts[2])).id());if(parts.length>4){clips.setValue(selectedAnimator().clips().get(Integer.parseInt(parts[4])).name());if(parts.length>6)frames.getSelectionModel().select(Integer.parseInt(parts[6]));}}json.requestFocus();}catch(IndexOutOfBoundsException|NumberFormatException ignored){status.setText("Source changed; choose the current definition");}}
@Override public void close(){closed=true;generation++;clock.stop();play.setSelected(false);pending.toCompletableFuture().complete(null);}
}