feat(studio): ship JavaFX 2 Play and delegate integration tooling
Test / Tests and coverage occurred while executing withChecks step.
Intrepid/Prometeu/Studio/pipeline/head There was a failure building this commit

Launch the JavaFX 2 project shell on Java 25 with an interactive viewport,
managed Play lifecycle and project mutation guards. Preserve headless/MCP and
save compatibility, and qualify exact runtime executable bundles.
Separate unit JaCoCo gates from opt-in integration suites and use the internal
Pong fixture for the headless visual pilot.
Move maintenance and native conformance tools into tooling; retain the VS Code
extension and update current navigation links.

Validation: tooling make verify passed, including 1064 Studio unit tests,
JaCoCo thresholds and 22 headless integration tests.
This commit is contained in:
2026-11-19 17:32:03 +00:00
parent 1e17fc4d67
commit 71fb80efc3
163 changed files with 5929 additions and 4950 deletions
@@ -5,11 +5,11 @@ import javafx.stage.Stage;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import p.studio.ui.javafx.window.StudioWindowCoordinator;
import p.studio.ui.javafx2.window.StudioWindowCoordinator2;
public class App extends Application {
private ConfigurableApplicationContext applicationContext;
private StudioWindowCoordinator studioWindowCoordinator;
private StudioWindowCoordinator2 studioWindowCoordinator;
@Override
public void init() throws Exception {
@@ -18,11 +18,12 @@ public class App extends Application {
.web(WebApplicationType.NONE)
.headless(false)
.run();
applicationContext.getBean(StudioUiFactory.class).prepareInteractive();
}
@Override
public void start(Stage stage) {
studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).create(stage);
studioWindowCoordinator = applicationContext.getBean(StudioUiFactory.class).createInteractive(stage);
studioWindowCoordinator.showLauncher();
}
@@ -323,7 +323,9 @@ public class StudioApplicationConfiguration {
TiledAssetService tiledAssetService,
SceneBankWorkflow sceneBankWorkflow,
WindowStateStore windowStateStore,
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) {
ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide,
p.studio.api.assets.animation.AnimationService animationService,ObjectMapper mapper,OperationExecutor operations,
p.studio.core.project.ProjectAccessRegistry access,ProjectLocalStudioSetupStore setupStore) {
var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory,
executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper,
assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService,
@@ -331,6 +333,9 @@ public class StudioApplicationConfiguration {
tiledAssetService, sceneBankWorkflow, windowStateStore,
activityHistoryStore, connectionGuide);
factory.setAnimationService(animationService);
factory.enableInteractive(new p.studio.core.execution.DefaultExecutionControllerFactory(shipper,
new p.studio.app.runtime.studio.StudioRuntimeGateway(mapper),operations,access),
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setupStore.save(project,setup);}});
return factory;
}
@@ -31,6 +31,19 @@ import p.studio.ui.javafx.utilities.i18n.I18nService;
import p.studio.ui.javafx.events.StudioEventBus;
public final class StudioUiFactory {
private ExecutionControllerFactory interactiveExecutions;
private java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> setupSaver;
private p.studio.ui.javafx2.window.WindowResources interactiveResources;
public void enableInteractive(ExecutionControllerFactory factory,
java.util.function.BiConsumer<p.studio.api.project.ProjectReference,p.studio.api.project.ProjectLocalStudioSetup> saver) {
interactiveExecutions=Objects.requireNonNull(factory);setupSaver=Objects.requireNonNull(saver);
}
public void prepareInteractive(){interactiveResources=new p.studio.ui.javafx2.window.WindowResources();}
public p.studio.ui.javafx2.window.StudioWindowCoordinator2 createInteractive(Stage stage){
if(interactiveResources==null)throw new IllegalStateException("Interactive resources were not initialized");
return new p.studio.ui.javafx2.window.StudioWindowCoordinator2(stage,projectCatalog,knownProjects,projectSessionFactory,
Objects.requireNonNull(interactiveExecutions),setupSaver,executor,interactiveResources);
}
private final ProjectCatalog projectCatalog;
private final KnownProjects knownProjects;
private final ProjectLanguageCatalog languageCatalog;
@@ -5,35 +5,55 @@ import p.studio.api.assets.AssetBudgets.*;
import p.studio.api.project.ProjectLocalStudioSetup;
import java.nio.file.*;
import java.util.*;
import java.io.InputStream;
import java.util.function.Function;
/** Installed resource profiles only. Ordinary builds never inspect a sibling runtime checkout. */
public final class AssetCapacityProfiles {
public record Bundle(Profile profile,Map<String,String> executables){}
public record Catalog(int schemaVersion,List<Bundle> profiles){}
private final ObjectMapper json;
public AssetCapacityProfiles(ObjectMapper json){this.json=json;}
private static final Set<String> EXECUTABLES = Set.of("prometeu", "prometeu-headless", "prometeu-runtime");
private final Function<String, InputStream> resources;
public AssetCapacityProfiles(ObjectMapper json){this(json, name -> AssetCapacityProfiles.class.getClassLoader().getResourceAsStream(name));}
AssetCapacityProfiles(ObjectMapper json, Function<String, InputStream> resources){this.json=json;this.resources=resources;}
public ProfileSelection select(ProjectLocalStudioSetup setup) {
if(setup==null||setup.prometeuRuntimePath()==null)return ProfileSelection.unknown(null,"No runtime installation selected");
String selected=null;
try {
Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=System.getProperty("os.name").startsWith("Windows")?"prometeu.exe":"prometeu";
Path root=Path.of(setup.prometeuRuntimePath()).toRealPath();String dispatcher=executable("prometeu");
selected=AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(dispatcher)));
try(var stream=getClass().getResourceAsStream("/asset-capacity/catalog.json")) {
var actual = new HashMap<String, String>();
actual.put("prometeu", selected);
String mismatch = null;
try(var stream=resources.apply("asset-capacity/catalog.json")) {
if(stream==null)return ProfileSelection.unknown(selected,"No distributed capacity profiles");
var catalog=json.readValue(stream,Catalog.class);if(catalog.schemaVersion()!=1)throw new IllegalArgumentException("Unsupported profile catalog");
for(var bundle:catalog.profiles())if(bundle.profile().executableSha256().equals(selected)) {
if(!bundle.executables().keySet().containsAll(Set.of("prometeu","prometeu-headless","prometeu-runtime")))throw new IllegalArgumentException("Incomplete executable identity");
if(!bundle.executables().keySet().equals(EXECUTABLES))throw new IllegalArgumentException("Incomplete or unsupported executable identity");
String changed = null;
for(var entry:bundle.executables().entrySet()) {
if(!Set.of("prometeu","prometeu-headless","prometeu-runtime").contains(entry.getKey()))throw new IllegalArgumentException("Unsupported executable identity");
if(!AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(entry.getKey()))).equals(entry.getValue()))return ProfileSelection.unknown(selected,"Runtime component changed: "+entry.getKey());
String hash = actual.get(entry.getKey());
if(hash == null) {
hash = AssetWorkspaceFiles.hash(Files.readAllBytes(root.resolve(executable(entry.getKey()))));
actual.put(entry.getKey(), hash);
}
if(!hash.equals(entry.getValue())) { changed = entry.getKey(); break; }
}
for(var evidence:bundle.profile().evidence())try(var record=getClass().getClassLoader().getResourceAsStream(evidence.evidencePath())) {
// Several qualified releases may legitimately share an unchanged dispatcher.
// Never combine backend identities from separate catalog entries.
if(changed != null) { mismatch = "Runtime component changed: " + changed + "; no complete qualified bundle matched"; continue; }
for(var evidence:bundle.profile().evidence())try(var record=resources.apply(evidence.evidencePath())) {
if(record==null||!AssetWorkspaceFiles.hash(record.readAllBytes()).equals(evidence.evidenceSha256()))throw new IllegalArgumentException("Capacity evidence integrity mismatch");
}
return new ProfileSelection(QualificationState.known,selected,bundle.profile(),"Exact qualified dispatcher and runtime components match");
}
}
if(mismatch != null)return ProfileSelection.unknown(selected,mismatch);
return ProfileSelection.unknown(selected,"Selected executable has no qualified capacity profile");
}catch(Exception invalid){return ProfileSelection.unknown(selected,"Capacity profile unavailable or invalid: "+Objects.requireNonNullElse(invalid.getMessage(),invalid.getClass().getSimpleName()));}
}
private static String executable(String name) {
return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : "");
}
}
@@ -0,0 +1,48 @@
package p.studio.app.runtime.studio;
import p.studio.api.execution.ExecutionFrame;
import java.io.IOException;
import java.util.ArrayDeque;
/** Three CPU buffers; at most one presentation lease, independent of reception. */
final class LatestFramePool implements AutoCloseable {
private final int width,height;
private final ArrayDeque<byte[]> free=new ArrayDeque<>(3);
private Pending pending;
private boolean leased,closed;
private record Pending(byte[] pixels,long id,long epoch,long receivedAt) { }
LatestFramePool(int width,int height)throws IOException {
this.width=width;this.height=height;
int size=StudioWire.frameBytes(width,height,width);
for(int i=0;i<3;i++)free.add(new byte[size]);
}
synchronized byte[] receive()throws IOException {
if(closed)throw new IOException("Video pool closed");
byte[] pixels=free.poll();
if(pixels==null)throw new IOException("Video ownership exhausted");
return pixels;
}
synchronized void recycle(byte[] pixels){if(!closed)free.add(pixels);}
synchronized void publish(byte[] pixels,long id,long epoch){
publish(pixels,id,epoch,System.nanoTime());
}
synchronized void publish(byte[] pixels,long id,long epoch,long receivedAt){
if(closed)return;
if(pending!=null)free.add(pending.pixels());
pending=new Pending(pixels,id,epoch,receivedAt);
}
synchronized ExecutionFrame acquire(){
if(closed||leased||pending==null)return null;
Pending owned=pending;pending=null;leased=true;
return new ExecutionFrame(width,height,owned.id(),owned.epoch(),owned.pixels(),owned.receivedAt(),()->{
synchronized(this){leased=false;if(!closed)free.add(owned.pixels());}
});
}
@Override public synchronized void close(){closed=true;pending=null;free.clear();}
static void rgbaToBgraPre(byte[] pixels){
for(int i=0;i<pixels.length;i+=4){
int r=pixels[i]&255,g=pixels[i+1]&255,b=pixels[i+2]&255,a=pixels[i+3]&255;
pixels[i]=(byte)((b*a+127)/255);pixels[i+1]=(byte)((g*a+127)/255);pixels[i+2]=(byte)((r*a+127)/255);
}
}
}
@@ -0,0 +1,205 @@
package p.studio.app.runtime.studio;
import p.studio.api.execution.*;
import p.studio.api.runtime.RuntimeLogEntry;
import p.studio.core.runtime.*;
import java.io.*;
import java.net.Socket;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.Consumer;
import static p.studio.app.runtime.studio.StudioWire.*;
import p.studio.app.runtime.studio.StudioWire.Reader;
import p.studio.app.runtime.studio.StudioWire.Writer;
final class StudioRuntimeConnection implements RuntimeConnection {
private final Process process;
private final Socket control,video;
private final Reader controlReader,videoReader;
private final Writer writer;
private final byte[] session;
private final int width,height;
private final LatestFramePool frames;
private final Consumer<RuntimeLogEntry> logs;
private final Executor executor;
private final CompletableFuture<Integer> completion=new CompletableFuture<>();
private final CompletableFuture<Void> stopped=new CompletableFuture<>();
private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{
Thread t=new Thread(r,"studio-play-heartbeat");t.setDaemon(true);return t;
});
private final ArrayBlockingQueue<Packet> outgoing=new ArrayBlockingQueue<>(256);
private final ConcurrentMap<Long,Pending> pending=new ConcurrentHashMap<>();
private final AtomicBoolean closing=new AtomicBoolean(),failed=new AtomicBoolean();
private final AtomicLong epoch=new AtomicLong(1);
private final AtomicInteger state=new AtomicInteger();
private final List<CompletableFuture<Void>> workers=new ArrayList<>();
private volatile long lastControl=System.nanoTime();
private volatile Throwable failure;
private volatile boolean expectedEnd;
private long nextRequest;
private volatile long stopRequest;
private CompletableFuture<Void> stopResult;
private record Packet(int kind,long request,byte[] payload) { }
private record Pending(int kind,long deadline,CompletableFuture<Void> result) { }
StudioRuntimeConnection(Process process,Socket control,Socket video,Reader controlReader,Reader videoReader,
byte[] session,int width,int height,Consumer<RuntimeLogEntry> logs,Executor executor,
CompletableFuture<Void> stdout,CompletableFuture<Void> stderr)throws IOException {
this.process=process;this.control=control;this.video=video;this.controlReader=controlReader;this.videoReader=videoReader;
this.session=session.clone();this.width=width;this.height=height;this.logs=logs;this.executor=executor;
writer=new Writer(control.getOutputStream());frames=new LatestFramePool(width,height);
workers.add(CompletableFuture.runAsync(this::writeLoop,executor));
workers.add(CompletableFuture.runAsync(this::controlLoop,executor));
workers.add(CompletableFuture.runAsync(this::videoLoop,executor));
timer.scheduleAtFixedRate(this::heartbeat,1,1,TimeUnit.SECONDS);
executor.execute(()->{
try{
int code=process.waitFor();
// Drain the terminal control message before closing the other channel.
// TCP ordering is per channel; video EOF can race STOPPED on control.
if(code==0&&stopRequest!=0&&!failed.get()){
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception missing){fail(new IOException("Runtime exited without STOPPED",missing));}
}
closing.set(true);state.set(4);timer.shutdownNow();closeSockets();frames.close();
for(Pending p:pending.values())p.result().completeExceptionally(new IOException("Runtime exited"));pending.clear();
for(var worker:workers)await(worker);await(stdout);await(stderr);
logs.accept(code==0?RuntimeLogEntry.info("Runtime stopped."):RuntimeLogEntry.error("Runtime exit code "+code));
Throwable why=failure;
if(why==null)completion.complete(code);else completion.completeExceptionally(why);
if(!stopped.isDone())stopped.completeExceptionally(why==null?new IOException("Runtime exited before STOPPED"):why);
}catch(InterruptedException interrupted){Thread.currentThread().interrupt();fail(interrupted);completion.completeExceptionally(interrupted);}
});
}
@Override public CompletableFuture<Integer> completion(){return completion;}
@Override public CompletableFuture<Void> startExecution(){return command(START);}
@Override public CompletableFuture<Void> pause(){return command(PAUSE);}
@Override public CompletableFuture<Void> resume(){return command(RESUME);}
@Override public synchronized CompletableFuture<Void> stopAsync(){
if(completion.isDone())return completion.thenApply(code->{if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return null;});
if(stopResult!=null)return stopResult;
CompletableFuture<Void> accepted=command(STOP);
stopResult=accepted.thenCompose(v->stopped).thenCompose(v->completion).thenApply(code->{
if(code!=0)throw new CompletionException(new IOException("Runtime exit "+code));return (Void)null;
}).orTimeout(5,TimeUnit.SECONDS);
CompletableFuture<Void> result=stopResult;
result.whenComplete((v,e)->{
Throwable why=root(e);
if(why instanceof RuntimeStopRefusedException){synchronized(this){if(stopResult==result)stopResult=null;}}
else if(e!=null)fail(why);
});
return result;
}
@Override public void close(){try{stopAsync().join();}catch(CompletionException e){
if(root(e) instanceof RuntimeException runtime)throw runtime;throw e;}}
@Override public ExecutionFrame acquireLatestFrame(){return frames.acquire();}
@Override public void input(ExecutionInput input){
if(state.get()!=1||closing.get()||failed.get())return;
if((input.buttons()&4096)!=0&&(input.touchX()<0||input.touchY()<0||input.touchX()>=width||input.touchY()>=height))
throw new IllegalArgumentException("Touch outside game image");
enqueue(new Packet(INPUT,0,little(20).putLong(epoch.get()).putShort((short)input.buttons()).putShort((short)0)
.putInt(input.touchX()).putInt(input.touchY()).array()));
}
private synchronized CompletableFuture<Void> command(int kind){
if(closing.get()||failed.get())return CompletableFuture.failedFuture(new IOException("Runtime connection closed"));
long id=++nextRequest;
if(kind==STOP)stopRequest=id;
var future=new CompletableFuture<Void>();
pending.put(id,new Pending(kind,System.nanoTime()+TimeUnit.SECONDS.toNanos(5),future));
enqueue(new Packet(kind,id,new byte[0]));return future;
}
private void enqueue(Packet packet){if(!outgoing.offer(packet))fail(new IOException("Runtime control queue saturated"));}
private void writeLoop(){
try{while(!closing.get()&&!failed.get()){
Packet p=outgoing.poll(100,TimeUnit.MILLISECONDS);if(p!=null)writer.send(p.kind(),p.request(),p.payload());
}}catch(InterruptedException e){Thread.currentThread().interrupt();if(!closing.get())fail(e);}
catch(IOException e){if(!closing.get()&&!expectedEnd)fail(e);}
}
private void controlLoop(){
try{while(!closing.get()){
Message m=controlReader.receive();lastControl=System.nanoTime();
switch(m.header().kind()){
case RESULT->result(m);
case PONG->{
if(m.payload().length!=20||m.header().request()!=0)throw new IOException("Invalid PONG");
var p=ByteBuffer.wrap(m.payload()).order(ByteOrder.LITTLE_ENDIAN);
long e=p.getLong();p.getLong();int s=p.getInt();
if(e==0||s<0||s>2)throw new IOException("Invalid PONG state");
}
case ERROR->{String text=text(m.payload(),0);logs.accept(RuntimeLogEntry.error(text));fail(new IOException(text));return;}
case STOPPED->{if(m.payload().length!=0||m.header().request()!=stopRequest||stopRequest==0)
throw new IOException("Unexpected STOPPED");expectedEnd=true;stopped.complete(null);return;}
default->throw new IOException("Unexpected runtime control message");
}
}}catch(IOException|RuntimeException e){if(!closing.get()&&!expectedEnd)fail(e);}
}
private void result(Message message)throws IOException {
byte[] p=message.payload();if(p.length<20)throw new IOException("Invalid command result");
var b=ByteBuffer.wrap(p).order(ByteOrder.LITTLE_ENDIAN);
int kind=Short.toUnsignedInt(b.getShort()),status=Short.toUnsignedInt(b.getShort());
long nextEpoch=b.getLong();b.getLong();String text=text(p,20);
Pending request=pending.remove(message.header().request());
if(request==null||request.kind()!=kind||status>2||nextEpoch==0)throw new IOException("Uncorrelated runtime result");
epoch.set(nextEpoch);
if(status==0){switch(kind){
case START->state.compareAndSet(0,1);case RESUME->state.set(1);case PAUSE,STOP->state.set(2);default->{}}
request.result().complete(null);
}else if(status==2&&kind==STOP){state.set(2);stopRequest=0;request.result().completeExceptionally(new RuntimeStopRefusedException(text));}
else request.result().completeExceptionally(new IllegalStateException(text));
}
private void videoLoop(){
byte[] metadata=new byte[FRAME_METADATA_BYTES];
try{while(!closing.get()){
Header h=videoReader.nextHeader();
if(h.kind()!=FRAME||h.length()<FRAME_METADATA_BYTES||h.request()!=0)throw new IOException("Invalid frame envelope");
videoReader.readFully(metadata,0,metadata.length);
if(!Arrays.equals(session,Arrays.copyOfRange(metadata,0,16)))throw new IOException("Frame belongs to another session");
var b=ByteBuffer.wrap(metadata).order(ByteOrder.LITTLE_ENDIAN);b.position(16);
long frameEpoch=b.getLong(),id=b.getLong();int w=b.getInt(),height=b.getInt(),stride=b.getInt(),format=b.getInt();
int bytes=frameBytes(w,height,stride);
if(w!=width||height!=this.height||format!=RGBA8||frameEpoch==0||bytes+FRAME_METADATA_BYTES!=h.length())
throw new IOException("Frame metadata changed or mismatches payload");
byte[] pixels=frames.receive();boolean published=false;
try{
videoReader.readFully(pixels,0,pixels.length);
long receivedAt=System.nanoTime();
if(Long.compareUnsigned(frameEpoch,epoch.get())>=0){
LatestFramePool.rgbaToBgraPre(pixels);frames.publish(pixels,id,frameEpoch,receivedAt);published=true;
}
enqueue(new Packet(FRAME_RECEIVED,0,little(16).putLong(frameEpoch).putLong(id).array()));
}finally{if(!published)frames.recycle(pixels);}
}}catch(IOException|RuntimeException e){
if(!closing.get()&&!expectedEnd){
if(stopRequest!=0){
try{stopped.get(2,TimeUnit.SECONDS);}catch(Exception incomplete){if(!closing.get()&&!expectedEnd)fail(e);}
}else fail(e);
}
}
}
private void heartbeat(){
if(closing.get()||failed.get())return;
long now=System.nanoTime();
if(now-lastControl>TimeUnit.SECONDS.toNanos(5)){fail(new IOException("Runtime control heartbeat expired"));return;}
for(Pending p:pending.values())if(now-p.deadline()>0){fail(new IOException("Runtime command timed out"));return;}
enqueue(new Packet(PING,0,new byte[0]));
}
private void fail(Throwable why){
if(closing.get()||!failed.compareAndSet(false,true))return;
failure=why;state.set(4);logs.accept(RuntimeLogEntry.error("Runtime connection failed: "+why.getMessage()));
for(Pending p:pending.values())p.result().completeExceptionally(why);pending.clear();
stopped.completeExceptionally(why);closeSockets();frames.close();timer.shutdownNow();
// Process identity is owned by this connection; never search or kill by executable name.
executor.execute(()->{
process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();
try{if(!process.waitFor(2,TimeUnit.SECONDS)){
process.destroyForcibly();if(!process.waitFor(2,TimeUnit.SECONDS))logs.accept(RuntimeLogEntry.error("Runtime termination is not confirmed"));
}}catch(InterruptedException e){Thread.currentThread().interrupt();}
});
}
private void closeSockets(){StudioRuntimeGateway.close(control);StudioRuntimeGateway.close(video);}
private static void await(CompletableFuture<Void> work){try{work.join();}catch(CompletionException|CancellationException ignored){}}
private static Throwable root(Throwable failure){
while((failure instanceof CompletionException||failure instanceof ExecutionException)&&failure.getCause()!=null)failure=failure.getCause();return failure;
}
}
@@ -0,0 +1,121 @@
package p.studio.app.runtime.studio;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.api.execution.PlayOptions;
import p.studio.api.project.*;
import p.studio.api.runtime.RuntimeLogEntry;
import p.studio.core.runtime.*;
import p.studio.core.project.ProjectCartridgeConfiguration;
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.security.SecureRandom;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Consumer;
import static p.studio.app.runtime.studio.StudioWire.*;
import p.studio.app.runtime.studio.StudioWire.Reader;
import p.studio.app.runtime.studio.StudioWire.Writer;
/** Owns a direct child runtime and two private loopback channels. */
public final class StudioRuntimeGateway implements RuntimeGateway {
private final ObjectMapper mapper;
public StudioRuntimeGateway(ObjectMapper mapper){this.mapper=Objects.requireNonNull(mapper);}
@Override public boolean interactive(){return true;}
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,Consumer<RuntimeLogEntry> logs)throws Exception {
return start(project,setup,logs,PlayOptions.PERSISTENT);
}
@Override public RuntimeConnection start(ProjectReference project,ProjectLocalStudioSetup setup,
Consumer<RuntimeLogEntry> logs,PlayOptions options)throws Exception {
new p.studio.app.assets.ManagedAssetGuard(mapper).require(project.rootPath(),project.rootPath().resolve("build"),setup);
Path executable=executable(setup);
List<String> command=new ArrayList<>(List.of(executable.toString(),"--studio","--run",project.rootPath().resolve("build").toString()));
if(project.memcardSlots()!=null&&!options.disposableSave()){
Path image=ProjectCartridgeConfiguration.selectedImage(project,setup);
if(!Files.isRegularFile(image))throw new IOException("Select an existing development save or an explicitly disposable session");
command.add("--memcard");command.add(image.toString());
}
InetAddress loopback=InetAddress.getByName("127.0.0.1");
byte[] session=new byte[16],token=new byte[32];SecureRandom random=new SecureRandom();random.nextBytes(session);random.nextBytes(token);
Process process=null;Socket control=null,video=null;
ExecutorService io=Executors.newThreadPerTaskExecutor(Thread.ofVirtual().name("studio-play-io-",0).factory());
try(ServerSocket controls=new ServerSocket(0,4,loopback);ServerSocket videos=new ServerSocket(0,4,loopback)){
process=new ProcessBuilder(command).directory(project.rootPath().toFile()).start();
CompletableFuture<Void> stdout=drain(process.getInputStream(),false,logs,io);
CompletableFuture<Void> stderr=drain(process.getErrorStream(),true,logs,io);
byte[] bootstrap=little(53).put(session).put(token).putShort((short)controls.getLocalPort())
.putShort((short)videos.getLocalPort()).put((byte)(options.disposableSave()?1:0)).array();
try(OutputStream input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,bootstrap);}
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);
Accepted c=accept(controls,session,token,1,process,deadline);control=c.socket();
Accepted v=accept(videos,session,token,2,process,deadline);video=v.socket();
control.setSoTimeout(remaining(deadline));
Message ready=c.reader().receive();
if(ready.header().kind()!=READY||ready.header().request()!=0||ready.payload().length<16)throw new IOException("Interactive runtime did not become ready");
var fields=java.nio.ByteBuffer.wrap(ready.payload()).order(java.nio.ByteOrder.LITTLE_ENDIAN);
int width=fields.getInt(),height=fields.getInt(),fps=fields.getInt(),format=fields.getInt();
frameBytes(width,height,width);
if(fps!=60||format!=RGBA8)throw new IOException("Unsupported interactive display format");
String version=text(ready.payload(),16);
logs.accept(RuntimeLogEntry.info("Studio Play protocol 1.0; runtime "+version));
control.setSoTimeout(0);video.setSoTimeout(0);
var connection=new StudioRuntimeConnection(process,control,video,c.reader(),v.reader(),session,width,height,logs,io,stdout,stderr);
connection.completion().whenComplete((code,failure)->io.shutdown());
return connection;
}catch(Throwable failure){
close(control);close(video);
if(process!=null){process.descendants().forEach(ProcessHandle::destroyForcibly);process.destroyForcibly();process.waitFor(2,TimeUnit.SECONDS);}
io.shutdownNow();
throw failure;
}finally{Arrays.fill(token,(byte)0);}
}
private static Path executable(ProjectLocalStudioSetup setup)throws IOException {
if(setup.prometeuRuntimePath()==null)throw new IOException("Select a runtime installation");
String name=System.getProperty("os.name").startsWith("Windows")?"prometeu-runtime.exe":"prometeu-runtime";
Path path=Path.of(setup.prometeuRuntimePath()).resolve(name).toAbsolutePath().normalize();
if(!Files.isRegularFile(path)||!Files.isExecutable(path))throw new IOException("Interactive runtime not found: "+path);
return path;
}
private record Accepted(Socket socket,Reader reader){ }
private static Accepted accept(ServerSocket listener,byte[] session,byte[] token,int role,Process process,long deadline)throws IOException {
listener.setSoTimeout(100);
while(System.nanoTime()<deadline){
if(Thread.currentThread().isInterrupted())throw new InterruptedIOException("Runtime startup cancelled");
if(!process.isAlive())throw new IOException("Runtime exited during startup with code "+process.exitValue());
Socket socket;
try{socket=listener.accept();}catch(SocketTimeoutException wait){continue;}
boolean admitted=false;
try{
socket.setSoTimeout(Math.min(1000,remaining(deadline)));socket.setTcpNoDelay(true);
Reader reader=new Reader(socket.getInputStream());Message hello=reader.receive();
byte[] p=hello.payload();
if(hello.header().kind()!=HELLO||hello.header().request()!=0||p.length!=49||p[48]!=(byte)role
||!Arrays.equals(session,Arrays.copyOfRange(p,0,16))
||!java.security.MessageDigest.isEqual(token,Arrays.copyOfRange(p,16,48)))continue;
admitted=true;return new Accepted(socket,reader);
}catch(IOException invalid){/* Reject an unrelated/malformed peer within the startup deadline. */}
finally{if(!admitted)close(socket);}
}
throw new SocketTimeoutException("Interactive runtime handshake timed out");
}
private static int remaining(long deadline)throws SocketTimeoutException {
long ms=TimeUnit.NANOSECONDS.toMillis(deadline-System.nanoTime());
if(ms<=0)throw new SocketTimeoutException("Interactive runtime handshake timed out");return (int)Math.min(ms,Integer.MAX_VALUE);
}
static void close(Socket socket){if(socket!=null)try{socket.close();}catch(IOException ignored){}}
static CompletableFuture<Void> drain(InputStream source,boolean error,Consumer<RuntimeLogEntry> logs,Executor executor){
return CompletableFuture.runAsync(()->{
try(var reader=new InputStreamReader(source,java.nio.charset.StandardCharsets.UTF_8)){
StringBuilder line=new StringBuilder();boolean truncated=false;char[] chars=new char[2048];int count;
while((count=reader.read(chars))!=-1){for(int i=0;i<count;i++){
char ch=chars[i];
if(ch=='\n'){
String text=line+(truncated?"…":"");if(!text.isBlank())logs.accept(error?RuntimeLogEntry.error(text):RuntimeLogEntry.info(text));
line.setLength(0);truncated=false;
}else if(ch!='\r'){if(line.length()<8192)line.append(ch);else truncated=true;}
}}
if(!line.toString().isBlank())logs.accept(error?RuntimeLogEntry.error(line.toString()):RuntimeLogEntry.info(line.toString()));
}catch(IOException ignored){/* Process completion owns status; preserve the already drained prefix. */}
},executor);
}
}
@@ -0,0 +1,81 @@
package p.studio.app.runtime.studio;
import java.io.*;
import java.nio.*;
import java.nio.charset.*;
/** Studio Play v1. No JavaFX, object serialization or platform-native transport. */
public final class StudioWire {
private StudioWire() { }
public static final int HEADER_BYTES = 32, CONTROL_LIMIT = 65536, FRAME_LIMIT = 16 * 1024 * 1024;
public static final int FRAME_METADATA_BYTES = 48, RGBA8 = 1;
public static final int HELLO=1, READY=2, START=3, PAUSE=4, RESUME=5, STOP=6, RESULT=7,
INPUT=8, FRAME=9, FRAME_RECEIVED=10, PING=11, PONG=12, ERROR=13, STOPPED=14, BOOTSTRAP=15;
public static ByteBuffer little(int length) { return ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN); }
public record Header(int kind, int length, long sequence, long request) {
public Header {
if (kind < HELLO || kind > BOOTSTRAP || sequence == 0 || length < 0
|| length > (kind == FRAME ? FRAME_LIMIT : CONTROL_LIMIT))
throw new IllegalArgumentException("Invalid Studio message type, sequence or payload length");
}
public byte[] encode() {
return little(HEADER_BYTES).putInt(0x31545350).putShort((short)1).putShort((short)0)
.putShort((short)kind).putShort((short)0).putInt(length).putLong(sequence).putLong(request).array();
}
public static Header decode(byte[] bytes) throws IOException {
if (bytes.length != HEADER_BYTES) throw new IOException("Truncated Studio header");
var b = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
if (b.getInt()!=0x31545350 || b.getShort()!=1 || b.getShort()!=0)
throw new IOException("Incompatible Studio protocol magic/version");
int kind = Short.toUnsignedInt(b.getShort());
if (b.getShort()!=0) throw new IOException("Unknown Studio protocol flags");
long length = Integer.toUnsignedLong(b.getInt()), seq=b.getLong(), request=b.getLong();
if (length > FRAME_LIMIT) throw new IOException("Studio payload exceeds limit");
try { return new Header(kind, (int)length, seq, request); }
catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); }
}
}
public record Message(Header header, byte[] payload) { }
public static final class Reader {
private final DataInputStream input;
private final byte[] header = new byte[HEADER_BYTES];
private long sequence;
public Reader(InputStream input) { this.input = new DataInputStream(input); }
public Header nextHeader() throws IOException {
input.readFully(header);
Header result = Header.decode(header);
if (Long.compareUnsigned(result.sequence(),sequence) <= 0)
throw new IOException("Non-monotonic Studio sequence");
sequence = result.sequence(); return result;
}
public void readFully(byte[] into, int offset, int length) throws IOException { input.readFully(into,offset,length); }
public Message receive() throws IOException {
Header h = nextHeader();
if (h.kind()==FRAME) throw new IOException("Video must use the bounded frame pool");
byte[] bytes = new byte[h.length()]; input.readFully(bytes); return new Message(h,bytes);
}
}
public static final class Writer {
private final OutputStream output;
private long sequence;
public Writer(OutputStream output) { this.output=output; }
public synchronized void send(int kind,long request,byte[] bytes) throws IOException {
if (++sequence==0) throw new IOException("Studio sequence exhausted");
try { output.write(new Header(kind,bytes.length,sequence,request).encode()); }
catch (IllegalArgumentException e) { throw new IOException(e.getMessage(),e); }
output.write(bytes); output.flush();
}
}
public static int frameBytes(int width,int height,int stride) throws IOException {
if (width <= 0 || height <= 0 || stride != width) throw new IOException("Invalid Studio frame dimensions/stride");
final long bytes;
try { bytes = Math.multiplyExact(Math.multiplyExact((long)width,height),4); }
catch (ArithmeticException e) { throw new IOException("Studio frame dimensions overflow",e); }
if (bytes > FRAME_LIMIT-FRAME_METADATA_BYTES) throw new IOException("Studio frame exceeds limit");
return (int)bytes;
}
public static String text(byte[] bytes,int offset) throws IOException {
try { return StandardCharsets.UTF_8.newDecoder().decode(ByteBuffer.wrap(bytes,offset,bytes.length-offset)).toString(); }
catch (CharacterCodingException e) { throw new IOException("Invalid Studio UTF-8",e); }
}
}