feat(studio): ship JavaFX 2 Play and delegate integration tooling
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:
@@ -3,6 +3,9 @@ plugins {
|
||||
alias(libs.plugins.javafx)
|
||||
}
|
||||
|
||||
// Configure the application-capable UI module before lazy classpath queries configure it.
|
||||
evaluationDependsOn(":prometeu-studio-ui-javafx-2")
|
||||
|
||||
dependencies {
|
||||
implementation(libs.tomlj)
|
||||
implementation(project(":prometeu-infra"))
|
||||
@@ -17,6 +20,7 @@ dependencies {
|
||||
implementation(project(":prometeu-studio-api"))
|
||||
implementation(project(":prometeu-studio-core"))
|
||||
implementation(project(":prometeu-studio-ui-javafx"))
|
||||
implementation(project(":prometeu-studio-ui-javafx-2"))
|
||||
implementation(libs.spring.boot)
|
||||
implementation(libs.lsp4j)
|
||||
implementation(libs.javafx.controls)
|
||||
@@ -25,9 +29,10 @@ dependencies {
|
||||
|
||||
application {
|
||||
mainClass = "p.studio.app.StudioLauncher"
|
||||
applicationDefaultJvmArgs = listOf("--enable-native-access=ALL-UNNAMED")
|
||||
}
|
||||
|
||||
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(21) }
|
||||
val studioJava = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) }
|
||||
val studioRuntime = layout.buildDirectory.dir("studio-runtime")
|
||||
val assembleStudioRuntime by tasks.registering(Exec::class) {
|
||||
val jdk = studioJava.get().metadata.installationPath.asFile
|
||||
@@ -40,11 +45,16 @@ val assembleStudioRuntime by tasks.registering(Exec::class) {
|
||||
check(it.setWritable(true, true)) { "Cannot normalize staged runtime permissions" }
|
||||
}
|
||||
}
|
||||
commandLine(jdk.resolve("bin/jlink"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
|
||||
commandLine(jdk.resolve("bin/jlink"), "--module-path", jdk.resolve("jmods"), "--add-modules", "ALL-MODULE-PATH", "--strip-debug", "--no-header-files",
|
||||
"--no-man-pages", "--output", studioRuntime.get().asFile)
|
||||
}
|
||||
distributions {
|
||||
main { contents { from(assembleStudioRuntime) { into("runtime") } } }
|
||||
main { contents {
|
||||
from(assembleStudioRuntime) { into("runtime") }
|
||||
from(project(":prometeu-studio-ui-javafx-2").file("src/main/resources/p/studio/ui/javafx2/fonts")) {
|
||||
include("*-LICENSE.txt");into("licenses")
|
||||
}
|
||||
} }
|
||||
}
|
||||
tasks.register<JavaExec>("stageStudioInstallation") {
|
||||
group = "application"
|
||||
@@ -121,6 +131,7 @@ tasks.register<Test>("headlessProcessTest") {
|
||||
project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath)
|
||||
include("**/HeadlessTaskIntegrationTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath)
|
||||
}
|
||||
|
||||
tasks.register<Test>("memcardProcessTest") {
|
||||
@@ -149,8 +160,41 @@ tasks.register<Test>("headlessMcpDesktopTest") {
|
||||
// Subprocess tests exercise the actual Studio main and OS ownership boundaries.
|
||||
tasks.withType<Test>().configureEach {
|
||||
systemProperty("studio.test.classpath", sourceSets["test"].runtimeClasspath.asPath)
|
||||
systemProperty("studio.test.protocolFixtures", rootProject.file("../runtime/devtools/studio-protocol/fixtures").absolutePath)
|
||||
systemProperty("studio.test.studioHost", providers.gradleProperty("studioPlayHost").getOrElse(
|
||||
rootProject.file("../runtime/target/debug/prometeu-host-desktop-winit" + if (System.getProperty("os.name").startsWith("Windows")) ".exe" else "").absolutePath))
|
||||
systemProperty("studio.test.studioCartridge", rootProject.file("../runtime/test-cartridges/dummy-boy").absolutePath)
|
||||
}
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayProcessTest.class") }
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayDesktopTest.class") }
|
||||
tasks.register<Test>("studioPlayDesktopTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies the default Play frontend with an installed native runtime and a desktop."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/StudioPlayDesktopTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
systemProperty("studio.test.pong", rootProject.file("test-projects/pong").absolutePath)
|
||||
systemProperty("studio.test.playStress", providers.gradleProperty("studioPlayStress").getOrElse("false"))
|
||||
systemProperty("java.awt.headless", "false")
|
||||
outputs.upToDateWhen { false }
|
||||
testLogging.showStandardStreams = true
|
||||
}
|
||||
tasks.register<Test>("studioPlayProcessTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies real interactive binary IPC (requires the Studio host binary, no display)."
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
include("**/StudioPlayProcessTest.class")
|
||||
include("**/StudioPlayInstalledRuntimeTest.class")
|
||||
systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse(""))
|
||||
outputs.upToDateWhen { false }
|
||||
}
|
||||
tasks.named<Test>("test") { exclude("**/StudioPlayInstalledRuntimeTest.class") }
|
||||
|
||||
tasks.named<Test>("test") { exclude("**/InstalledConnectorTest.class") }
|
||||
tasks.register<Test>("installedConnectorTest") {
|
||||
group = "verification"
|
||||
@@ -191,6 +235,9 @@ tasks.named<Test>("test") { exclude("**/AssetCapacityInstalledRuntimeTest.class"
|
||||
tasks.register<Test>("assetCapacityProcessTest") {
|
||||
group = "verification"
|
||||
description = "Qualifies glyph/scene 16/17 boundaries against the exact installed runtime."
|
||||
// The selected installation is external and can be rebuilt at the same path.
|
||||
outputs.upToDateWhen { false }
|
||||
outputs.doNotCacheIf("Qualification must observe the currently installed native binaries") { true }
|
||||
testClassesDirs = sourceSets["test"].output.classesDirs
|
||||
classpath = sourceSets["test"].runtimeClasspath
|
||||
useJUnitPlatform()
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,72 @@
|
||||
"prometeu-headless": "18423f798ab28bbd38c12a7ee46459f3ef3d08876cc64327952f57be041fc5df",
|
||||
"prometeu-runtime": "ee00a587eb48030d1455d3c9bedd784ab620309a09877b50fe3641ae502635df"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "macos-arm64-studio-play-v1-b377b99e40b7",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json",
|
||||
"evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/studio-play-native-capacity.json",
|
||||
"evidenceSha256": "3890ff2fe308f3b6a57f71e30e5f10db13c73871aa09dc451bbcff148982ff5c"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "b377b99e40b716ba6663043fdd3ffc14011b2769d4eaade1640dba7e8195e43a",
|
||||
"prometeu-headless": "3ace82881012fbdb83834055cf9f9fb759256da6d95260bce80de045f978ece5",
|
||||
"prometeu-runtime": "b56341fd45011871ef192a7788eeef2fb15edb8b4fd4fbd03e2d03a378cfd8a0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"profile": {
|
||||
"contractVersion": 1,
|
||||
"profileId": "native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60",
|
||||
"runtimeVersion": "0.1.0",
|
||||
"executableSha256": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"limits": {
|
||||
"glyph": 16,
|
||||
"scene": 16
|
||||
},
|
||||
"evidence": [
|
||||
{
|
||||
"bankType": "glyph",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json",
|
||||
"evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0"
|
||||
},
|
||||
{
|
||||
"bankType": "scene",
|
||||
"acceptedPreloads": 16,
|
||||
"rejectedPreloads": 17,
|
||||
"evidencePath": "asset-capacity/evidence/native-bundle-586a899bf9248ce6551a8b2f8e2f51740782c04b7f85a3ec346d742547275d60.json",
|
||||
"evidenceSha256": "89345c8a70973c5389c91ed02d1fe0866da30eaaa864d8602cb11c8ea25cdbc0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"executables": {
|
||||
"prometeu": "bb245dd057bbc910053b63c55b75a573ab4e9c9a02b7c79ba89e659bea8e85c3",
|
||||
"prometeu-headless": "a1662aaae81794a0f1eedfdbe386a52601ca133cf1634845d82c882fa130c942",
|
||||
"prometeu-runtime": "918ff7a8eccf3e7263cbfb265a27fd2d015a317d5bb0dcb25a801a04a7c969f6"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+1675
File diff suppressed because it is too large
Load Diff
+1675
File diff suppressed because it is too large
Load Diff
@@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Uses the actual desktop toolkit; runtime, operation and document inputs are test consumers only. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class DevDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit() throws Exception {
|
||||
|
||||
@@ -13,6 +13,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StudioApplicationConfigurationTest {
|
||||
@Test
|
||||
void bootsAndClosesWithoutAWebApplicationContext() {
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package p.studio.app;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import javafx.application.Platform;
|
||||
import javafx.scene.control.*;
|
||||
import javafx.scene.image.ImageView;
|
||||
import javafx.scene.input.*;
|
||||
import javafx.stage.Stage;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.springframework.boot.WebApplicationType;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import p.studio.api.execution.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.session.ProjectSessionFactory;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.execution.DefaultExecutionControllerFactory;
|
||||
import p.studio.app.runtime.studio.StudioRuntimeGateway;
|
||||
import p.studio.ui.javafx2.window.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual new frontend, real compiler/packer and direct installed native process. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StudioPlayDesktopTest {
|
||||
@TempDir Path temporary;
|
||||
static <T> T fx(Callable<T> action)throws Exception{
|
||||
var future=new CompletableFuture<T>();Platform.runLater(()->{try{future.complete(action.call());}catch(Throwable f){future.completeExceptionally(f);}});
|
||||
return future.get(15,TimeUnit.SECONDS);
|
||||
}
|
||||
@BeforeAll static void toolkit()throws Exception{
|
||||
var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(15,TimeUnit.SECONDS);
|
||||
}
|
||||
@AfterAll static void stopToolkit(){Platform.exit();}
|
||||
private static void await(BooleanSupplier condition,Supplier<String> failure)throws Exception{
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(20);
|
||||
while(System.nanoTime()<deadline){if(condition.getAsBoolean())return;Thread.sleep(25);}fail(failure.get());
|
||||
}
|
||||
@Test void realPongProjectPlayZoomPauseFocusStopAndClose()throws Exception{
|
||||
Path source=Path.of(System.getProperty("studio.test.pong")),root=temporary.resolve("Pong Project");
|
||||
try(var files=Files.walk(source)){for(Path file:files.toList()){
|
||||
Path relative=source.relativize(file);if(relative.toString().startsWith(".")||relative.toString().startsWith("build"))continue;
|
||||
Path target=root.resolve(relative);if(Files.isDirectory(file))Files.createDirectories(target);else Files.copy(file,target);
|
||||
}}
|
||||
var resources=new WindowResources();
|
||||
try(var app=new SpringApplicationBuilder(StudioApplicationConfiguration.class).web(WebApplicationType.NONE).headless(false).run()){
|
||||
var catalog=app.getBean(ProjectCatalog.class);var setups=app.getBean(ProjectLocalStudioSetupStore.class);
|
||||
var ref=catalog.openProject(root);setups.save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
|
||||
var access=app.getBean(ProjectAccessRegistry.class);var executor=app.getBean("studioExecutor",ExecutorService.class);
|
||||
var delayedPause=new java.util.concurrent.atomic.AtomicBoolean();
|
||||
var oldPause=new java.util.concurrent.atomic.AtomicReference<CompletableFuture<Void>>();
|
||||
var nativeGateway=new StudioRuntimeGateway(app.getBean(ObjectMapper.class));
|
||||
p.studio.core.runtime.RuntimeGateway gateway=new p.studio.core.runtime.RuntimeGateway(){
|
||||
public boolean interactive(){return true;}
|
||||
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs)throws Exception{return start(p,s,logs,PlayOptions.PERSISTENT);}
|
||||
public p.studio.core.runtime.RuntimeConnection start(ProjectReference p,ProjectLocalStudioSetup s,Consumer<p.studio.api.runtime.RuntimeLogEntry> logs,PlayOptions options)throws Exception{
|
||||
var actual=nativeGateway.start(p,s,logs,options);
|
||||
return new p.studio.core.runtime.RuntimeConnection(){
|
||||
public CompletableFuture<Integer> completion(){return actual.completion();}
|
||||
public CompletableFuture<Void> startExecution(){return actual.startExecution();}
|
||||
public CompletableFuture<Void> pause(){
|
||||
if(!delayedPause.getAndSet(false))return actual.pause();
|
||||
var result=new CompletableFuture<Void>();oldPause.set(result);return actual.pause().thenCompose(v->result);
|
||||
}
|
||||
public CompletableFuture<Void> resume(){return actual.resume();}
|
||||
public CompletableFuture<Void> stopAsync(){return actual.stopAsync();}
|
||||
public ExecutionFrame acquireLatestFrame(){return actual.acquireLatestFrame();}
|
||||
public void input(ExecutionInput value){actual.input(value);}
|
||||
public void close(){actual.close();}
|
||||
};
|
||||
}
|
||||
};
|
||||
var factory=new DefaultExecutionControllerFactory(app.getBean(p.studio.api.shipper.Shipper.class),
|
||||
gateway,app.getBean(p.studio.api.operation.OperationExecutor.class),access);
|
||||
var known=new KnownProjects(){public List<ProjectReference> listKnownProjects(){return List.of(ref);}public void remember(ProjectReference r){}public void forget(ProjectReference r){}};
|
||||
Stage stage=fx(Stage::new);
|
||||
var window=fx(()->new StudioWindowCoordinator2(stage,catalog,known,app.getBean(ProjectSessionFactory.class),factory,
|
||||
(project,setup)->{try(var lease=access.enterManual(project.rootPath())){setups.save(project,setup);}},executor,resources));
|
||||
try{
|
||||
fx(()->{window.showLauncher();stage.toFront();stage.requestFocus();assertNotNull(stage.getScene().lookup("#studio-shell"));window.openProject(root);return null;});
|
||||
await(()->{try{return fx(()->window.projectSession()!=null);}catch(Exception e){throw new RuntimeException(e);}},()->"Project did not open");
|
||||
Supplier<String> facts=()->{try{capture(stage,"failure.png");return fx(()->"state="+window.projectSession().executionSession().snapshot().state()+" focused="+stage.isFocused()+" frames="+window.viewport().paintedFrames()+"\n"+((Label)stage.getScene().lookup("#studio-notice")).getText()+"\n"+((TextArea)stage.getScene().lookup("#execution-logs")).getText());}catch(Exception e){return e.toString();}};
|
||||
focus(stage);
|
||||
fire(stage,"play");running(window,stage,facts);
|
||||
await(()->{try{return fx(()->window.viewport().paintedFrames()>3);}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
fx(()->{assertTrue(stage.getScene().lookup("#runtime-path").isDisabled());return null;});
|
||||
assertThrows(p.studio.api.automation.ControlDeniedException.class,()->access.enterManual(root));
|
||||
fx(()->{ComboBox<Integer> zoom=(ComboBox<Integer>)stage.getScene().lookup("#viewport-zoom");zoom.setValue(4);
|
||||
var image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(1920,image.getFitWidth());assertFalse(image.isSmooth());
|
||||
zoom.setValue(2);assertEquals(960,image.getFitWidth());zoom.setValue(1);assertEquals(480,image.getFitWidth());return null;});
|
||||
// Deliver a real key edge through the viewport; Pong leaves its static menu.
|
||||
// Zoom popup/native activation can transfer desktop focus. Establish the
|
||||
// input precondition explicitly; the later focus-loss checks never resume.
|
||||
running(window,stage,facts);
|
||||
long before=imageHash(stage);
|
||||
fx(()->{assertTrue(stage.isFocused(),"Keyboard qualification requires actual foreground focus");
|
||||
assertEquals(ExecutionState.RUNNING,window.projectSession().executionSession().snapshot().state());
|
||||
var surface=stage.getScene().lookup("#game-surface");surface.requestFocus();
|
||||
surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));return null;});
|
||||
try {
|
||||
await(()->{try{return imageHash(stage)!=before;}catch(Exception e){throw new RuntimeException(e);}},
|
||||
()->"Keyboard A must move Pong out of its menu\n"+facts.get());
|
||||
} finally {
|
||||
fx(()->{stage.getScene().lookup("#game-surface").fireEvent(new KeyEvent(KeyEvent.KEY_RELEASED,"a","a",KeyCode.A,false,false,false,false));return null;});
|
||||
}
|
||||
fire(stage,"pause");state(window,ExecutionState.PAUSED,facts);
|
||||
long paused=fx(()->window.viewport().lastFrameId());Thread.sleep(200);
|
||||
assertEquals(paused,fx(()->window.viewport().lastFrameId()));fire(stage,"resume");running(window,stage,facts);
|
||||
// A window owned by Studio is not an application switch.
|
||||
Stage owned=fx(()->{var s=new Stage();s.initOwner(stage);s.setScene(new javafx.scene.Scene(new Label("Studio dialog"),240,120));s.show();s.requestFocus();return s;});Thread.sleep(250);
|
||||
assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state()));
|
||||
fx(()->{owned.hide();stage.requestFocus();stage.setIconified(true);return null;});state(window,ExecutionState.PAUSED,facts);
|
||||
fx(()->{stage.setIconified(false);stage.requestFocus();return null;});Thread.sleep(200);
|
||||
assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts);
|
||||
Stage other=fx(()->{var s=new Stage();s.setTitle("Other application focus probe");s.setScene(new javafx.scene.Scene(new Label("Focus probe"),300,150));s.show();s.requestFocus();return s;});state(window,ExecutionState.PAUSED,facts);
|
||||
fx(()->{other.hide();stage.requestFocus();return null;});Thread.sleep(200);
|
||||
assertEquals(ExecutionState.PAUSED,fx(()->window.projectSession().executionSession().snapshot().state()));fire(stage,"resume");running(window,stage,facts);
|
||||
capture(stage,"play.png");
|
||||
if(Boolean.getBoolean("studio.test.playStress")){
|
||||
var process=runtime();long runtimeCpu=cpuNanos(process);
|
||||
long javaCpu=cpuNanos(ProcessHandle.current());
|
||||
long painted=fx(()->window.viewport().paintedFrames());
|
||||
long heapBefore=java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
|
||||
Thread.sleep(30_000);
|
||||
double p95=fx(()->window.viewport().latencyP95Millis());System.out.println("RECEIVE_TO_PAINT_P95_MS="+p95);assertTrue(p95<=33.4,"Idle receive-to-paint p95 "+p95);
|
||||
System.out.println("PAINT_FPS="+(fx(()->window.viewport().paintedFrames())-painted)/30.0);
|
||||
System.out.println("RUNTIME_CPU_SECONDS="+(cpuNanos(process)-runtimeCpu)/1e9);
|
||||
System.out.println("JAVA_CPU_SECONDS="+(cpuNanos(ProcessHandle.current())-javaCpu)/1e9);
|
||||
System.out.println("HEAP_USED_BEFORE_AFTER="+heapBefore+","+java.lang.management.ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed());
|
||||
assertEquals(ExecutionState.RUNNING,fx(()->window.projectSession().executionSession().snapshot().state()),facts);
|
||||
assertTrue(fx(stage::isFocused),"Idle-host measurement requires the Studio to retain actual focus");
|
||||
long frame=fx(()->window.viewport().lastFrameId());
|
||||
fx(()->{Thread.sleep(500);return null;});Thread.sleep(70);
|
||||
long afterFreeze=fx(()->window.viewport().lastFrameId());
|
||||
System.out.println("FX_FREEZE_FRAME_IDS="+frame+","+afterFreeze);
|
||||
assertTrue(afterFreeze>frame+15,()->"Runtime must advance while FX is blocked: "+frame+" -> "+afterFreeze+"\n"+facts.get());
|
||||
for(int i=0;i<20;i++){fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);Thread.sleep(130);
|
||||
assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads());
|
||||
fire(stage,"play");running(window,stage,facts);Thread.sleep(50);
|
||||
assertEquals(1,runtimeCount());assertEquals(1,heartbeatThreads());}
|
||||
System.out.println("PLAY_STOP_CYCLES=20");
|
||||
}
|
||||
fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);
|
||||
await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
try(var lease=access.enterManual(root)){}
|
||||
assertFalse(Files.exists(root.resolve(".codex")),"Play must not prepare an AI client");
|
||||
assertFalse(Files.exists(root.resolve("build.pmc")));
|
||||
fire(stage,"play");running(window,stage,facts);
|
||||
delayedPause.set(true);fire(stage,"pause");
|
||||
await(()->oldPause.get()!=null,facts);
|
||||
fire(stage,"stop");state(window,ExecutionState.STOPPED,facts);
|
||||
fire(stage,"play");running(window,stage,facts);
|
||||
oldPause.get().completeExceptionally(new java.io.IOException("obsolete-pause-result"));
|
||||
Thread.sleep(200);
|
||||
assertFalse(fx(()->((Label)stage.getScene().lookup("#studio-notice")).getText().contains("obsolete-pause-result")),
|
||||
"An old command must not replace a new execution's feedback");
|
||||
runtime().destroyForcibly();state(window,ExecutionState.RUNTIME_FAILED,facts);
|
||||
await(()->{try{return fx(()->!stage.getScene().lookup("#runtime-path").isDisabled());}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
assertTrue(fx(()->((TextArea)stage.getScene().lookup("#execution-logs")).getText().contains("Runtime")));
|
||||
fire(stage,"play");running(window,stage,facts);
|
||||
fx(()->{window.requestCloseProject();return null;});
|
||||
await(()->{try{return fx(()->window.projectSession()==null);}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
fx(()->{assertNotNull(stage.getScene().lookup("#open-project"));return null;});capture(stage,"projects.png");
|
||||
assertEquals(0,runtimeCount());assertEquals(0,heartbeatThreads());
|
||||
}finally{fx(()->{window.close();stage.hide();return null;});}
|
||||
}
|
||||
}
|
||||
static void fire(Stage stage,String id)throws Exception{fx(()->{Button button=(Button)stage.getScene().lookup("#"+id);assertFalse(button.isDisabled(),id+" disabled");button.fire();return null;});}
|
||||
static void state(StudioWindowCoordinator2 w,ExecutionState expected,Supplier<String> facts)throws Exception{
|
||||
await(()->{try{return fx(()->w.projectSession().executionSession().snapshot().state()==expected);}catch(Exception e){throw new RuntimeException(e);}},facts);
|
||||
Thread.sleep(130);
|
||||
}
|
||||
static void running(StudioWindowCoordinator2 w,Stage stage,Supplier<String> facts)throws Exception{
|
||||
focus(stage);
|
||||
await(()->{try{return fx(()->{var state=w.projectSession().executionSession().snapshot().state();
|
||||
if(state==ExecutionState.PAUSED){stage.requestFocus();((Button)stage.getScene().lookup("#resume")).fire();}
|
||||
return state==ExecutionState.RUNNING && stage.isFocused();});}catch(Exception e){throw new RuntimeException(e);}},facts);Thread.sleep(150);
|
||||
}
|
||||
static void focus(Stage stage)throws Exception{fx(()->{stage.setIconified(false);stage.toFront();stage.requestFocus();
|
||||
var point=stage.getScene().getRoot().localToScreen(10,10);
|
||||
var robot=new javafx.scene.robot.Robot();robot.mouseMove(point);robot.mouseClick(MouseButton.PRIMARY);return null;});Thread.sleep(150);}
|
||||
static void capture(Stage stage,String name)throws Exception{fx(()->{
|
||||
var image=stage.getScene().snapshot(null);var output=new java.awt.image.BufferedImage((int)image.getWidth(),(int)image.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);
|
||||
for(int y=0;y<output.getHeight();y++)for(int x=0;x<output.getWidth();x++)output.setRGB(x,y,image.getPixelReader().getArgb(x,y));
|
||||
Path file=Path.of("build/studio-play-qualification",name);Files.createDirectories(file.getParent());javax.imageio.ImageIO.write(output,"png",file.toFile());return null;});}
|
||||
static long imageHash(Stage stage)throws Exception{return fx(()->{var image=((ImageView)stage.getScene().lookup("#game-image")).getImage();long hash=1;
|
||||
for(int y=0;y<(int)image.getHeight();y++)for(int x=0;x<(int)image.getWidth();x++)hash=31*hash+image.getPixelReader().getArgb(x,y);return hash;});}
|
||||
static long runtimeCount(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).count();}
|
||||
static ProcessHandle runtime(){return ProcessHandle.current().children().filter(p->p.isAlive()&&p.info().command().orElse("").endsWith("/prometeu-runtime")).findFirst().orElseThrow();}
|
||||
static long heartbeatThreads(){return Thread.getAllStackTraces().keySet().stream().filter(t->t.isAlive()&&t.getName().equals("studio-play-heartbeat")).count();}
|
||||
static long cpuNanos(ProcessHandle process)throws Exception{
|
||||
var cpu=process.info().totalCpuDuration();if(cpu.isPresent())return cpu.get().toNanos();
|
||||
// HotSpot on this macOS does not expose child CPU duration through ProcessHandle.Info.
|
||||
var query=new ProcessBuilder("/bin/ps","-p",Long.toString(process.pid()),"-o","cputime=").start();
|
||||
String value=new String(query.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8).trim();
|
||||
assertTrue(query.waitFor(2,TimeUnit.SECONDS));assertEquals(0,query.exitValue());
|
||||
double seconds=0;for(String component:value.split(":"))seconds=seconds*60+Double.parseDouble(component);
|
||||
return (long)(seconds*1e9);
|
||||
}
|
||||
|
||||
@Test void viewportCopiesStablePixelsAndInvertsZoomWithoutClampingOutsideTouches()throws Exception{
|
||||
var input=new java.util.concurrent.atomic.AtomicReference<>(ExecutionInput.NEUTRAL);
|
||||
byte[] pixels=new byte[4*2*4];for(int i=0;i<pixels.length;i+=4){pixels[i+2]=(byte)255;pixels[i+3]=(byte)255;}
|
||||
var frame=new java.util.concurrent.atomic.AtomicReference<>(new ExecutionFrame(4,2,1,1,pixels,()->{}));
|
||||
ExecutionController controller=new ExecutionController(){
|
||||
public p.studio.api.operation.OperationHandle<ExecutionSnapshot> play(){throw new UnsupportedOperationException();}
|
||||
public void stop(){}public void close(){}public ExecutionFrame acquireLatestFrame(){return frame.getAndSet(null);}
|
||||
public void input(ExecutionInput value){input.set(value);}
|
||||
};
|
||||
var viewport=fx(()->new p.studio.ui.javafx2.play.PlaybackViewport(()->controller,()->ExecutionState.RUNNING));
|
||||
Stage stage=fx(()->{var s=new Stage();s.setScene(new javafx.scene.Scene(viewport,500,300));s.show();return s;});
|
||||
try{
|
||||
await(()->{try{return fx(()->viewport.paintedFrames()==1);}catch(Exception e){throw new RuntimeException(e);}},()->"Frame was not painted");
|
||||
fx(()->{viewport.zoom(4);stage.getScene().getRoot().applyCss();stage.getScene().getRoot().layout();
|
||||
ImageView image=(ImageView)stage.getScene().lookup("#game-image");assertEquals(0xffff0000,image.getImage().getPixelReader().getArgb(1,1));
|
||||
assertEquals(16,image.getFitWidth());
|
||||
pointer(image,MouseEvent.MOUSE_PRESSED,6,6);assertEquals(new ExecutionInput(4096,1,1),input.get());
|
||||
pointer(image,MouseEvent.MOUSE_DRAGGED,-1,6);assertEquals(0,input.get().buttons());assertEquals(-1,input.get().touchX());
|
||||
pointer(image,MouseEvent.MOUSE_PRESSED,14,6);assertEquals(new ExecutionInput(4096,3,1),input.get());
|
||||
pointer(image,MouseEvent.MOUSE_RELEASED,30,30);assertEquals(0,input.get().buttons());
|
||||
var surface=stage.getScene().lookup("#game-surface");
|
||||
surface.fireEvent(new KeyEvent(KeyEvent.KEY_PRESSED,"a","a",KeyCode.A,false,false,false,false));assertEquals(16,input.get().buttons());
|
||||
viewport.neutralize();assertEquals(0,input.get().buttons());return null;});
|
||||
}finally{fx(()->{viewport.close();stage.hide();return null;});}
|
||||
}
|
||||
static void pointer(ImageView image,javafx.event.EventType<MouseEvent> type,double x,double y){
|
||||
var point=image.localToScene(x,y);
|
||||
image.fireEvent(new MouseEvent(type,point.getX(),point.getY(),0,0,MouseButton.PRIMARY,1,
|
||||
false,false,false,false,type!=MouseEvent.MOUSE_RELEASED,false,false,false,false,false,
|
||||
new PickResult(image,point.getX(),point.getY())));
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AnimationDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit()throws Exception{
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Production packaged runtime: canonical authoring -> generated PBS -> Composer -> pixels. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AnimationInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
@Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{
|
||||
|
||||
@@ -24,6 +24,7 @@ import javax.imageio.ImageIO;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static p.animation.AnimationDocument.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AnimationIntegrationTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper=new ObjectMapper();
|
||||
|
||||
@@ -28,6 +28,7 @@ import java.util.function.Supplier;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual Assets controls, shared preview/publication, capacity projection and grant inspection. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AssetAuthoringDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit()throws Exception {
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real packer/filesystem composition behind the same human/task service. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AssetBatchIntegrationTest {
|
||||
@TempDir Path root;
|
||||
AnimationIntegrationTest fixture;FileAssetBatchWorkspace disk;AssetAuthoringService service;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
package p.studio.app.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.assets.AssetBudgets.*;
|
||||
import p.studio.api.project.ProjectLocalStudioSetup;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AssetCapacityProfilesTest {
|
||||
@TempDir Path installation;
|
||||
private final ObjectMapper json = new ObjectMapper();
|
||||
private final byte[] evidence = "native qualification evidence".getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||
|
||||
@Test void findsCompleteBundleAfterAnOlderProfileWithTheSameDispatcher() throws Exception {
|
||||
var old = bundle("old", "old-headless", "old-runtime");
|
||||
var current = bundle("current", "new-headless", "new-runtime");
|
||||
install("new-headless", "new-runtime");
|
||||
for (var order : List.of(List.of(old, current), List.of(current, old))) {
|
||||
var selection = select(order, evidence);
|
||||
assertEquals(QualificationState.known, selection.state(), selection.reason());
|
||||
assertEquals("current", selection.profile().profileId());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void rejectsComponentsStitchedFromDifferentQualifiedBundles() throws Exception {
|
||||
install("old-headless", "new-runtime");
|
||||
var selection = select(List.of(bundle("old", "old-headless", "old-runtime"),
|
||||
bundle("new", "new-headless", "new-runtime")), evidence);
|
||||
assertEquals(QualificationState.unknown, selection.state());
|
||||
assertNull(selection.profile());
|
||||
assertTrue(selection.reason().contains("component changed"), selection.reason());
|
||||
}
|
||||
|
||||
@Test void rejectsChangedComponentAndCorruptOrMissingEvidence() throws Exception {
|
||||
var current = bundle("current", "new-headless", "new-runtime");
|
||||
install("modified-headless", "new-runtime");
|
||||
assertEquals(QualificationState.unknown, select(List.of(current), evidence).state());
|
||||
install("new-headless", "new-runtime");
|
||||
for (byte[] resource : Arrays.asList("corrupt".getBytes(), null)) {
|
||||
var selection = select(List.of(current), resource);
|
||||
assertEquals(QualificationState.unknown, selection.state());
|
||||
assertTrue(selection.reason().contains("evidence integrity"), selection.reason());
|
||||
}
|
||||
}
|
||||
|
||||
@Test void rejectsUnqualifiedDispatcherAndIncompleteIdentity() throws Exception {
|
||||
var current = bundle("current", "new-headless", "new-runtime");
|
||||
install("new-headless", "new-runtime");
|
||||
Files.writeString(installation.resolve(executable("prometeu")), "unqualified-cli");
|
||||
assertEquals(QualificationState.unknown, select(List.of(current), evidence).state());
|
||||
install("new-headless", "new-runtime");
|
||||
var incomplete = new AssetCapacityProfiles.Bundle(current.profile(), Map.of("prometeu", hash("cli")));
|
||||
assertEquals(QualificationState.unknown, select(List.of(incomplete), evidence).state());
|
||||
}
|
||||
|
||||
@Test void missingInstallationOrCatalogRemainsUnknown() throws Exception {
|
||||
var service = new AssetCapacityProfiles(json, name -> null);
|
||||
assertEquals(QualificationState.unknown, service.select(null).state());
|
||||
assertEquals(QualificationState.unknown, service.select(ProjectLocalStudioSetup.defaults()).state());
|
||||
install("headless", "runtime");
|
||||
assertEquals(QualificationState.unknown, service.select(setup()).state());
|
||||
}
|
||||
|
||||
private AssetCapacityProfiles.Bundle bundle(String id, String headless, String runtime) {
|
||||
var profile = new Profile(1, id, "test", hash("cli"), Map.of(BankType.glyph, 16),
|
||||
List.of(new BoundaryEvidence(BankType.glyph, 16, 17, "evidence.json", AssetWorkspaceFiles.hash(evidence))));
|
||||
return new AssetCapacityProfiles.Bundle(profile, Map.of("prometeu", hash("cli"),
|
||||
"prometeu-headless", hash(headless), "prometeu-runtime", hash(runtime)));
|
||||
}
|
||||
|
||||
private ProfileSelection select(List<AssetCapacityProfiles.Bundle> bundles, byte[] record) throws Exception {
|
||||
byte[] catalog = json.writeValueAsBytes(new AssetCapacityProfiles.Catalog(1, bundles));
|
||||
return new AssetCapacityProfiles(json, name -> {
|
||||
byte[] bytes = name.equals("asset-capacity/catalog.json") ? catalog : record;
|
||||
return bytes == null ? null : new ByteArrayInputStream(bytes);
|
||||
}).select(setup());
|
||||
}
|
||||
|
||||
private ProjectLocalStudioSetup setup() { return new ProjectLocalStudioSetup(installation.toString(), null); }
|
||||
private void install(String headless, String runtime) throws Exception {
|
||||
Files.writeString(installation.resolve(executable("prometeu")), "cli");
|
||||
Files.writeString(installation.resolve(executable("prometeu-headless")), headless);
|
||||
Files.writeString(installation.resolve(executable("prometeu-runtime")), runtime);
|
||||
}
|
||||
private static String executable(String name) { return name + (System.getProperty("os.name").startsWith("Windows") ? ".exe" : ""); }
|
||||
private static String hash(String text) { return AssetWorkspaceFiles.hash(text.getBytes(java.nio.charset.StandardCharsets.UTF_8)); }
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class InstalledKnowledgeTest {
|
||||
@TempDir Path outsideRepository;
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real compiler/packer/project composition, no guest or runtime installation required. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class TargetBuildIntegrationTest {
|
||||
@TempDir Path root;
|
||||
ConfigurableApplicationContext app;ProjectSession project;TaskTools tools;String task;ObjectMapper mapper;
|
||||
|
||||
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class EvidenceIntegrationTest {
|
||||
@TempDir Path root;
|
||||
ExecutorService pool;DefaultAutomationSession session;ProjectAccessRegistry projects;ObjectMapper mapper=new ObjectMapper();
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class InstalledConnectorTest {
|
||||
@TempDir Path temporary;
|
||||
@Test void bundledJavaAndStableUpdateWorkWithSpacesMinimalEnvironmentAndBothPreparationPaths() throws Exception {
|
||||
@@ -67,12 +68,15 @@ class InstalledConnectorTest {
|
||||
return builder;
|
||||
}
|
||||
public static class DesktopProbe {
|
||||
public static void main(String[] args) {
|
||||
public static void main(String[] args) throws Exception {
|
||||
var application=new p.studio.app.App();application.init();
|
||||
javafx.application.Platform.startup(() -> {
|
||||
try {
|
||||
var stage = new javafx.stage.Stage(); stage.setScene(new javafx.scene.Scene(new javafx.scene.control.Label("Installed Studio JavaFX")));
|
||||
stage.show(); stage.close(); System.exit(0);
|
||||
} catch (Throwable failure) { System.exit(2); }
|
||||
var stage = new javafx.stage.Stage();application.start(stage);
|
||||
if(stage.getScene().lookup("#studio-shell")==null||stage.getScene().lookup("#open-project")==null)
|
||||
throw new AssertionError("Installed app did not open the new project chooser");
|
||||
application.stop();stage.hide();System.exit(0);
|
||||
} catch (Throwable failure) { failure.printStackTrace();System.exit(2); }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AutomationLspQueriesTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path temporary;
|
||||
|
||||
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Controlled protocol faults use real sockets; the stubborn child is an explicitly injected port. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class LanguageFailureContractTest {
|
||||
@TempDir Path root;
|
||||
@Test void protocolMechanismsBecomeNeutralFailuresAndLegacyFallbackStaysLimited() throws Exception {
|
||||
|
||||
@@ -8,6 +8,7 @@ import p.studio.lsp.services.LspServerLifecycleImpl;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class LspDiscoveryTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.util.concurrent.atomic.AtomicInteger;
|
||||
import p.studio.api.automation.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class LocalMcpServerTest {
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
final HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
|
||||
@@ -13,6 +13,7 @@ import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class McpConnectionGuideTest {
|
||||
@TempDir Path root;
|
||||
@Test void preparationIsStableAndSeparateFromAuthority() throws Exception {
|
||||
|
||||
@@ -19,6 +19,7 @@ import java.util.concurrent.atomic.*;
|
||||
import java.util.function.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class McpTaskToolsTest {
|
||||
String httpAuthorization;
|
||||
@TempDir Path root;
|
||||
|
||||
@@ -8,6 +8,7 @@ import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Map;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class ProjectConnectionPublisherTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Frozen sources, production compiler/packer/LSP, authenticated loopback MCP. No runtime execution. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StructuredDiagnosticsIntegrationTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper json = new ObjectMapper();
|
||||
|
||||
@@ -11,6 +11,7 @@ import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StudioMcpStdioTest {
|
||||
@TempDir Path temporary;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Provider qualification precedes publication of a consumer capacity profile. No managed-guard bypass in production. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AssetCapacityInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
@Test void actualInstalledPoolsAcceptSixteenAndRejectSeventeenGlyphAndScenePreloads()throws Exception {
|
||||
|
||||
+1
@@ -16,6 +16,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Real qualified build/preflight and process execution, independent of the provider boundary qualification. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class AssetManagedBuildInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
Map<String,String> files(Path directory)throws Exception {
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Required pilot on a disposable copy of the actual game, using only its existing public APIs. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class GuestTestPilotTest {
|
||||
@TempDir Path root;
|
||||
static Map<String,String> sources(Path root)throws Exception {
|
||||
|
||||
@@ -28,6 +28,7 @@ import java.util.function.Supplier;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual Tests workspace + authenticated HTTP MCP + installed provider, over one service. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class GuestTestsDesktopTest {
|
||||
@TempDir Path root;
|
||||
@BeforeAll static void toolkit()throws Exception {var ready=new CompletableFuture<Void>();Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});ready.get(10,TimeUnit.SECONDS);}
|
||||
|
||||
@@ -17,6 +17,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual installed provider and PBS/compiler/packer/shared runner; no simulated protocol. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class GuestTestsInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
ConfigurableApplicationContext app;ProjectSession session;GuestTestTools tests;ObjectMapper mapper;String task;
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Explicit packaged-process gate, not satisfied by protocol fixtures. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class HeadlessInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
@Test void configuredDistributionBootsSavedBuildAndReturnsDeterministicCanonicalPixels() throws Exception {
|
||||
|
||||
@@ -30,6 +30,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Full real loop: external HTTP client -> app -> Rust JSONL -> MCP image and JavaFX DEV. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class HeadlessMcpDesktopTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -10,6 +10,7 @@ import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class HeadlessProcessSessionTest {
|
||||
@TempDir Path root;
|
||||
final List<HeadlessProcessSession> sessions = new ArrayList<>();
|
||||
|
||||
@@ -18,6 +18,7 @@ import java.util.concurrent.TimeUnit;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Actual app composition and saved-source services; no runtime/build/LSP doubles. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class HeadlessTaskIntegrationTest {
|
||||
@TempDir Path root;
|
||||
ConfigurableApplicationContext app;
|
||||
@@ -120,12 +121,16 @@ class HeadlessTaskIntegrationTest {
|
||||
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(Map.of("kind","native-checkpoint","artifact",artifact,"report",report.report(),"nativeAdvanceRequests",2,"persistenceExtraAdvanceOrCaptureRequests",0)));
|
||||
}
|
||||
|
||||
@Test void zeldaPilotUsesDisposableCopyAndKeepsReferenceLimitationsExplicit() throws Exception {
|
||||
Path originalProject=Path.of(System.getProperty("studio.test.zeldaProject", "../../zelda-1")).toAbsolutePath().normalize();
|
||||
assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Zelda pilot checkout is required for this qualification");
|
||||
project.close();Path copy=root.resolve("zelda-pilot");Files.createDirectories(copy);
|
||||
@Test void pongPilotUsesDisposableCopyAndIndependentRegionReferences() throws Exception {
|
||||
String fixture=System.getProperty("studio.test.pong");
|
||||
assertNotNull(fixture,"Run headlessProcessTest to select Studio's test-projects/pong fixture");
|
||||
Path originalProject=Path.of(fixture).toAbsolutePath().normalize();
|
||||
assertTrue(Files.isRegularFile(originalProject.resolve("prometeu.json")),"Repository-owned Pong fixture is required");
|
||||
String originalSource=Files.readString(originalProject.resolve("src/main.pbs"));
|
||||
project.close();Path copy=root.resolve("Pong Headless");Files.createDirectories(copy);
|
||||
for(String name:List.of("prometeu.json","src","assets")) {
|
||||
Path from=originalProject.resolve(name);
|
||||
if(!Files.exists(from))continue; // Pong has no external assets.
|
||||
if(Files.isDirectory(from))try(var paths=Files.walk(from)) {
|
||||
for(var p:paths.toList()){var target=copy.resolve(originalProject.relativize(p));if(Files.isDirectory(p))Files.createDirectories(target);else Files.copy(p,target);}
|
||||
}else Files.copy(from,copy.resolve(name));
|
||||
@@ -133,17 +138,20 @@ class HeadlessTaskIntegrationTest {
|
||||
root=copy.toRealPath();var ref=app.getBean(ProjectCatalog.class).openProject(root);
|
||||
app.getBean(ProjectLocalStudioSetupStore.class).save(ref,new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null));
|
||||
project=app.getBean(ProjectSessionFactory.class).open(ref);project.automation().grant(false).toCompletableFuture().get(5,TimeUnit.SECONDS);task=tasks.acquire(root).task().value();
|
||||
String build=successfulBuild("zelda-pilot-build");tasks.headless(root,task,TaskTools.HeadlessAction.BOOT,build,Map.of("memcardChoice","memory_fresh"));
|
||||
String build=successfulBuild("pong-pilot-build");call(TaskTools.HeadlessAction.BOOT,build);
|
||||
var evidence=app.getBean(EvidenceTools.class);var measurements=new ArrayList<Map<String,Object>>();
|
||||
var mcp=app.getBean(p.studio.app.mcp.McpToolRegistry.class);
|
||||
long beforeWireBytes=0,afterWireBytes=0;int beforeCalls=0,afterCalls=0;
|
||||
var legacyPaths=new ArrayList<String>();
|
||||
String[] refs={"extracted/inventory_screen/validation/production_start.png","extracted/hud/runtime_initial.png","extracted/bomb_wall/validation/scroll_north_mid.png"};
|
||||
String[] names={"screen","hud","scroll"};
|
||||
String[] names={"menu-accent","serve-ball","moved-paddle"};
|
||||
// Fixed expectations from the fixture's draw/input contract, never from a native capture.
|
||||
Evidence.Rect[] regions={new Evidence.Rect(113,114,1,80),new Evidence.Rect(237,152,6,6),new Evidence.Rect(42,72,8,36)};
|
||||
int[][] colors={{77,237,205},{236,244,250},{77,237,205}};
|
||||
long totalPngBytes=0;
|
||||
for(int i=0;i<names.length;i++) {
|
||||
if(i>0)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of(i==1?"start":"right",true));
|
||||
String request="zelda-"+names[i];tasks.advance(root,task,request,i==0?1:i==1?76:120);var operation=finished(request);
|
||||
if(i==1)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",true));
|
||||
if(i==2)tasks.headless(root,task,TaskTools.HeadlessAction.SET_INPUT,null,Map.of("start",false,"up",true));
|
||||
String request="pong-"+names[i];tasks.advance(root,task,request,i==2?20:1);var operation=finished(request);
|
||||
assertNull(operation.failure());assertNotNull(operation.runtimeResult().capture());
|
||||
var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task);
|
||||
var before=mcp.call("studio_operation_get",args.deepCopy().put("clientRequestId",request)).wire();
|
||||
@@ -154,13 +162,18 @@ class HeadlessTaskIntegrationTest {
|
||||
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(persisted).length;
|
||||
assertFalse(persisted.path("isError").asBoolean(),persisted.toString());
|
||||
var actual=mapper.convertValue(persisted.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
|
||||
Path reference=root.resolve("reference-"+names[i]+".png");Files.copy(originalProject.resolve(refs[i]),reference);
|
||||
Path reference=root.resolve("reference-"+names[i]+".png");
|
||||
byte[] rgba=new byte[480*270*4];
|
||||
for(int pixel=0;pixel<rgba.length;pixel+=4){
|
||||
rgba[pixel]=(byte)colors[i][0];rgba[pixel+1]=(byte)colors[i][1];rgba[pixel+2]=(byte)colors[i][2];rgba[pixel+3]=(byte)255;
|
||||
}
|
||||
Files.write(reference,new p.studio.app.evidence.PngEvidenceCodec().encode(new Evidence.Pixels(480,270,rgba)));
|
||||
legacyPaths.add(reference.toString());legacyPaths.add(legacyActual.toString());
|
||||
var imported=mcp.call("studio_evidence_import",args.deepCopy().put("clientRequestId","import-"+request).put("path",reference.toString())).wire();
|
||||
afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(imported).length;
|
||||
assertFalse(imported.path("isError").asBoolean(),imported.toString());
|
||||
var expected=mapper.convertValue(imported.path("structuredContent").path("value"),Evidence.Publication.class).artifacts().getFirst();
|
||||
Evidence.Rect roi=i==1?new Evidence.Rect(112,15,256,56):null;
|
||||
Evidence.Rect roi=regions[i];
|
||||
var params=new Evidence.Parameters(roi,List.of(),Evidence.Alpha.compare,0,0);
|
||||
var comparisonArgs=args.deepCopy().put("clientRequestId","compare-"+request).put("expectedId",expected.id()).put("actualId",actual.id());
|
||||
var parametersNode=(com.fasterxml.jackson.databind.node.ObjectNode)mapper.valueToTree(params);
|
||||
@@ -168,8 +181,12 @@ class HeadlessTaskIntegrationTest {
|
||||
var compared=mcp.call("studio_evidence_compare",comparisonArgs).wire();afterCalls++;afterWireBytes+=mapper.writeValueAsBytes(compared).length;
|
||||
assertFalse(compared.path("isError").asBoolean(),compared.toString());
|
||||
var report=mapper.convertValue(compared.path("structuredContent").path("value"),Evidence.Publication.class);
|
||||
assertEquals(Evidence.Verdict.passed,report.report().verdict(),names[i]);
|
||||
assertEquals((long)roi.width()*roi.height(),report.report().comparedPixels());
|
||||
assertEquals(0,report.report().differentPixels());
|
||||
assertArrayEquals(legacyPng,evidence.image(root,task,actual.id()));
|
||||
totalPngBytes+=legacyPng.length;
|
||||
measurements.add(Map.of("case",names[i],"referencePath",refs[i],"actual",actual,"report",report.report()));
|
||||
measurements.add(Map.of("case",names[i],"referencePath",reference.getFileName().toString(),"actual",actual,"report",report.report()));
|
||||
}
|
||||
// Execute the former external comparison path against the same checkpoints; count actual calls/bytes/scripts.
|
||||
Path script=root.resolve("LegacyVisualCompare.java");
|
||||
@@ -187,10 +204,11 @@ class HeadlessTaskIntegrationTest {
|
||||
var command=new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"),"bin","java").toString(),script.toString()));command.addAll(legacyPaths);
|
||||
var legacy=new ProcessBuilder(command).redirectErrorStream(true).start();assertTrue(legacy.waitFor(30,TimeUnit.SECONDS));
|
||||
String legacyOutput=new String(legacy.getInputStream().readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);assertEquals(0,legacy.exitValue(),legacyOutput);
|
||||
var output=Map.of("kind","zelda-pilot","limitations","Saved port captures are contextual references, not an independent NES oracle; screen/HUD/scroll reference labels identify their provenance. Current checkpoints are observations and mismatch is retained as a comparison result.",
|
||||
assertEquals(originalSource,Files.readString(originalProject.resolve("src/main.pbs")),"Build and runtime must use only the disposable copy");
|
||||
var output=Map.of("kind","pong-pilot","limitations","Solid-color references specify only the declared ROIs independently of native captures. These checks cover menu, serve and input-driven paddle movement, not full-game visual equivalence.",
|
||||
"results",measurements,"measurement",Map.of("sharedGuestAdvanceRequests",3,"before",Map.of("mcpCalls",beforeCalls,"wireResponseBytes",beforeWireBytes,"imagePngBytes",totalPngBytes,"externalComparisonScripts",1,"externalScriptOutput",legacyOutput),
|
||||
"after",Map.of("mcpCalls",afterCalls,"wireResponseBytes",afterWireBytes,"imageTransferBytesForMetrics",0,"externalComparisonScripts",0),
|
||||
"basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from the explicit HUD ROI by design."));
|
||||
"basis","Actual local MCP adapter dispatches and serialized response bytes, excluding shared build/advance/asynchronous polling. Both comparison paths use the same three retained guest checkpoints. Legacy full-image exact metrics differ from ROI-specific checks by design."));
|
||||
System.out.println("VISUAL_EVIDENCE "+mapper.writeValueAsString(output));
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** PBS/shipper -> configured dispatcher -> distinct OS processes; no native injection. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class MemcardInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
package p.studio.app.runtime;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.execution.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.api.automation.TaskTools;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
import p.studio.core.project.*;
|
||||
import p.studio.core.runtime.*;
|
||||
import p.studio.core.shipper.StudioShipperService;
|
||||
import p.studio.app.compiler.CompilerBuildGatewayAdapter;
|
||||
import p.studio.app.operation.ExecutorOperationExecutor;
|
||||
import p.studio.app.runtime.studio.StudioRuntimeGateway;
|
||||
import java.nio.file.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/** Cross-mode save compatibility and actual interactive dirty-Stop refusal. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StudioPlayInstalledRuntimeTest {
|
||||
@TempDir Path root;
|
||||
final ObjectMapper json=new ObjectMapper();
|
||||
@Test void persistentDirtyStopRefusesThenGuestCommitsAndHeadlessReadsWhileDisposableNeverOverwrites()throws Exception{
|
||||
Files.createDirectories(root.resolve("src"));
|
||||
Files.writeString(root.resolve("prometeu.json"),"""
|
||||
{"name":"studio-save","version":"1","language":"pbs","stdlib":"1","target":"Game","app_id":4294967295,"memcard_slots":1,"dependencies":[]}
|
||||
""");
|
||||
Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;");
|
||||
String writer=MemcardInstalledRuntimeTest.WRITER
|
||||
.replace(MemcardInstalledRuntimeTest.PREFIX,MemcardInstalledRuntimeTest.PREFIX+"import {Pad, Button} from @sdk:input;\n")
|
||||
.replace("let commit = Mem.slot_commit(context, 0);","if Pad.down(Button.A) == false { return; }\nlet commit = Mem.slot_commit(context, 0);");
|
||||
Files.writeString(root.resolve("src/main.pbs"),writer);
|
||||
var store=new ProjectLocalStudioSetupStore(json);var project=new ProjectCatalogService(root,json,store).openProject(root);
|
||||
Path image=root.resolve("development-save.pmc");var setup=new ProjectLocalStudioSetup(System.getProperty("studio.test.runtimeInstall"),null,null,image.toString());store.save(project,setup);
|
||||
var logs=new CopyOnWriteArrayList<RuntimeLogEntry>();
|
||||
try(var workers=Executors.newFixedThreadPool(2);var packer=p.packer.Packer.bootstrap(json,e->{})){
|
||||
var shipper=new StudioShipperService(new CompilerBuildGatewayAdapter(),packer.workspaceService(),json,new ExecutorOperationExecutor(workers))
|
||||
.withAssetPreflight(new p.studio.app.assets.AssetBudgetInspection(json,packer.workspaceService(),store::load));
|
||||
var build=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(build.success(),build.diagnostics().toString());
|
||||
var headless=new HeadlessProcessGateway(json,store::load);
|
||||
var formatting=(HeadlessProcessSession)headless.boot(project,"format-test-media",build,
|
||||
Map.of("memcard",Map.of("path",image.toString(),"action","create","access","read_write"),"memcardChoice","persistent"));
|
||||
try{formatting.call(TaskTools.HeadlessAction.RESET,Map.of("discardUnsaved",true,"pendingWrites","cancel"));}
|
||||
finally{formatting.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
|
||||
assertTrue(Files.isRegularFile(image));
|
||||
var gateway=new StudioRuntimeGateway(json);
|
||||
var persistent=gateway.start(project,setup,logs::add,PlayOptions.PERSISTENT);
|
||||
try{
|
||||
persistent.startExecution().get(5,TimeUnit.SECONDS);awaitColor(persistent,0,0,255,logs); // BGRA red
|
||||
var refusal=assertThrows(ExecutionException.class,()->persistent.stopAsync().get(5,TimeUnit.SECONDS));
|
||||
assertInstanceOf(RuntimeStopRefusedException.class,refusal.getCause());assertFalse(persistent.completion().isDone());
|
||||
persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0));
|
||||
awaitColor(persistent,0,255,0,logs);persistent.input(ExecutionInput.NEUTRAL);
|
||||
persistent.stopAsync().get(5,TimeUnit.SECONDS);assertEquals(0,persistent.completion().join());
|
||||
}finally{if(!persistent.completion().isDone()){persistent.resume().get(5,TimeUnit.SECONDS);persistent.input(new ExecutionInput(16,0,0));awaitColor(persistent,0,255,0,logs);persistent.stopAsync().get(5,TimeUnit.SECONDS);}}
|
||||
byte[] saved=Files.readAllBytes(image);
|
||||
var disposable=gateway.start(project,setup,logs::add,new PlayOptions(true));
|
||||
try{disposable.startExecution().get(5,TimeUnit.SECONDS);awaitColor(disposable,0,0,255,logs);disposable.stopAsync().get(5,TimeUnit.SECONDS);}
|
||||
finally{disposable.close();}
|
||||
assertArrayEquals(saved,Files.readAllBytes(image),"Explicit disposable Play must leave selected persistent media intact");
|
||||
Files.writeString(root.resolve("src/main.pbs"),MemcardInstalledRuntimeTest.READER);
|
||||
var readBuild=shipper.prepare(project,e->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS);assertTrue(readBuild.success(),readBuild.diagnostics().toString());
|
||||
var reader=(HeadlessProcessSession)headless.boot(project,"read-studio-save",readBuild,
|
||||
Map.of("memcard",Map.of("path",image.toString(),"action","open","access","read_write"),"memcardChoice","persistent"));
|
||||
try{assertEquals(p.studio.api.automation.AutomationOutcome.Kind.SUCCEEDED,reader.advance(1,e->{}).kind());}
|
||||
finally{reader.shutdown().toCompletableFuture().get(7,TimeUnit.SECONDS);}
|
||||
assertArrayEquals(saved,Files.readAllBytes(image),"Headless reader must not resave");
|
||||
var missing=new ProjectLocalStudioSetup(setup.prometeuRuntimePath(),null,null,root.resolve("absent.pmc").toString());
|
||||
assertThrows(java.io.IOException.class,()->gateway.start(project,missing,logs::add,PlayOptions.PERSISTENT));assertFalse(Files.exists(root.resolve("absent.pmc")));
|
||||
}
|
||||
}
|
||||
static void awaitColor(RuntimeConnection connection,int b,int g,int r,List<RuntimeLogEntry> logs)throws Exception{
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(5);
|
||||
while(System.nanoTime()<deadline){try(var frame=connection.acquireLatestFrame()){
|
||||
if(frame!=null){var p=frame.pixels();if((p.get(0)&255)==b&&(p.get(1)&255)==g&&(p.get(2)&255)==r)return;}}
|
||||
Thread.sleep(10);
|
||||
}fail("Native image did not reach expected color: "+logs);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.util.Arrays;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class LatestFramePoolTest {
|
||||
@Test void slowPresentationKeepsLeaseStableAndSkipsPendingFrames()throws Exception {
|
||||
var pool=new LatestFramePool(2,1);
|
||||
byte[] first=pool.receive();Arrays.fill(first,(byte)7);pool.publish(first,1,1);
|
||||
var held=pool.acquire();assertNotNull(held);assertNull(pool.acquire());
|
||||
for(int i=2;i<=100;i++){byte[] next=pool.receive();Arrays.fill(next,(byte)i);pool.publish(next,i,1);}
|
||||
assertEquals(7,held.pixels().get(0));assertTrue(held.pixels().isReadOnly());
|
||||
held.close();held.close();
|
||||
try(var latest=pool.acquire()){assertEquals(100,latest.frameId());assertEquals(100,latest.pixels().get(0));}
|
||||
assertNull(pool.acquire());pool.close();assertThrows(java.io.IOException.class,pool::receive);
|
||||
}
|
||||
@Test void rgbaConversionPremultipliesAndOrdersChannels(){
|
||||
byte[] bytes=java.util.HexFormat.of().parseHex("ff0000ff0000ff80ffffffff");
|
||||
LatestFramePool.rgbaToBgraPre(bytes);
|
||||
assertArrayEquals(java.util.HexFormat.of().parseHex("0000ffff80000080ffffffff"),bytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import p.studio.api.execution.ExecutionFrame;
|
||||
import p.studio.api.runtime.RuntimeLogEntry;
|
||||
import java.io.*;
|
||||
import java.net.*;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.nio.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static p.studio.app.runtime.studio.StudioWire.*;
|
||||
import p.studio.app.runtime.studio.StudioWire.Reader;
|
||||
import p.studio.app.runtime.studio.StudioWire.Writer;
|
||||
|
||||
/** Java adapter against the actual Rust host and an existing native cartridge. */
|
||||
@org.junit.jupiter.api.Tag("integration")
|
||||
class StudioPlayProcessTest {
|
||||
static final class Native implements AutoCloseable {
|
||||
final ExecutorService io=Executors.newVirtualThreadPerTaskExecutor();
|
||||
final List<String> logs=new CopyOnWriteArrayList<>();
|
||||
Process process;Socket control,video;StudioRuntimeConnection connection;
|
||||
Native()throws Exception {
|
||||
try(ServerSocket c=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"));
|
||||
ServerSocket v=new ServerSocket(0,4,InetAddress.getByName("127.0.0.1"))){
|
||||
process=new ProcessBuilder(System.getProperty("studio.test.studioHost"),"--studio","--run",
|
||||
System.getProperty("studio.test.studioCartridge")).start();
|
||||
var stdout=StudioRuntimeGateway.drain(process.getInputStream(),false,e->logs.add(e.message()),io);
|
||||
var stderr=StudioRuntimeGateway.drain(process.getErrorStream(),true,e->logs.add(e.message()),io);
|
||||
byte[] session=new byte[16],token=new byte[32];Arrays.fill(session,(byte)3);Arrays.fill(token,(byte)7);
|
||||
try(var input=process.getOutputStream()){new Writer(input).send(BOOTSTRAP,0,little(53)
|
||||
.put(session).put(token).putShort((short)c.getLocalPort()).putShort((short)v.getLocalPort()).put((byte)1).array());}
|
||||
c.setSoTimeout(10000);v.setSoTimeout(10000);control=c.accept();video=v.accept();
|
||||
control.setSoTimeout(10000);video.setSoTimeout(10000);
|
||||
Reader cr=new Reader(control.getInputStream()),vr=new Reader(video.getInputStream());
|
||||
assertEquals(HELLO,cr.receive().header().kind());assertEquals(HELLO,vr.receive().header().kind());
|
||||
var ready=cr.receive();assertEquals(READY,ready.header().kind());
|
||||
var b=ByteBuffer.wrap(ready.payload()).order(ByteOrder.LITTLE_ENDIAN);int width=b.getInt(),height=b.getInt();
|
||||
control.setSoTimeout(0);video.setSoTimeout(0);
|
||||
connection=new StudioRuntimeConnection(process,control,video,cr,vr,session,width,height,e->logs.add(e.message()),io,stdout,stderr);
|
||||
}catch(Throwable failure){close();throw failure;}
|
||||
}
|
||||
ExecutionFrame image()throws Exception {
|
||||
long deadline=System.nanoTime()+TimeUnit.SECONDS.toNanos(3);
|
||||
while(System.nanoTime()<deadline){ExecutionFrame frame=connection.acquireLatestFrame();if(frame!=null)return frame;Thread.sleep(5);}
|
||||
fail("No complete image: "+logs);return null;
|
||||
}
|
||||
@Override public void close(){
|
||||
if(process!=null&&process.isAlive())process.destroyForcibly();
|
||||
StudioRuntimeGateway.close(control);StudioRuntimeGateway.close(video);
|
||||
if(process!=null)try{process.waitFor(3,TimeUnit.SECONDS);}catch(InterruptedException e){Thread.currentThread().interrupt();}
|
||||
if(connection!=null)try{connection.completion().get(3,TimeUnit.SECONDS);}catch(Exception ignored){}
|
||||
io.shutdownNow();
|
||||
}
|
||||
}
|
||||
@Test void liveFramesRemainStableDuringSlowPresentationAndStopIsConfirmed()throws Exception {
|
||||
try(var s=new Native()){
|
||||
long pid=s.process.pid();s.connection.startExecution().get(3,TimeUnit.SECONDS);
|
||||
long first;
|
||||
try(var held=s.image()){
|
||||
first=held.frameId();byte pixel=held.pixels().get(0);
|
||||
Thread.sleep(150);assertEquals(pixel,held.pixels().get(0));assertNull(s.connection.acquireLatestFrame());
|
||||
}
|
||||
try(var recent=s.image()){assertTrue(recent.frameId()>first+1);}
|
||||
s.connection.pause().get(3,TimeUnit.SECONDS);Thread.sleep(40);
|
||||
try(var finalFrame=s.connection.acquireLatestFrame()){/* Drain an asynchronous final publication. */}
|
||||
Thread.sleep(40);assertNull(s.connection.acquireLatestFrame());
|
||||
s.connection.resume().get(3,TimeUnit.SECONDS);try(var resumed=s.image()){assertTrue(resumed.frameId()>first);}
|
||||
assertEquals(pid,s.process.pid());s.connection.stopAsync().get(5,TimeUnit.SECONDS);
|
||||
assertEquals(0,s.connection.completion().get(1,TimeUnit.SECONDS));assertFalse(s.process.isAlive());
|
||||
assertTrue(s.logs.stream().anyMatch(line->line.contains("Runtime stopped")));
|
||||
}
|
||||
}
|
||||
@Test void pauseBeforeStartWaitsForExplicitResume()throws Exception {
|
||||
try(var s=new Native()){
|
||||
s.connection.pause().get(3,TimeUnit.SECONDS);s.connection.startExecution().get(3,TimeUnit.SECONDS);
|
||||
Thread.sleep(80);assertNull(s.connection.acquireLatestFrame());
|
||||
s.connection.resume().get(3,TimeUnit.SECONDS);try(var image=s.image()){assertEquals(480,image.width());}
|
||||
s.connection.stopAsync().get(5,TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
@Test void brokenVideoAndControlKillTheOwnedProcessAndKeepLogs()throws Exception {
|
||||
for(boolean video:new boolean[]{true,false})try(var s=new Native()){
|
||||
s.connection.startExecution().get(3,TimeUnit.SECONDS);
|
||||
if(video)s.video.close();else s.control.close();
|
||||
assertThrows(ExecutionException.class,()->s.connection.completion().get(4,TimeUnit.SECONDS));
|
||||
assertFalse(s.process.isAlive());assertTrue(s.logs.stream().anyMatch(line->line.contains("connection failed")));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package p.studio.app.runtime.studio;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.io.*;
|
||||
import java.nio.file.*;
|
||||
import java.util.HexFormat;
|
||||
import p.studio.app.runtime.studio.StudioWire.Reader;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static p.studio.app.runtime.studio.StudioWire.*;
|
||||
|
||||
class StudioWireTest {
|
||||
@Test void blankNativeLinesDoNotStopBoundedLogDrain() {
|
||||
var logs=new java.util.ArrayList<p.studio.api.runtime.RuntimeLogEntry>();
|
||||
String output="\n \r\nready\n"+"x".repeat(9000)+"\nlast";
|
||||
StudioRuntimeGateway.drain(new ByteArrayInputStream(output.getBytes(java.nio.charset.StandardCharsets.UTF_8)),false,logs::add,Runnable::run).join();
|
||||
assertEquals(3,logs.size());assertEquals("ready",logs.getFirst().message());
|
||||
assertEquals(8193,logs.get(1).message().length());assertEquals("last",logs.getLast().message());
|
||||
}
|
||||
private byte[] fixture() throws IOException {
|
||||
String hex=Files.readString(Path.of(System.getProperty("studio.test.protocolFixtures"),"pause.hex"));
|
||||
return HexFormat.of().parseHex(hex.replaceAll("\\s+",""));
|
||||
}
|
||||
@Test void headerMatchesSharedRustFixture() throws Exception {
|
||||
assertArrayEquals(fixture(),new Header(PAUSE,0,1,42).encode());
|
||||
assertEquals(42,Header.decode(fixture()).request());
|
||||
}
|
||||
@Test void fragmentedReadsWorkButTruncationAndReplayFail() throws Exception {
|
||||
byte[] bytes=fixture();
|
||||
InputStream fragmented=new FilterInputStream(new ByteArrayInputStream(bytes)) {
|
||||
@Override public int read(byte[] b,int off,int len)throws IOException {return super.read(b,off,Math.min(len,3));}
|
||||
};
|
||||
assertEquals(PAUSE,new Reader(fragmented).receive().header().kind());
|
||||
assertThrows(EOFException.class,()->new Reader(new ByteArrayInputStream(bytes,0,31)).receive());
|
||||
var twice=new ByteArrayOutputStream();twice.write(bytes);twice.write(bytes);
|
||||
var reader=new Reader(new ByteArrayInputStream(twice.toByteArray()));reader.receive();
|
||||
assertThrows(IOException.class,reader::receive);
|
||||
}
|
||||
@Test void validatesBeforeAllocatingPayload() throws Exception {
|
||||
for(int offset:new int[]{0,4,6,8,10}) {byte[] bad=fixture();bad[offset]=(byte)255;
|
||||
assertThrows(IOException.class,()->Header.decode(bad));}
|
||||
byte[] huge=fixture();java.util.Arrays.fill(huge,12,16,(byte)255);
|
||||
assertThrows(IOException.class,()->Header.decode(huge));
|
||||
assertThrows(IOException.class,()->frameBytes(Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE));
|
||||
assertThrows(IOException.class,()->frameBytes(480,270,481));
|
||||
assertEquals(518400,frameBytes(480,270,480));
|
||||
assertThrows(IOException.class,()->text(new byte[]{(byte)0xff},0));
|
||||
}
|
||||
@Test void rgbaPayloadMatchesSharedFixture() throws Exception {
|
||||
byte[] bytes=HexFormat.of().parseHex(Files.readString(Path.of(
|
||||
System.getProperty("studio.test.protocolFixtures"),"rgba.hex")).replaceAll("\\s+",""));
|
||||
var reader=new Reader(new ByteArrayInputStream(bytes));var h=reader.nextHeader();
|
||||
assertEquals(FRAME,h.kind());assertEquals(56,h.length());
|
||||
byte[] metadata=new byte[48];reader.readFully(metadata,0,48);
|
||||
var b=java.nio.ByteBuffer.wrap(metadata).order(java.nio.ByteOrder.LITTLE_ENDIAN);
|
||||
b.position(16);assertEquals(1,b.getLong());assertEquals(7,b.getLong());
|
||||
int width=b.getInt(),height=b.getInt(),stride=b.getInt();assertEquals(RGBA8,b.getInt());
|
||||
byte[] pixels=new byte[frameBytes(width,height,stride)];reader.readFully(pixels,0,pixels.length);
|
||||
assertArrayEquals(HexFormat.of().parseHex("ff0000ff0000ff80"),pixels);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user