implement DEV workspace and project automation authority
This commit is contained in:
+15
-6
@@ -10,6 +10,13 @@ import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStorage {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public FileSystemAssetWorkspaceStorage() { }
|
||||
public FileSystemAssetWorkspaceStorage(p.studio.api.automation.ProjectAccess access) {
|
||||
this();
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Path assetsRoot(ProjectReference projectReference) {
|
||||
return Objects.requireNonNull(projectReference, "projectReference")
|
||||
@@ -21,12 +28,14 @@ public final class FileSystemAssetWorkspaceStorage implements AssetWorkspaceStor
|
||||
|
||||
@Override
|
||||
public AssetWorkspacePreparation prepare(ProjectReference projectReference) {
|
||||
final Path root = assetsRoot(projectReference);
|
||||
try {
|
||||
Files.createDirectories(root);
|
||||
return new AssetWorkspacePreparation(true, root, "");
|
||||
} catch (IOException exception) {
|
||||
return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory."));
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(projectReference.rootPath())) {
|
||||
final Path root = assetsRoot(projectReference);
|
||||
try {
|
||||
Files.createDirectories(root);
|
||||
return new AssetWorkspacePreparation(true, root, "");
|
||||
} catch (IOException exception) {
|
||||
return new AssetWorkspacePreparation(false, root, Objects.requireNonNullElse(exception.getMessage(), "Unable to prepare assets directory."));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,12 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetCatalog implements AssetCatalog {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public PackerAssetCatalog(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
|
||||
this(packer);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerAssetCatalog(PackerWorkspaceService packer) {
|
||||
@@ -22,20 +28,22 @@ public final class PackerAssetCatalog implements AssetCatalog {
|
||||
|
||||
@Override
|
||||
public List<AssetSummary> list(ProjectReference projectReference, boolean deepSync) {
|
||||
final var context = new p.packer.messages.PackerProjectContext(
|
||||
projectReference.name(),
|
||||
projectReference.rootPath());
|
||||
return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream()
|
||||
.map(summary -> new AssetSummary(
|
||||
AssetReference.of(summary.assetReference().value()),
|
||||
summary.identity().assetName(),
|
||||
AssetRegistrationState.valueOf(summary.state().name()),
|
||||
AssetBuildParticipation.valueOf(summary.buildParticipation().name()),
|
||||
summary.identity().assetId(),
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics()))
|
||||
.toList();
|
||||
try (p.studio.api.automation.ManualLease accessLease = deepSync ? access.enterManual(projectReference.rootPath()) : () -> {}) {
|
||||
final var context = new p.packer.messages.PackerProjectContext(
|
||||
projectReference.name(),
|
||||
projectReference.rootPath());
|
||||
return packer.listAssets(new ListAssetsRequest(context, deepSync)).assets().stream()
|
||||
.map(summary -> new AssetSummary(
|
||||
AssetReference.of(summary.assetReference().value()),
|
||||
summary.identity().assetName(),
|
||||
AssetRegistrationState.valueOf(summary.state().name()),
|
||||
AssetBuildParticipation.valueOf(summary.buildParticipation().name()),
|
||||
summary.identity().assetId(),
|
||||
AssetFamily.valueOf(summary.assetFamily().name()),
|
||||
summary.identity().assetRoot(),
|
||||
summary.preloadEnabled(),
|
||||
summary.hasDiagnostics()))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,12 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetCommands implements AssetCommands {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public PackerAssetCommands(PackerWorkspaceService packer, p.studio.api.automation.ProjectAccess access) {
|
||||
this(packer);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
private final PackerWorkspaceService packer;
|
||||
|
||||
public PackerAssetCommands(PackerWorkspaceService packer) {
|
||||
@@ -23,64 +29,80 @@ public final class PackerAssetCommands implements AssetCommands {
|
||||
@Override
|
||||
public AssetMutationResult create(ProjectReference project, String assetRoot, String assetName,
|
||||
AssetFamily assetFamily, String outputFormat, String outputCodec, boolean preloadEnabled) {
|
||||
final var result = packer.createAsset(new CreateAssetRequest(
|
||||
context(project), assetRoot, assetName,
|
||||
AssetFamilyCatalog.valueOf(assetFamily.name()),
|
||||
OutputFormatCatalog.valueOf(outputFormat),
|
||||
OutputCodecCatalog.valueOf(outputCodec),
|
||||
preloadEnabled));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.createAsset(new CreateAssetRequest(
|
||||
context(project), assetRoot, assetName,
|
||||
AssetFamilyCatalog.valueOf(assetFamily.name()),
|
||||
OutputFormatCatalog.valueOf(outputFormat),
|
||||
OutputCodecCatalog.valueOf(outputCodec),
|
||||
preloadEnabled));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult move(ProjectReference project, AssetReference assetReference, String targetRoot) {
|
||||
final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.moveAsset(new MoveAssetRequest(context(project), reference(assetReference), targetRoot));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult register(ProjectReference project, AssetReference assetReference) {
|
||||
final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.registerAsset(new RegisterAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult delete(ProjectReference project, AssetReference assetReference) {
|
||||
final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.deleteAsset(new DeleteAssetRequest(context(project), reference(assetReference)));
|
||||
return mutation(result.status(), result.summary(), reference(assetReference), result.assetRoot(), result.manifestPath());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetMutationResult updateBuildParticipation(ProjectReference project, AssetReference assetReference,
|
||||
boolean includeInBuild) {
|
||||
final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest(
|
||||
context(project), reference(assetReference), includeInBuild));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), null, null);
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.updateAssetBuildParticipation(new UpdateAssetBuildParticipationRequest(
|
||||
context(project), reference(assetReference), includeInBuild));
|
||||
return mutation(result.status(), result.summary(), result.assetReference(), null, null);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult updateContract(ProjectReference project, AssetReference assetReference, boolean preload,
|
||||
String outputCodec, Map<String, String> codecFieldValues, Map<String, String> metadataFieldValues) {
|
||||
final var result = packer.updateAssetContract(new UpdateAssetContractRequest(
|
||||
context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec),
|
||||
codecFieldValues, metadataFieldValues));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.updateAssetContract(new UpdateAssetContractRequest(
|
||||
context(project), reference(assetReference), preload, OutputCodecCatalog.valueOf(outputCodec),
|
||||
codecFieldValues, metadataFieldValues));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult applyBankComposition(ProjectReference project, AssetReference assetReference,
|
||||
List<String> selectedPaths) {
|
||||
final var result = packer.applyBankComposition(new ApplyBankCompositionRequest(
|
||||
context(project), reference(assetReference), selectedPaths));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.applyBankComposition(new ApplyBankCompositionRequest(
|
||||
context(project), reference(assetReference), selectedPaths));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public AssetUpdateResult applyPaletteOverhauling(ProjectReference project, AssetReference assetReference,
|
||||
List<Map<String, Object>> selectedPalettes) {
|
||||
final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest(
|
||||
context(project), reference(assetReference), selectedPalettes));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(project.rootPath())) {
|
||||
final var result = packer.applyPaletteOverhauling(new ApplyPaletteOverhaulingRequest(
|
||||
context(project), reference(assetReference), selectedPalettes));
|
||||
return new AssetUpdateResult(result.success(), result.errorMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static PackerProjectContext context(ProjectReference project) {
|
||||
|
||||
@@ -10,6 +10,12 @@ import p.studio.api.operation.OperationHandle;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class PackerAssetPacking implements AssetPacking {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public PackerAssetPacking(PackerWorkspaceService packer, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
|
||||
this(packer, operations);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
private final PackerWorkspaceService packer;
|
||||
private final OperationExecutor operations;
|
||||
|
||||
@@ -20,7 +26,7 @@ public final class PackerAssetPacking implements AssetPacking {
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetSyncResult> deepSync(ProjectReference project) {
|
||||
return operations.submit("Synchronize project assets", () -> deepSyncNow(project));
|
||||
return access.submitManual(project.rootPath(), operations, "Synchronize project assets", () -> deepSyncNow(project));
|
||||
}
|
||||
|
||||
private AssetSyncResult deepSyncNow(ProjectReference project) {
|
||||
@@ -63,7 +69,7 @@ public final class PackerAssetPacking implements AssetPacking {
|
||||
|
||||
@Override
|
||||
public OperationHandle<AssetPackExecution> pack(ProjectReference project) {
|
||||
return operations.submit("Pack project assets", () -> packNow(project));
|
||||
return access.submitManual(project.rootPath(), operations, "Pack project assets", () -> packNow(project));
|
||||
}
|
||||
|
||||
private AssetPackExecution packNow(ProjectReference project) {
|
||||
|
||||
+27
-15
@@ -18,6 +18,12 @@ import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
public final class AssetStudioMetadataService implements AssetMetadataService {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public AssetStudioMetadataService(ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
|
||||
this(mapper);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
public static final String STUDIO_ASSET_METADATA_FILE = "studio.asset.json";
|
||||
public static final String SCENE_BANK_SUPPORT_FILE = "scene-bank.studio.json";
|
||||
public static final String GLYPH_MATERIAL_SUPPORT_FILE = "glyph-material.json";
|
||||
@@ -43,11 +49,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService {
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeSceneBankMetadata(Path assetRoot, AssetStudioSceneBankMetadata metadata) {
|
||||
try {
|
||||
writeSceneBankMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception));
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) {
|
||||
try {
|
||||
writeSceneBankMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write scene-bank metadata.", exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,11 +99,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService {
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeGlyphSpecialization(Path assetRoot, AssetStudioGlyphSpecialization specialization) {
|
||||
try {
|
||||
writeGlyphSpecializationFile(assetRoot, specialization);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception));
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) {
|
||||
try {
|
||||
writeGlyphSpecializationFile(assetRoot, specialization);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph specialization metadata.", exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,11 +129,13 @@ public final class AssetStudioMetadataService implements AssetMetadataService {
|
||||
|
||||
@Override
|
||||
public AssetMetadataWriteResult writeGlyphMaterialMetadata(Path assetRoot, AssetStudioGlyphMaterialMetadata metadata) {
|
||||
try {
|
||||
writeGlyphMaterialMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception));
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(assetRoot)) {
|
||||
try {
|
||||
writeGlyphMaterialMetadataFile(assetRoot, metadata);
|
||||
return AssetMetadataWriteResult.success();
|
||||
} catch (IOException exception) {
|
||||
return AssetMetadataWriteResult.failure(message("Unable to write glyph-material metadata.", exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+9
-1
@@ -23,6 +23,12 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class SceneBankWorkflowService implements SceneBankWorkflow {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public SceneBankWorkflowService(AssetCatalog assetCatalog, ObjectMapper mapper, p.studio.api.automation.ProjectAccess access) {
|
||||
this(assetCatalog, mapper);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
public static final String ACCEPTED_REQUEST_FILE = "scene-bank.pack-request.json";
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
@@ -60,10 +66,12 @@ public final class SceneBankWorkflowService implements SceneBankWorkflow {
|
||||
}
|
||||
final List<AssetDiagnostic> diagnostics = new ArrayList<>(validateDiagnostics(projectReference, details));
|
||||
if (diagnostics.stream().noneMatch(AssetDiagnostic::blocking)) {
|
||||
try {
|
||||
try (var accessLease = access.enterManual(projectReference.rootPath())) {
|
||||
writeAcceptedRequest(
|
||||
details.summary().assetRoot().resolve(ACCEPTED_REQUEST_FILE),
|
||||
buildCanonicalRequest(projectReference, details));
|
||||
} catch (p.studio.api.automation.ControlDeniedException locked) {
|
||||
// Inspection remains available while ceded; do not persist derived requests.
|
||||
} catch (IOException | IllegalArgumentException exception) {
|
||||
diagnostics.add(error(
|
||||
"Unable to persist canonical scene-pack request: " + exception.getMessage(),
|
||||
|
||||
+250
-230
@@ -25,6 +25,12 @@ import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class TiledAssetGenerationService implements TiledAssetService {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public TiledAssetGenerationService(AssetMetadataService metadataService, p.studio.api.automation.ProjectAccess access) {
|
||||
this(metadataService);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
public static final String GENERATED_TSX_FILE = "tileset.tsx";
|
||||
|
||||
private static final long FLIP_HORIZONTAL_FLAG = 0x80000000L;
|
||||
@@ -49,61 +55,71 @@ public final class TiledAssetGenerationService implements TiledAssetService {
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateTilesetTsx(AssetWorkspaceAssetDetails details) {
|
||||
return exportTilesetTsx(details);
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
return exportTilesetTsx(details);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TiledAssetGenerationResult exportTilesetTsx(AssetWorkspaceAssetDetails details) {
|
||||
if (details == null
|
||||
|| details.summary().assetFamily() != AssetFamily.GLYPH_BANK
|
||||
|| details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) {
|
||||
return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> selectedFiles = details.bankComposition().selectedFiles();
|
||||
if (selectedFiles.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of());
|
||||
}
|
||||
final int tileSize = parseTileSize(details.metadataFields());
|
||||
final List<TiledTilesetTile> tiles = new ArrayList<>();
|
||||
for (int index = 0; index < selectedFiles.size(); index += 1) {
|
||||
final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index);
|
||||
tiles.add(new TiledTilesetTile(
|
||||
index,
|
||||
file.path(),
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
if (details == null
|
||||
|| details.summary().assetFamily() != AssetFamily.GLYPH_BANK
|
||||
|| details.summary().glyphSpecialization() != AssetStudioGlyphSpecialization.TILESET) {
|
||||
return new TiledAssetGenerationResult(false, "TSX export is available only for Tileset-specialized glyph banks.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetWorkspaceBankCompositionFile> selectedFiles = details.bankComposition().selectedFiles();
|
||||
if (selectedFiles.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "The selected tileset bank has no included glyph artifacts.", List.of(), List.of());
|
||||
}
|
||||
final int tileSize = parseTileSize(details.metadataFields());
|
||||
final List<TiledTilesetTile> tiles = new ArrayList<>();
|
||||
for (int index = 0; index < selectedFiles.size(); index += 1) {
|
||||
final AssetWorkspaceBankCompositionFile file = selectedFiles.get(index);
|
||||
tiles.add(new TiledTilesetTile(
|
||||
index,
|
||||
file.path(),
|
||||
tileSize,
|
||||
tileSize,
|
||||
List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))),
|
||||
null));
|
||||
}
|
||||
final TiledTilesetDocument document = new TiledTilesetDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
details.summary().assetName(),
|
||||
tileSize,
|
||||
tileSize,
|
||||
List.of(new TiledProperty("glyph_id", "int", Integer.toString(index))),
|
||||
null));
|
||||
}
|
||||
final TiledTilesetDocument document = new TiledTilesetDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
details.summary().assetName(),
|
||||
tileSize,
|
||||
tileSize,
|
||||
tiles.size(),
|
||||
0,
|
||||
List.of(),
|
||||
tiles);
|
||||
final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE);
|
||||
try {
|
||||
codec.writeTileset(outputPath, document);
|
||||
return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath));
|
||||
} catch (IOException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of());
|
||||
tiles.size(),
|
||||
0,
|
||||
List.of(),
|
||||
tiles);
|
||||
final Path outputPath = details.summary().assetRoot().resolve(GENERATED_TSX_FILE);
|
||||
try {
|
||||
codec.writeTileset(outputPath, document);
|
||||
return new TiledAssetGenerationResult(true, "Exported TSX successfully.", List.of(), List.of(outputPath));
|
||||
} catch (IOException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TSX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateSceneBankTilemaps(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
}
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult generateSceneBankTilemap(ProjectReference projectReference, AssetWorkspaceAssetDetails details, int layerIndex) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
return exportSceneBankTmx(projectReference, details);
|
||||
}
|
||||
}
|
||||
|
||||
public TiledAssetGenerationResult exportSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE);
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
return exportSceneBankTmx(projectReference, details, SceneTmxExportDisposition.OVERWRITE);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -111,221 +127,225 @@ public final class TiledAssetGenerationService implements TiledAssetService {
|
||||
ProjectReference projectReference,
|
||||
AssetWorkspaceAssetDetails details,
|
||||
SceneTmxExportDisposition disposition) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
if (enabledLayers.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of());
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final List<TiledTileLayer> tileLayers = new ArrayList<>();
|
||||
int nextLayerId = 1;
|
||||
for (AssetStudioSceneLayerBinding binding : enabledLayers) {
|
||||
final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot());
|
||||
final List<Long> gids = new ArrayList<>(binding.tiles().size());
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
if (!tile.active()) {
|
||||
gids.add(0L);
|
||||
continue;
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX export is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
if (enabledLayers.isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "Enable at least one layer before exporting TMX.", List.of(), List.of());
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX export requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final List<TiledTileLayer> tileLayers = new ArrayList<>();
|
||||
int nextLayerId = 1;
|
||||
for (AssetStudioSceneLayerBinding binding : enabledLayers) {
|
||||
final TilesetRef ref = context.tilesetByAssetRoot().get(binding.tilesetAssetRoot());
|
||||
final List<Long> gids = new ArrayList<>(binding.tiles().size());
|
||||
for (AssetStudioSceneTile tile : binding.tiles()) {
|
||||
if (!tile.active()) {
|
||||
gids.add(0L);
|
||||
continue;
|
||||
}
|
||||
if (tile.glyphId() >= ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Layer " + binding.index() + " references glyph_id outside the exported TSX range.",
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
long gid = ref.firstGid() + tile.glyphId();
|
||||
if (tile.flipX()) {
|
||||
gid |= FLIP_HORIZONTAL_FLAG;
|
||||
}
|
||||
if (tile.flipY()) {
|
||||
gid |= FLIP_VERTICAL_FLAG;
|
||||
}
|
||||
gids.add(gid);
|
||||
}
|
||||
if (tile.glyphId() >= ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Layer " + binding.index() + " references glyph_id outside the exported TSX range.",
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
long gid = ref.firstGid() + tile.glyphId();
|
||||
if (tile.flipX()) {
|
||||
gid |= FLIP_HORIZONTAL_FLAG;
|
||||
}
|
||||
if (tile.flipY()) {
|
||||
gid |= FLIP_VERTICAL_FLAG;
|
||||
}
|
||||
gids.add(gid);
|
||||
tileLayers.add(new TiledTileLayer(
|
||||
nextLayerId,
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
gids,
|
||||
List.of()));
|
||||
nextLayerId += 1;
|
||||
}
|
||||
tileLayers.add(new TiledTileLayer(
|
||||
final TiledMapDocument document = new TiledMapDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
"orthogonal",
|
||||
"right-down",
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1),
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1),
|
||||
context.tileSize(),
|
||||
context.tileSize(),
|
||||
nextLayerId,
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
gids,
|
||||
List.of()));
|
||||
nextLayerId += 1;
|
||||
1,
|
||||
List.of(),
|
||||
context.tilesetRefs(),
|
||||
tileLayers,
|
||||
List.of());
|
||||
final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
final ArrayList<Path> writtenFiles = new ArrayList<>();
|
||||
if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) {
|
||||
final Path backupPath = nextSceneTmxBackupPath(outputPath);
|
||||
Files.copy(outputPath, backupPath);
|
||||
writtenFiles.add(backupPath);
|
||||
}
|
||||
codec.writeMap(outputPath, document);
|
||||
writtenFiles.add(outputPath);
|
||||
return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
final TiledMapDocument document = new TiledMapDocument(
|
||||
"1.10",
|
||||
"1.12.1",
|
||||
"orthogonal",
|
||||
"right-down",
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::width).max().orElse(1),
|
||||
enabledLayers.stream().mapToInt(AssetStudioSceneLayerBinding::height).max().orElse(1),
|
||||
context.tileSize(),
|
||||
context.tileSize(),
|
||||
nextLayerId,
|
||||
1,
|
||||
List.of(),
|
||||
context.tilesetRefs(),
|
||||
tileLayers,
|
||||
List.of());
|
||||
final Path outputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
final ArrayList<Path> writtenFiles = new ArrayList<>();
|
||||
if (disposition == SceneTmxExportDisposition.KEEP_BOTH && Files.isRegularFile(outputPath)) {
|
||||
final Path backupPath = nextSceneTmxBackupPath(outputPath);
|
||||
Files.copy(outputPath, backupPath);
|
||||
writtenFiles.add(backupPath);
|
||||
}
|
||||
codec.writeMap(outputPath, document);
|
||||
writtenFiles.add(outputPath);
|
||||
return new TiledAssetGenerationResult(true, "Exported TMX successfully.", enabledLayers, List.copyOf(writtenFiles));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to export TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public TiledAssetGenerationResult importSceneBankTmx(ProjectReference projectReference, AssetWorkspaceAssetDetails details) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
if (!Files.isRegularFile(inputPath)) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final TiledMapDocument map = codec.readMap(inputPath);
|
||||
if (map.tileLayers().isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of());
|
||||
try (p.studio.api.automation.ManualLease accessLease = access.enterManual(details.summary().assetRoot())) {
|
||||
if (details == null || details.summary().assetFamily() != AssetFamily.SCENE_BANK) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import is available only for Scene Bank assets.", List.of(), List.of());
|
||||
}
|
||||
if (map.tileLayers().size() > metadata.layerCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of());
|
||||
final AssetStudioSceneBankMetadata metadata = details.sceneBankMetadata();
|
||||
if (metadata == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene Bank support metadata is missing or invalid.", List.of(), List.of());
|
||||
}
|
||||
if (map.tilesets().size() != context.tilesetRefs().size()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of());
|
||||
final String sceneTilemap = resolveSceneTilemap(metadata);
|
||||
if (sceneTilemap == null) {
|
||||
return new TiledAssetGenerationResult(false, "Scene TMX import requires a single shared tilemap binding across Scene Bank layers.", List.of(), List.of());
|
||||
}
|
||||
for (int index = 0; index < context.tilesetRefs().size(); index += 1) {
|
||||
if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of());
|
||||
final Path inputPath = details.summary().assetRoot().resolve(sceneTilemap);
|
||||
if (!Files.isRegularFile(inputPath)) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import source is missing: " + sceneTilemap, List.of(), List.of());
|
||||
}
|
||||
try {
|
||||
final List<AssetStudioSceneLayerBinding> enabledLayers = metadata.layerBindings().stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.toList();
|
||||
final ExportContext context = buildExportContext(projectReference, details, enabledLayers);
|
||||
final TiledMapDocument map = codec.readMap(inputPath);
|
||||
if (map.tileLayers().isEmpty()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: at least one tile layer is required.", List.of(), List.of());
|
||||
}
|
||||
if (map.tileLayers().size() > metadata.layerCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: more than four tile layers are not supported.", List.of(), List.of());
|
||||
}
|
||||
if (map.tilesets().size() != context.tilesetRefs().size()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset count.", List.of(), List.of());
|
||||
}
|
||||
for (int index = 0; index < context.tilesetRefs().size(); index += 1) {
|
||||
if (!context.tilesetRefs().get(index).source().equals(map.tilesets().get(index).source())) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: unexpected tileset reference.", List.of(), List.of());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final List<AssetStudioSceneLayerBinding> updatedBindings = new ArrayList<>();
|
||||
for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) {
|
||||
final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex);
|
||||
if (bindingIndex >= map.tileLayers().size()) {
|
||||
final List<AssetStudioSceneLayerBinding> updatedBindings = new ArrayList<>();
|
||||
for (int bindingIndex = 0; bindingIndex < metadata.layerBindings().size(); bindingIndex += 1) {
|
||||
final AssetStudioSceneLayerBinding binding = metadata.layerBindings().get(bindingIndex);
|
||||
if (bindingIndex >= map.tileLayers().size()) {
|
||||
updatedBindings.add(new AssetStudioSceneLayerBinding(
|
||||
false,
|
||||
binding.index(),
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
binding.tilemap(),
|
||||
binding.tilesetAssetRoot(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.defaultPaletteId(),
|
||||
binding.tiles()));
|
||||
continue;
|
||||
}
|
||||
final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex);
|
||||
if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of());
|
||||
}
|
||||
final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context);
|
||||
if (ref == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneTile> importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height());
|
||||
for (long rawGid : importedLayer.gids()) {
|
||||
if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of());
|
||||
}
|
||||
final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L;
|
||||
final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L;
|
||||
final long gid = rawGid & GID_MASK;
|
||||
if (gid == 0L) {
|
||||
importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId()));
|
||||
continue;
|
||||
}
|
||||
if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final int tilesetTileId = (int) (gid - ref.firstGid());
|
||||
final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId);
|
||||
if (glyphId == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of());
|
||||
}
|
||||
importedTiles.add(new AssetStudioSceneTile(
|
||||
true,
|
||||
glyphId,
|
||||
binding.defaultPaletteId(),
|
||||
flipX,
|
||||
flipY));
|
||||
}
|
||||
updatedBindings.add(new AssetStudioSceneLayerBinding(
|
||||
false,
|
||||
true,
|
||||
binding.index(),
|
||||
binding.layerName(),
|
||||
binding.width(),
|
||||
binding.height(),
|
||||
importedLayer.width(),
|
||||
importedLayer.height(),
|
||||
binding.tilemap(),
|
||||
binding.tilesetAssetRoot(),
|
||||
ref.assetRoot(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.defaultPaletteId(),
|
||||
binding.tiles()));
|
||||
continue;
|
||||
importedTiles));
|
||||
}
|
||||
final TiledTileLayer importedLayer = map.tileLayers().get(bindingIndex);
|
||||
if (importedLayer.gids().size() != importedLayer.width() * importedLayer.height()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer tile data does not match layer dimensions.", List.of(), List.of());
|
||||
final int mapWidth = Math.max(map.width(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::width)
|
||||
.max()
|
||||
.orElse(metadata.mapWidth()));
|
||||
final int mapHeight = Math.max(map.height(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::height)
|
||||
.max()
|
||||
.orElse(metadata.mapHeight()));
|
||||
final var metadataWrite = metadataService.writeSceneBankMetadata(
|
||||
details.summary().assetRoot(), new AssetStudioSceneBankMetadata(
|
||||
mapWidth,
|
||||
mapHeight,
|
||||
metadata.layerCount(),
|
||||
updatedBindings,
|
||||
metadata.supportFile()));
|
||||
if (!metadataWrite.successful()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Unable to import TMX: " + metadataWrite.message(),
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
final TilesetRef ref = resolveImportedLayerTilesetRef(importedLayer, binding, context);
|
||||
if (ref == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: layer uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final List<AssetStudioSceneTile> importedTiles = new ArrayList<>(importedLayer.width() * importedLayer.height());
|
||||
for (long rawGid : importedLayer.gids()) {
|
||||
if ((rawGid & FLIP_DIAGONAL_FLAG) != 0L) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: diagonal flips are not supported.", List.of(), List.of());
|
||||
}
|
||||
final boolean flipX = (rawGid & FLIP_HORIZONTAL_FLAG) != 0L;
|
||||
final boolean flipY = (rawGid & FLIP_VERTICAL_FLAG) != 0L;
|
||||
final long gid = rawGid & GID_MASK;
|
||||
if (gid == 0L) {
|
||||
importedTiles.add(AssetStudioSceneTile.inactive(binding.defaultPaletteId()));
|
||||
continue;
|
||||
}
|
||||
if (gid < ref.firstGid() || gid >= ref.firstGid() + ref.tileCount()) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tile uses an unexpected tileset.", List.of(), List.of());
|
||||
}
|
||||
final int tilesetTileId = (int) (gid - ref.firstGid());
|
||||
final Integer glyphId = ref.glyphIdByTileId().get(tilesetTileId);
|
||||
if (glyphId == null) {
|
||||
return new TiledAssetGenerationResult(false, "TMX import rejected: tileset tile is missing glyph_id mapping.", List.of(), List.of());
|
||||
}
|
||||
importedTiles.add(new AssetStudioSceneTile(
|
||||
true,
|
||||
glyphId,
|
||||
binding.defaultPaletteId(),
|
||||
flipX,
|
||||
flipY));
|
||||
}
|
||||
updatedBindings.add(new AssetStudioSceneLayerBinding(
|
||||
true,
|
||||
binding.index(),
|
||||
binding.layerName(),
|
||||
importedLayer.width(),
|
||||
importedLayer.height(),
|
||||
binding.tilemap(),
|
||||
ref.assetRoot(),
|
||||
binding.parallaxFactorX(),
|
||||
binding.parallaxFactorY(),
|
||||
binding.defaultPaletteId(),
|
||||
importedTiles));
|
||||
return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile()));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
final int mapWidth = Math.max(map.width(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::width)
|
||||
.max()
|
||||
.orElse(metadata.mapWidth()));
|
||||
final int mapHeight = Math.max(map.height(), updatedBindings.stream()
|
||||
.filter(AssetStudioSceneLayerBinding::enabled)
|
||||
.mapToInt(AssetStudioSceneLayerBinding::height)
|
||||
.max()
|
||||
.orElse(metadata.mapHeight()));
|
||||
final var metadataWrite = metadataService.writeSceneBankMetadata(
|
||||
details.summary().assetRoot(), new AssetStudioSceneBankMetadata(
|
||||
mapWidth,
|
||||
mapHeight,
|
||||
metadata.layerCount(),
|
||||
updatedBindings,
|
||||
metadata.supportFile()));
|
||||
if (!metadataWrite.successful()) {
|
||||
return new TiledAssetGenerationResult(
|
||||
false,
|
||||
"Unable to import TMX: " + metadataWrite.message(),
|
||||
List.of(),
|
||||
List.of());
|
||||
}
|
||||
return new TiledAssetGenerationResult(true, "Imported TMX successfully.", updatedBindings, List.of(inputPath, metadata.supportFile()));
|
||||
} catch (IOException | TiledUnsupportedFeatureException exception) {
|
||||
return new TiledAssetGenerationResult(false, "Unable to import TMX: " + exception.getMessage(), List.of(), List.of());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+5
-2
@@ -15,15 +15,18 @@ public final class DefaultExecutionControllerFactory implements ExecutionControl
|
||||
private final Shipper shipper;
|
||||
private final RuntimeGateway runtime;
|
||||
private final OperationExecutor operations;
|
||||
private final p.studio.api.automation.ProjectAccess access;
|
||||
|
||||
public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) {
|
||||
public DefaultExecutionControllerFactory(Shipper shipper, RuntimeGateway runtime, OperationExecutor operations,
|
||||
p.studio.api.automation.ProjectAccess access) {
|
||||
this.shipper = Objects.requireNonNull(shipper, "shipper");
|
||||
this.runtime = Objects.requireNonNull(runtime, "runtime");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
this.access = Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ExecutionController create(ProjectReference project, ProjectLocalStudioSetup setup, ExecutionSession session) {
|
||||
return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations);
|
||||
return new PlayStopExecutionController(project, setup, session, shipper, runtime, operations, access);
|
||||
}
|
||||
}
|
||||
|
||||
+28
-2
@@ -30,15 +30,24 @@ final class PlayStopExecutionController implements ExecutionController {
|
||||
private OperationHandle<ExecutionSnapshot> activeOperation;
|
||||
private OperationHandle<ShipperPrepareResult> preparationOperation;
|
||||
private boolean stopRequested;
|
||||
private final p.studio.api.automation.ProjectAccess access;
|
||||
private p.studio.api.automation.ManualLease manualLease;
|
||||
|
||||
PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup,
|
||||
ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations) {
|
||||
this(project, setup, session, shipper, runtime, operations, new p.studio.core.project.ProjectAccessRegistry());
|
||||
}
|
||||
|
||||
PlayStopExecutionController(ProjectReference project, ProjectLocalStudioSetup setup,
|
||||
ExecutionSession session, Shipper shipper, RuntimeGateway runtime, OperationExecutor operations,
|
||||
p.studio.api.automation.ProjectAccess access) {
|
||||
this.project = Objects.requireNonNull(project, "project");
|
||||
this.setup = Objects.requireNonNull(setup, "setup");
|
||||
this.session = Objects.requireNonNull(session, "session");
|
||||
this.shipper = Objects.requireNonNull(shipper, "shipper");
|
||||
this.runtime = Objects.requireNonNull(runtime, "runtime");
|
||||
this.operations = Objects.requireNonNull(operations, "operations");
|
||||
this.access = Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -47,9 +56,17 @@ final class PlayStopExecutionController implements ExecutionController {
|
||||
if (isBusy(session.snapshot().state()) && activeOperation != null) {
|
||||
return activeOperation;
|
||||
}
|
||||
if (manualLease != null) throw new p.studio.api.automation.ControlDeniedException(
|
||||
p.studio.api.automation.ControlResult.Status.BUSY);
|
||||
manualLease = access.enterManual(project.rootPath());
|
||||
manualLease.onProjectClose(this::stop);
|
||||
stopRequested = false;
|
||||
session.beginPreparationCycle();
|
||||
activeOperation = operations.submit("Run " + project.name(), this::runPlay);
|
||||
try { activeOperation = operations.submit("Run " + project.name(), this::runPlay); }
|
||||
catch (RuntimeException failure) { releaseManual(); throw failure; }
|
||||
activeOperation.termination().whenComplete((v, f) -> {
|
||||
synchronized (monitor) { if (!isBusy(session.snapshot().state()) || stopRequested) releaseManual(); }
|
||||
});
|
||||
return activeOperation;
|
||||
}
|
||||
}
|
||||
@@ -74,6 +91,7 @@ final class PlayStopExecutionController implements ExecutionController {
|
||||
if (state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING) {
|
||||
session.transitionToStopped();
|
||||
}
|
||||
if (execution == null || execution.termination().toCompletableFuture().isDone()) releaseManual();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -141,8 +159,10 @@ final class PlayStopExecutionController implements ExecutionController {
|
||||
private void handleExit(RuntimeConnection started, Integer exitCode, Throwable failure) {
|
||||
final boolean stopped;
|
||||
synchronized (monitor) {
|
||||
if (connection == started) connection = null;
|
||||
if (connection != started) return;
|
||||
connection = null;
|
||||
stopped = stopRequested;
|
||||
releaseManual();
|
||||
}
|
||||
if (stopped || session.snapshot().state() == ExecutionState.STOPPED) return;
|
||||
if (failure == null && exitCode != null && exitCode == 0) {
|
||||
@@ -159,6 +179,12 @@ final class PlayStopExecutionController implements ExecutionController {
|
||||
return state == ExecutionState.PREPARING || state == ExecutionState.CONNECTING || state == ExecutionState.RUNNING;
|
||||
}
|
||||
|
||||
private void releaseManual() {
|
||||
synchronized (monitor) {
|
||||
if (manualLease != null) { manualLease.close(); manualLease = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private static String message(Throwable failure) {
|
||||
return failure.getMessage() == null || failure.getMessage().isBlank()
|
||||
? failure.getClass().getSimpleName() : failure.getMessage();
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package p.studio.core.project;
|
||||
|
||||
import p.studio.api.automation.ManualLease;
|
||||
import p.studio.api.automation.ProjectAccess;
|
||||
import p.studio.api.operation.OperationSubscription;
|
||||
import java.nio.file.Path;
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/** Application-composed routing only; authority is owned by each project session. */
|
||||
public final class ProjectAccessRegistry implements ProjectAccess {
|
||||
private final Map<Path, Supplier<ManualLease>> projects = new HashMap<>();
|
||||
|
||||
public synchronized OperationSubscription register(Path root, Supplier<ManualLease> authority) {
|
||||
Path key = canonical(root);
|
||||
if (projects.putIfAbsent(key, authority) != null) throw new IllegalStateException("Project already open: " + key);
|
||||
return () -> { synchronized (this) { projects.remove(key, authority); } };
|
||||
}
|
||||
|
||||
@Override public ManualLease enterManual(Path path) {
|
||||
Supplier<ManualLease> authority;
|
||||
synchronized (this) {
|
||||
Path key = canonical(path);
|
||||
authority = projects.entrySet().stream().filter(e -> key.startsWith(e.getKey()))
|
||||
.max(java.util.Comparator.comparingInt(e -> e.getKey().getNameCount()))
|
||||
.map(Map.Entry::getValue).orElse(null);
|
||||
}
|
||||
// Project creation/setup before opening a session is still a manual workflow.
|
||||
return authority == null ? () -> {} : authority.get();
|
||||
}
|
||||
|
||||
private static Path canonical(Path path) {
|
||||
Path normalized = path.toAbsolutePath().normalize();
|
||||
try { return normalized.toRealPath(); }
|
||||
catch (IOException ignored) {
|
||||
Path parent = normalized.getParent();
|
||||
return parent == null ? normalized : canonical(parent).resolve(normalized.getFileName());
|
||||
}
|
||||
}
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.operation.*;
|
||||
import java.nio.file.Path;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Project authority is independent of any UI, transport connection or operation result. */
|
||||
public final class DefaultAutomationSession implements AutomationSession {
|
||||
private final Path root;
|
||||
private final OperationExecutor executor;
|
||||
private final List<Consumer<AutomationSnapshot>> listeners = new CopyOnWriteArrayList<>();
|
||||
private final List<DocumentHandoff> documents = new CopyOnWriteArrayList<>();
|
||||
private final Deque<String> calls = new ArrayDeque<>();
|
||||
private ControlState state = ControlState.MANUAL;
|
||||
private TaskIdentity task;
|
||||
private int manualOperations;
|
||||
private boolean handoffPending, closed, busy, stale;
|
||||
private long generation;
|
||||
private OperationHandle<AutomationOutcome> active;
|
||||
private ManagedHeadlessSession runtime;
|
||||
private CanonicalCapture capture;
|
||||
private List<String> diagnostics = List.of();
|
||||
private CompletableFuture<ControlResult> returning;
|
||||
private final List<Runnable> manualCancellation = new ArrayList<>();
|
||||
private CompletableFuture<Void> manualIdle = CompletableFuture.completedFuture(null);
|
||||
|
||||
public DefaultAutomationSession(Path root, OperationExecutor executor) {
|
||||
this.root = root.toAbsolutePath().normalize();
|
||||
this.executor = Objects.requireNonNull(executor);
|
||||
}
|
||||
|
||||
public synchronized ManualLease enterManual() {
|
||||
if (closed) throw new ControlDeniedException(ControlResult.Status.CLOSED);
|
||||
if (state != ControlState.MANUAL) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
if (manualOperations++ == 0) manualIdle = new CompletableFuture<>();
|
||||
stale = capture != null;
|
||||
publish();
|
||||
return new ManualLease() {
|
||||
private boolean released;
|
||||
private Runnable cancellation;
|
||||
@Override public void onProjectClose(Runnable action) {
|
||||
boolean cancel;
|
||||
synchronized (DefaultAutomationSession.this) {
|
||||
if (released) return;
|
||||
cancellation = action;
|
||||
manualCancellation.add(action);
|
||||
cancel = closed;
|
||||
}
|
||||
if (cancel) action.run();
|
||||
}
|
||||
@Override public void close() {
|
||||
synchronized (DefaultAutomationSession.this) {
|
||||
if (!released) {
|
||||
released = true; manualCancellation.remove(cancellation);
|
||||
if (--manualOperations == 0) manualIdle.complete(null);
|
||||
publish();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@Override public synchronized AutomationSnapshot snapshot() {
|
||||
return new AutomationSnapshot(root, state, handoffPending, closed, manualOperations, task,
|
||||
active == null ? null : active.snapshot(), capture, stale, diagnostics, List.copyOf(calls));
|
||||
}
|
||||
|
||||
@Override public OperationSubscription subscribe(Consumer<AutomationSnapshot> listener) {
|
||||
listeners.add(listener); notifyListener(listener, snapshot());
|
||||
return () -> listeners.remove(listener);
|
||||
}
|
||||
|
||||
@Override public OperationSubscription registerDocuments(DocumentHandoff participant) {
|
||||
documents.add(Objects.requireNonNull(participant));
|
||||
return () -> { if (documents.remove(participant)) participant.close(); };
|
||||
}
|
||||
|
||||
@Override public CompletionStage<ControlResult> grant(boolean save) {
|
||||
final long attempt;
|
||||
final List<DocumentHandoff> participants;
|
||||
synchronized (this) {
|
||||
if (closed) return result(ControlResult.Status.CLOSED, "Project closed");
|
||||
if (state != ControlState.MANUAL || handoffPending || manualOperations != 0)
|
||||
return result(ControlResult.Status.BUSY, "Manual work or another control transition is active");
|
||||
handoffPending = true; attempt = ++generation;
|
||||
participants = List.copyOf(documents); publish();
|
||||
}
|
||||
CompletableFuture<Boolean> dirty = CompletableFuture.completedFuture(false);
|
||||
for (var participant : participants)
|
||||
dirty = dirty.thenCompose(found -> participant.hasUnsavedChanges().thenApply(next -> found || next)).toCompletableFuture();
|
||||
return dirty.thenCompose(found -> {
|
||||
if (found && !save) return result(ControlResult.Status.DIRTY_DOCUMENTS, "Save all and grant, or cancel");
|
||||
CompletionStage<Void> saved = CompletableFuture.completedFuture(null);
|
||||
if (found) for (var participant : participants) saved = saved.thenCompose(v -> participant.saveAll());
|
||||
return saved.thenCompose(v -> verifySaved(participants)).thenApply(v -> {
|
||||
synchronized (this) {
|
||||
if (closed || generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
if (manualOperations != 0) return ControlResult.of(ControlResult.Status.BUSY, "Manual work is still active");
|
||||
state = ControlState.WAITING_FOR_AGENT;
|
||||
record("grant");
|
||||
return ControlResult.of(ControlResult.Status.GRANTED, "");
|
||||
}
|
||||
});
|
||||
}).exceptionally(f -> ControlResult.of(ControlResult.Status.SAVE_FAILED, message(f)))
|
||||
.thenApply(outcome -> {
|
||||
synchronized (this) {
|
||||
if (generation != attempt) return ControlResult.of(ControlResult.Status.CLOSED, "Grant invalidated");
|
||||
handoffPending = false;
|
||||
diagnostics = outcome.success() ? List.of() : List.of(outcome.diagnostic());
|
||||
publish(); return outcome;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private CompletionStage<Void> verifySaved(List<DocumentHandoff> participants) {
|
||||
CompletionStage<Void> check = CompletableFuture.completedFuture(null);
|
||||
for (var p : participants) check = check.thenCompose(v -> p.hasUnsavedChanges().thenAccept(dirty -> {
|
||||
if (dirty) throw new IllegalStateException("Document save did not finish successfully");
|
||||
}));
|
||||
return check;
|
||||
}
|
||||
|
||||
@Override public synchronized ControlResult acquire() {
|
||||
if (closed) return ControlResult.of(ControlResult.Status.CLOSED, "Project closed");
|
||||
if (state != ControlState.WAITING_FOR_AGENT) return ControlResult.of(ControlResult.Status.NOT_GRANTED, "Human grant required");
|
||||
task = new TaskIdentity(root, UUID.randomUUID().toString());
|
||||
state = ControlState.AGENT_WORKING; record("acquire"); publish();
|
||||
return new ControlResult(ControlResult.Status.ACQUIRED, task, "");
|
||||
}
|
||||
|
||||
@Override public CompletionStage<ControlResult> release(TaskIdentity identity) {
|
||||
return beginReturn(false, identity, true);
|
||||
}
|
||||
@Override public CompletionStage<ControlResult> reclaim() { return beginReturn(false, null, false); }
|
||||
@Override public CompletionStage<ControlResult> closeAsync() {
|
||||
var cleanup = beginReturn(true, null, false);
|
||||
for (var participant : List.copyOf(documents)) {
|
||||
if (documents.remove(participant)) participant.close();
|
||||
}
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
private CompletionStage<ControlResult> beginReturn(boolean closing, TaskIdentity identity, boolean requireIdentity) {
|
||||
final CompletableFuture<ControlResult> result;
|
||||
final OperationHandle<AutomationOutcome> operation;
|
||||
final ManagedHeadlessSession ownedRuntime;
|
||||
final List<Runnable> cancellations;
|
||||
final List<DocumentHandoff> participants;
|
||||
final CompletableFuture<Void> idle;
|
||||
synchronized (this) {
|
||||
if (requireIdentity && !valid(identity)) return result(ControlResult.Status.INVALID_TASK, "Task identity is not current");
|
||||
if (closing) closed = true;
|
||||
if (returning != null && !returning.isDone()) return returning;
|
||||
if (!closing && state == ControlState.MANUAL) return result(ControlResult.Status.RETURNED, "");
|
||||
state = ControlState.RETURNING_CONTROL; task = null; generation++; handoffPending = false;
|
||||
record(closing ? "close" : "reclaim"); stale = capture != null;
|
||||
result = returning = new CompletableFuture<>();
|
||||
operation = active; ownedRuntime = runtime; idle = manualIdle;
|
||||
cancellations = closing ? List.copyOf(manualCancellation) : List.of();
|
||||
participants = closing ? List.of() : List.copyOf(documents);
|
||||
publish();
|
||||
}
|
||||
// Never call another service while holding the authority monitor: Debug owns its own lock.
|
||||
CompletionStage<Void> cleanup;
|
||||
try {
|
||||
for (var cancellation : cancellations) cancellation.run();
|
||||
if (operation != null) operation.cancel();
|
||||
CompletionStage<Void> stopped = operation == null ? CompletableFuture.completedFuture(null) : operation.termination();
|
||||
CompletionStage<Void> shutdown = CompletableFuture.completedFuture(null);
|
||||
if (ownedRuntime != null) { ownedRuntime.cancel(); shutdown = ownedRuntime.shutdown(); }
|
||||
cleanup = CompletableFuture.allOf(stopped.toCompletableFuture(), shutdown.toCompletableFuture(), idle);
|
||||
// Closing disposes documents; an explicit return must refresh them before unlocking.
|
||||
for (var p : participants) cleanup = cleanup.thenCompose(v -> {
|
||||
synchronized (this) { if (closed) return CompletableFuture.completedFuture(null); }
|
||||
return p.refreshFromDisk();
|
||||
});
|
||||
} catch (RuntimeException failure) { cleanup = CompletableFuture.failedFuture(failure); }
|
||||
cleanup.whenComplete((v, failure) -> {
|
||||
synchronized (this) {
|
||||
if (failure == null) {
|
||||
runtime = null; busy = false; state = ControlState.MANUAL;
|
||||
diagnostics = List.of(); publish();
|
||||
result.complete(ControlResult.of(ControlResult.Status.RETURNED, ""));
|
||||
} else {
|
||||
diagnostics = List.of(message(failure)); publish();
|
||||
result.complete(ControlResult.of(ControlResult.Status.CLEANUP_FAILED, message(failure)));
|
||||
}
|
||||
}
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override public synchronized OperationHandle<AutomationOutcome> submit(TaskIdentity identity, String summary,
|
||||
Callable<AutomationOutcome> work) {
|
||||
requireTask(identity);
|
||||
if (busy) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
busy = true; record(summary);
|
||||
try { active = executor.submit(summary, work); }
|
||||
catch (RuntimeException failure) { busy = false; throw failure; }
|
||||
var operation = active;
|
||||
var subscription = operation.subscribe(s -> { synchronized (this) { if (active == operation) publish(); } });
|
||||
operation.completion().whenComplete((outcome, failure) -> {
|
||||
synchronized (this) {
|
||||
if (!valid(identity) || active != operation) return;
|
||||
diagnostics = failure != null ? List.of(message(failure)) : outcome.diagnostics();
|
||||
if (outcome != null && outcome.capture() != null && runtime != null
|
||||
&& runtime.sessionId().equals(outcome.capture().sessionId())) {
|
||||
capture = outcome.capture(); stale = false;
|
||||
}
|
||||
publish();
|
||||
}
|
||||
});
|
||||
operation.termination().whenComplete((v, f) -> {
|
||||
subscription.unsubscribe();
|
||||
synchronized (this) { if (active == operation) { busy = false; publish(); } }
|
||||
});
|
||||
publish(); return operation;
|
||||
}
|
||||
|
||||
@Override public synchronized void attachRuntime(TaskIdentity identity, ManagedHeadlessSession next) {
|
||||
requireTask(identity);
|
||||
if (runtime != null) throw new ControlDeniedException(ControlResult.Status.BUSY);
|
||||
runtime = Objects.requireNonNull(next); stale = capture != null; record("runtime " + next.sessionId()); publish();
|
||||
}
|
||||
@Override public synchronized void markCaptureStale() { stale = capture != null; publish(); }
|
||||
private boolean valid(TaskIdentity identity) { return !closed && state == ControlState.AGENT_WORKING && task != null && task.equals(identity); }
|
||||
private void requireTask(TaskIdentity identity) { if (!valid(identity)) throw new ControlDeniedException(ControlResult.Status.INVALID_TASK); }
|
||||
private void record(String call) { calls.addLast(Objects.requireNonNullElse(call, "")); while (calls.size() > 50) calls.removeFirst(); }
|
||||
private void publish() { var value = snapshot(); listeners.forEach(l -> notifyListener(l, value)); }
|
||||
private static void notifyListener(Consumer<AutomationSnapshot> listener, AutomationSnapshot value) {
|
||||
try { listener.accept(value); } catch (RuntimeException ignored) { /* Observation cannot change authority. */ }
|
||||
}
|
||||
private static CompletionStage<ControlResult> result(ControlResult.Status status, String text) {
|
||||
return CompletableFuture.completedFuture(ControlResult.of(status, text));
|
||||
}
|
||||
private static String message(Throwable failure) {
|
||||
while (failure instanceof CompletionException && failure.getCause() != null) failure = failure.getCause();
|
||||
return Objects.requireNonNullElse(failure.getMessage(), failure.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
+11
-2
@@ -17,30 +17,39 @@ public final class DefaultProjectSession implements ProjectSession {
|
||||
private final LspLifecyclePort lsp;
|
||||
private ProjectLocalStudioState state;
|
||||
private boolean closed;
|
||||
private final DefaultAutomationSession automation;
|
||||
private final p.studio.api.operation.OperationSubscription accessRegistration;
|
||||
|
||||
DefaultProjectSession(ProjectReference project, ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetup setup, ExecutionSession execution, LspLifecyclePort lsp,
|
||||
ProjectLocalStudioState state) {
|
||||
ProjectLocalStudioState state, DefaultAutomationSession automation,
|
||||
p.studio.api.operation.OperationSubscription accessRegistration) {
|
||||
this.project = Objects.requireNonNull(project, "project");
|
||||
this.stateStore = Objects.requireNonNull(stateStore, "stateStore");
|
||||
this.setup = Objects.requireNonNull(setup, "setup");
|
||||
this.execution = Objects.requireNonNull(execution, "execution");
|
||||
this.lsp = Objects.requireNonNull(lsp, "lsp");
|
||||
this.state = Objects.requireNonNull(state, "state");
|
||||
this.automation = Objects.requireNonNull(automation);
|
||||
this.accessRegistration = Objects.requireNonNull(accessRegistration);
|
||||
}
|
||||
|
||||
@Override public ProjectReference projectReference() { return project; }
|
||||
@Override public ProjectLocalStudioState projectLocalStudioState() { return state; }
|
||||
@Override public ProjectLocalStudioSetup projectLocalStudioSetup() { return setup; }
|
||||
@Override public ExecutionSession executionSession() { return execution; }
|
||||
@Override public p.studio.api.automation.AutomationSession automation() { return automation; }
|
||||
@Override public void replaceProjectLocalStudioState(ProjectLocalStudioState next) { state = Objects.requireNonNull(next, "state"); }
|
||||
@Override public void saveProjectLocalStudioState() { stateStore.save(project, state); }
|
||||
|
||||
@Override
|
||||
public synchronized void close() {
|
||||
if (closed) return;
|
||||
var cleanup = automation.closeAsync().toCompletableFuture().join();
|
||||
if (!cleanup.success()) throw new IllegalStateException(cleanup.diagnostic());
|
||||
closed = true;
|
||||
RuntimeException failure = attempt(this::saveProjectLocalStudioState, null);
|
||||
RuntimeException failure = attempt(accessRegistration::unsubscribe, null);
|
||||
failure = attempt(this::saveProjectLocalStudioState, failure);
|
||||
failure = attempt(execution::close, failure);
|
||||
failure = attempt(() -> lsp.shutdown(project), failure);
|
||||
if (failure != null) throw failure;
|
||||
|
||||
+11
-3
@@ -13,12 +13,17 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
private final ProjectLocalStudioStateStore stateStore;
|
||||
private final ProjectLocalStudioSetupStore setupStore;
|
||||
private final LspLifecyclePort lsp;
|
||||
private final p.studio.core.project.ProjectAccessRegistry access;
|
||||
private final p.studio.api.operation.OperationExecutor operations;
|
||||
|
||||
public DefaultProjectSessionFactory(ProjectLocalStudioStateStore stateStore,
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp) {
|
||||
ProjectLocalStudioSetupStore setupStore, LspLifecyclePort lsp,
|
||||
p.studio.core.project.ProjectAccessRegistry access, p.studio.api.operation.OperationExecutor operations) {
|
||||
this.stateStore = Objects.requireNonNull(stateStore, "stateStore");
|
||||
this.setupStore = Objects.requireNonNull(setupStore, "setupStore");
|
||||
this.lsp = Objects.requireNonNull(lsp, "lsp");
|
||||
this.access = Objects.requireNonNull(access);
|
||||
this.operations = Objects.requireNonNull(operations);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -26,7 +31,10 @@ public final class DefaultProjectSessionFactory implements ProjectSessionFactory
|
||||
final ProjectReference project = Objects.requireNonNull(projectReference, "projectReference");
|
||||
final var setup = setupStore.load(project);
|
||||
final var state = stateStore.load(project);
|
||||
lsp.boot(project);
|
||||
return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state);
|
||||
var automation = new DefaultAutomationSession(project.rootPath(), operations);
|
||||
var registration = access.register(project.rootPath(), automation::enterManual);
|
||||
try { lsp.boot(project); }
|
||||
catch (RuntimeException failure) { registration.unsubscribe(); throw failure; }
|
||||
return new DefaultProjectSession(project, stateStore, setup, new DefaultExecutionSession(), lsp, state, automation, registration);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,6 +28,12 @@ import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class StudioShipperService implements Shipper {
|
||||
private p.studio.api.automation.ProjectAccess access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
public StudioShipperService(CompilerBuildGateway compiler, PackerWorkspaceService packer, ObjectMapper mapper, OperationExecutor operations, p.studio.api.automation.ProjectAccess access) {
|
||||
this(compiler, packer, mapper, operations);
|
||||
this.access = java.util.Objects.requireNonNull(access);
|
||||
}
|
||||
|
||||
private final CompilerBuildGateway compiler;
|
||||
private final PackerWorkspaceService packer;
|
||||
private final ObjectMapper mapper;
|
||||
@@ -45,7 +51,7 @@ public final class StudioShipperService implements Shipper {
|
||||
public OperationHandle<ShipperPrepareResult> prepare(ProjectReference project, Consumer<ShipperLogEntry> sink) {
|
||||
Objects.requireNonNull(project, "project");
|
||||
Objects.requireNonNull(sink, "sink");
|
||||
return operations.submit("Build and pack " + project.name(), () -> prepareNow(project, sink));
|
||||
return access.submitManual(project.rootPath(), operations, "Build and pack " + project.name(), () -> prepareNow(project, sink));
|
||||
}
|
||||
|
||||
private ShipperPrepareResult prepareNow(ProjectReference project, Consumer<ShipperLogEntry> sink) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
package p.studio.core.assets;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.packer.PackerWorkspaceService;
|
||||
import p.studio.api.assets.*;
|
||||
import p.studio.api.assets.metadata.AssetStudioGlyphSpecialization;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.api.project.*;
|
||||
import p.studio.core.assets.metadata.AssetStudioMetadataService;
|
||||
import p.studio.core.project.ProjectAccessRegistry;
|
||||
import p.studio.core.session.DefaultAutomationSession;
|
||||
import p.studio.core.support.ControlledOperations;
|
||||
import java.nio.file.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class AssetAuthorityTest {
|
||||
@TempDir Path root;
|
||||
@Test void actualMutatorsRejectDirectCallsButInspectionRemainsAvailable() {
|
||||
var access = new ProjectAccessRegistry();
|
||||
var automation = new DefaultAutomationSession(root, new ControlledOperations());
|
||||
access.register(root, automation::enterManual);
|
||||
var project = new ProjectReference("Test", "1", "pbs", 1, ProjectTarget.Game, root);
|
||||
var packer = (PackerWorkspaceService) java.lang.reflect.Proxy.newProxyInstance(
|
||||
getClass().getClassLoader(), new Class[]{PackerWorkspaceService.class},
|
||||
(proxy, method, args) -> { throw new AssertionError("Rejected call reached packer: " + method); });
|
||||
var commands = new PackerAssetCommands(packer, access);
|
||||
var packing = new PackerAssetPacking(packer, new ControlledOperations(), access);
|
||||
var shipper = new p.studio.core.shipper.StudioShipperService((p, log) -> { throw new AssertionError("must not compile"); },
|
||||
packer, new ObjectMapper(), new ControlledOperations(), access);
|
||||
var storage = new FileSystemAssetWorkspaceStorage(access);
|
||||
var metadata = new AssetStudioMetadataService(new ObjectMapper(), access);
|
||||
automation.grant(false).toCompletableFuture().join();
|
||||
for (int state = 0; state < 2; state++) {
|
||||
assertThrows(ControlDeniedException.class, () -> commands.delete(project, AssetReference.of("test")));
|
||||
assertThrows(ControlDeniedException.class, () -> commands.register(project, AssetReference.of("test")));
|
||||
assertThrows(ControlDeniedException.class, () -> storage.prepare(project));
|
||||
assertThrows(ControlDeniedException.class, () -> packing.pack(project));
|
||||
assertThrows(ControlDeniedException.class, () -> packing.deepSync(project));
|
||||
assertThrows(ControlDeniedException.class, () -> shipper.prepare(project, log -> {}));
|
||||
assertThrows(ControlDeniedException.class, () -> metadata.writeGlyphSpecialization(root, AssetStudioGlyphSpecialization.NONE));
|
||||
assertFalse(storage.assetManifestExists(project, "missing"));
|
||||
assertNotNull(metadata.read(root, AssetFamily.GLYPH_BANK));
|
||||
automation.acquire();
|
||||
}
|
||||
assertFalse(Files.exists(root.resolve("assets")));
|
||||
automation.reclaim().toCompletableFuture().join();
|
||||
assertTrue(storage.prepare(project).success());
|
||||
}
|
||||
}
|
||||
+32
@@ -39,6 +39,38 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
final class PlayStopExecutionControllerTest {
|
||||
private static final OperationExecutor OPERATIONS = new ImmediateOperationExecutor();
|
||||
|
||||
@Test
|
||||
void debugAndAutomationAreMutuallyExclusiveAndLateExitCannotUnlockNewDebug() {
|
||||
var authority = new p.studio.core.session.DefaultAutomationSession(project().rootPath(), OPERATIONS);
|
||||
var access = new p.studio.core.project.ProjectAccessRegistry();
|
||||
access.register(project().rootPath(), authority::enterManual);
|
||||
var session = new DefaultExecutionSession();
|
||||
var exits = new java.util.ArrayList<CompletableFuture<Integer>>();
|
||||
RuntimeGateway runtime = (project, setup, logs) -> {
|
||||
var exit = new CompletableFuture<Integer>(); exits.add(exit);
|
||||
return new RuntimeConnection() {
|
||||
public CompletableFuture<Integer> completion() { return exit; }
|
||||
public void close() { } // Exit notification can arrive after close returned.
|
||||
};
|
||||
};
|
||||
var controller = new PlayStopExecutionController(project(), ProjectLocalStudioSetup.defaults(),
|
||||
session, successfulShipper(), runtime, OPERATIONS, access);
|
||||
controller.play();
|
||||
assertEquals(p.studio.api.automation.ControlResult.Status.BUSY, authority.grant(false).toCompletableFuture().join().status());
|
||||
controller.stop(); controller.play(); exits.getFirst().complete(0);
|
||||
assertEquals(ExecutionState.RUNNING, session.snapshot().state());
|
||||
assertEquals(1, authority.snapshot().manualOperations());
|
||||
controller.stop();
|
||||
assertEquals(p.studio.api.automation.ControlResult.Status.GRANTED, authority.grant(false).toCompletableFuture().join().status());
|
||||
org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play);
|
||||
authority.acquire();
|
||||
org.junit.jupiter.api.Assertions.assertThrows(p.studio.api.automation.ControlDeniedException.class, controller::play);
|
||||
authority.reclaim().toCompletableFuture().join();
|
||||
controller.play();
|
||||
authority.closeAsync().toCompletableFuture().join();
|
||||
assertEquals(ExecutionState.STOPPED, session.snapshot().state());
|
||||
}
|
||||
|
||||
@Test
|
||||
void successfulPreparationStartsRuntimeAndProjectsExit() {
|
||||
final var session = new DefaultExecutionSession();
|
||||
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package p.studio.core.session;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import p.studio.api.automation.*;
|
||||
import p.studio.core.project.ProjectAccessRegistry;
|
||||
import p.studio.core.support.ControlledOperations;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static p.studio.api.automation.ControlResult.Status.*;
|
||||
|
||||
class DefaultAutomationSessionTest {
|
||||
@TempDir Path root;
|
||||
final ControlledOperations operations = new ControlledOperations();
|
||||
DefaultAutomationSession session() { return new DefaultAutomationSession(root, operations); }
|
||||
ControlResult await(CompletionStage<ControlResult> result) { return result.toCompletableFuture().join(); }
|
||||
TaskIdentity start(DefaultAutomationSession s) { assertEquals(GRANTED, await(s.grant(false)).status()); return s.acquire().task(); }
|
||||
|
||||
@Test void explicitGrantAndProjectScopedIdentityAreRequired() {
|
||||
var s = session();
|
||||
assertEquals(NOT_GRANTED, s.acquire().status());
|
||||
var task = start(s);
|
||||
assertEquals(NOT_GRANTED, s.acquire().status());
|
||||
assertEquals(INVALID_TASK, await(s.release(new TaskIdentity(root.resolve("other"), task.value()))).status());
|
||||
assertThrows(ControlDeniedException.class, s::enterManual);
|
||||
assertEquals(RETURNED, await(s.release(task)).status());
|
||||
var next = start(s);
|
||||
assertNotEquals(task, next);
|
||||
assertEquals(INVALID_TASK, await(s.release(task)).status());
|
||||
assertEquals(ControlState.AGENT_WORKING, s.snapshot().state());
|
||||
}
|
||||
|
||||
@Test void racingClientsCannotBothAcquireAndWaitingGrantCanBeReclaimed() throws Exception {
|
||||
var s = session(); s.grant(false).toCompletableFuture().join();
|
||||
assertEquals(RETURNED, await(s.reclaim()).status()); assertEquals(NOT_GRANTED, s.acquire().status());
|
||||
s.grant(false).toCompletableFuture().join();
|
||||
var pool = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
var a = pool.submit(s::acquire); var b = pool.submit(s::acquire);
|
||||
assertEquals(1, java.util.stream.Stream.of(a.get(), b.get()).filter(r -> r.status() == ACQUIRED).count());
|
||||
} finally { pool.shutdownNow(); }
|
||||
}
|
||||
|
||||
@Test void captureFromWrongRuntimeIsNotPublished() {
|
||||
var s = session(); var task = start(s); s.attachRuntime(task, new Runtime());
|
||||
s.submit(task, "wrong frame", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 0, 0, List.of(),
|
||||
new CanonicalCapture("other-session", "build", 0, 0, 1, 1, 1, new byte[]{1})));
|
||||
operations.last.finish(); assertNull(s.snapshot().capture());
|
||||
}
|
||||
|
||||
@Test void closureDisposesPendingRefreshWithoutWaitingForPresentationThread() {
|
||||
var s = session(); var docs = new Documents() {
|
||||
@Override public void close() { refresh.complete(null); }
|
||||
};
|
||||
docs.refresh = new CompletableFuture<>();
|
||||
var registration = s.registerDocuments(docs); start(s);
|
||||
var returned = s.reclaim().toCompletableFuture(); assertFalse(returned.isDone());
|
||||
assertEquals(RETURNED, await(s.closeAsync()).status());
|
||||
registration.unsubscribe();
|
||||
assertEquals(RETURNED, returned.join().status()); assertFalse(s.snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void manualAndAgentAcquisitionRaceHasOnlyOneWinner() throws Exception {
|
||||
for (int n = 0; n < 100; n++) {
|
||||
var s = session();
|
||||
var gate = new CountDownLatch(1);
|
||||
var workers = Executors.newFixedThreadPool(2);
|
||||
try {
|
||||
var manual = workers.submit(() -> { gate.await(); try { return s.enterManual(); } catch (ControlDeniedException denied) { return null; } });
|
||||
var grant = workers.submit(() -> { gate.await(); return await(s.grant(false)); });
|
||||
gate.countDown();
|
||||
var lease = manual.get(2, TimeUnit.SECONDS);
|
||||
var granted = grant.get(2, TimeUnit.SECONDS).status() == GRANTED;
|
||||
assertNotEquals(lease != null, granted);
|
||||
if (lease != null) lease.close();
|
||||
} finally { workers.shutdownNow(); }
|
||||
}
|
||||
}
|
||||
|
||||
@Test void dirtyDocumentsRequireSuccessfulSaveAndRefreshBeforeManualReturn() {
|
||||
var s = session(); var docs = new Documents(); docs.dirty = true;
|
||||
s.registerDocuments(docs);
|
||||
assertEquals(DIRTY_DOCUMENTS, await(s.grant(false)).status());
|
||||
assertTrue(s.snapshot().manualAllowed()); assertEquals(0, docs.saves);
|
||||
docs.failSave = true;
|
||||
assertEquals(SAVE_FAILED, await(s.grant(true)).status());
|
||||
assertTrue(docs.dirty); assertTrue(s.snapshot().manualAllowed());
|
||||
docs.failSave = false;
|
||||
assertEquals(GRANTED, await(s.grant(true)).status());
|
||||
assertFalse(docs.dirty);
|
||||
docs.refresh = new CompletableFuture<>();
|
||||
var returned = s.reclaim().toCompletableFuture();
|
||||
assertEquals(ControlState.RETURNING_CONTROL, s.snapshot().state());
|
||||
assertFalse(returned.isDone()); assertFalse(s.snapshot().manualAllowed());
|
||||
docs.refresh.complete(null);
|
||||
assertEquals(RETURNED, returned.join().status()); assertTrue(s.snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void revocationInvalidatesFirstAndWaitsForWorkerAndRuntimeBeforeRefresh() {
|
||||
var s = session(); var docs = new Documents(); s.registerDocuments(docs);
|
||||
var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime);
|
||||
var capture = new CanonicalCapture("session", "build", 20, 7, 2, 2, 2, new byte[]{1});
|
||||
s.submit(task, "advance", () -> new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED, 20, 20, List.of(), capture));
|
||||
assertThrows(ControlDeniedException.class, () -> s.submit(task, "overlap", () -> null));
|
||||
var returned = s.reclaim().toCompletableFuture();
|
||||
assertNull(s.snapshot().task()); assertTrue(operations.last.cancelled); assertTrue(runtime.cancelled);
|
||||
assertThrows(ControlDeniedException.class, () -> s.submit(task, "late", () -> null));
|
||||
assertEquals(0, docs.refreshes);
|
||||
operations.last.finish(); // A late successful completion must not publish a frame.
|
||||
assertNull(s.snapshot().capture()); assertFalse(returned.isDone());
|
||||
runtime.stopped.complete(null);
|
||||
assertEquals(RETURNED, returned.join().status()); assertEquals(1, docs.refreshes);
|
||||
}
|
||||
|
||||
@Test void guestFaultAndCancellationDoNotRevokeAuthorityAndCaptureIsImmutable() {
|
||||
var s = session(); var task = start(s); var runtime = new Runtime(); s.attachRuntime(task, runtime);
|
||||
byte[] bytes = {1, 2}; var frame = new CanonicalCapture("session", "build", 9, 4, 2, 2, 2, bytes);
|
||||
bytes[0] = 8; frame.png()[0] = 9;
|
||||
assertEquals(1, frame.png()[0]);
|
||||
s.submit(task, "fault", () -> new AutomationOutcome(AutomationOutcome.Kind.GUEST_FAULT, 10, 9, List.of("fault"), frame));
|
||||
operations.last.finish();
|
||||
assertEquals(ControlState.AGENT_WORKING, s.snapshot().state()); assertEquals(frame, s.snapshot().capture());
|
||||
assertEquals(List.of("fault"), s.snapshot().diagnostics());
|
||||
s.markCaptureStale(); assertTrue(s.snapshot().stale());
|
||||
s.submit(task, "cancel", () -> new AutomationOutcome(AutomationOutcome.Kind.CANCELLED, 10, 0, List.of(), null)).cancel();
|
||||
operations.last.finish(); assertEquals(task, s.snapshot().task());
|
||||
}
|
||||
|
||||
@Test void failedCleanupKeepsGuardAndHumanCanRetry() {
|
||||
var s = session(); var docs = new Documents(); s.registerDocuments(docs); start(s);
|
||||
docs.refresh = CompletableFuture.failedFuture(new IllegalStateException("disk unavailable"));
|
||||
assertEquals(CLEANUP_FAILED, await(s.reclaim()).status());
|
||||
assertThrows(ControlDeniedException.class, s::enterManual);
|
||||
docs.refresh = CompletableFuture.completedFuture(null);
|
||||
assertEquals(RETURNED, await(s.reclaim()).status()); assertTrue(s.snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void registryIsPerProjectAndClosedAuthorityCannotBeReused() {
|
||||
var registry = new ProjectAccessRegistry(); var s = session();
|
||||
var registration = registry.register(root, s::enterManual); start(s);
|
||||
assertThrows(ControlDeniedException.class, () -> registry.enterManual(root.resolve("assets/new")));
|
||||
try (var unrelated = registry.enterManual(root.resolveSibling("unrelated"))) { assertNotNull(unrelated); }
|
||||
await(s.closeAsync()); assertEquals(CLOSED, s.acquire().status());
|
||||
assertThrows(ControlDeniedException.class, () -> registry.enterManual(root));
|
||||
registration.unsubscribe(); var reopened = session(); registry.register(root, reopened::enterManual);
|
||||
try (var manual = registry.enterManual(root)) { assertEquals(1, reopened.snapshot().manualOperations()); }
|
||||
}
|
||||
|
||||
@Test void closeCancelsManualWorkWithoutCallingItUnderAuthorityLock() throws Exception {
|
||||
var s = session(); var lease = s.enterManual();
|
||||
lease.onProjectClose(() -> {
|
||||
var worker = CompletableFuture.runAsync(() -> { s.snapshot(); lease.close(); });
|
||||
assertDoesNotThrow(() -> worker.get(2, TimeUnit.SECONDS));
|
||||
});
|
||||
assertEquals(RETURNED, await(s.closeAsync()).status()); assertTrue(s.snapshot().closed());
|
||||
assertFalse(s.snapshot().manualAllowed());
|
||||
}
|
||||
|
||||
@Test void closeDuringSaveCannotGrantAfterProjectHasClosed() {
|
||||
var s = session(); var docs = new Documents(); docs.dirty = true; docs.save = new CompletableFuture<>();
|
||||
s.registerDocuments(docs); var grant = s.grant(true);
|
||||
assertTrue(s.snapshot().handoffPending()); await(s.closeAsync()); docs.save.complete(null);
|
||||
assertEquals(CLOSED, await(grant).status()); assertTrue(s.snapshot().closed());
|
||||
}
|
||||
|
||||
static class Documents implements DocumentHandoff {
|
||||
boolean dirty, failSave; int saves, refreshes;
|
||||
CompletableFuture<Void> save = CompletableFuture.completedFuture(null), refresh = CompletableFuture.completedFuture(null);
|
||||
public CompletionStage<Boolean> hasUnsavedChanges() { return CompletableFuture.completedFuture(dirty); }
|
||||
public CompletionStage<Void> saveAll() {
|
||||
saves++;
|
||||
if (failSave) return CompletableFuture.failedFuture(new IllegalStateException("save failed"));
|
||||
return save.thenRun(() -> dirty = false);
|
||||
}
|
||||
public CompletionStage<Void> refreshFromDisk() { refreshes++; return refresh; }
|
||||
}
|
||||
static class Runtime implements ManagedHeadlessSession {
|
||||
final CompletableFuture<Void> stopped = new CompletableFuture<>(); boolean cancelled;
|
||||
public String sessionId() { return "session"; }
|
||||
public void cancel() { cancelled = true; }
|
||||
public CompletionStage<Void> shutdown() { return stopped; }
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -22,7 +22,8 @@ final class DefaultProjectSessionTest {
|
||||
final var stateStore = new ProjectLocalStudioStateStore(mapper);
|
||||
final var setupStore = new ProjectLocalStudioSetupStore(mapper);
|
||||
final var lsp = new RecordingLsp();
|
||||
final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp);
|
||||
final var factory = new DefaultProjectSessionFactory(stateStore, setupStore, lsp,
|
||||
new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations());
|
||||
final var project = project();
|
||||
|
||||
final var session = factory.open(project);
|
||||
@@ -44,7 +45,8 @@ final class DefaultProjectSessionTest {
|
||||
lsp.failShutdown = true;
|
||||
final var session = new DefaultProjectSessionFactory(
|
||||
new ProjectLocalStudioStateStore(mapper),
|
||||
new ProjectLocalStudioSetupStore(mapper), lsp).open(project());
|
||||
new ProjectLocalStudioSetupStore(mapper), lsp,
|
||||
new p.studio.core.project.ProjectAccessRegistry(), new p.studio.core.support.ControlledOperations()).open(project());
|
||||
final var failure = assertThrows(IllegalStateException.class, session::close);
|
||||
assertEquals("lsp shutdown", failure.getMessage());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package p.studio.core.support;
|
||||
|
||||
import p.studio.api.operation.*;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
/** Cancellation acknowledgement and worker termination are deliberately independent. */
|
||||
public final class ControlledOperations implements OperationExecutor {
|
||||
public Handle<?> last;
|
||||
@Override public <R> OperationHandle<R> submit(String summary, Callable<R> work) {
|
||||
Handle<R> handle = new Handle<>(summary, work);
|
||||
last = handle;
|
||||
return handle;
|
||||
}
|
||||
public static final class Handle<R> implements OperationHandle<R> {
|
||||
public final CompletableFuture<R> completed = new CompletableFuture<>();
|
||||
public final CompletableFuture<Void> stopped = new CompletableFuture<>();
|
||||
public boolean cancelled;
|
||||
private final Callable<R> work;
|
||||
private final String summary;
|
||||
private final OperationId id = new OperationId(java.util.UUID.randomUUID().toString());
|
||||
Handle(String summary, Callable<R> work) { this.summary = summary; this.work = work; }
|
||||
public void finish() {
|
||||
try { completed.complete(work.call()); } catch (Exception failure) { completed.completeExceptionally(failure); }
|
||||
stopped.complete(null);
|
||||
}
|
||||
@Override public OperationId id() { return id; }
|
||||
@Override public OperationSnapshot snapshot() {
|
||||
return new OperationSnapshot(id, cancelled ? OperationState.CANCELLED : completed.isDone() ? OperationState.SUCCEEDED : OperationState.RUNNING, Instant.now(), summary);
|
||||
}
|
||||
@Override public CompletionStage<R> completion() { return completed; }
|
||||
@Override public CompletionStage<Void> termination() { return stopped; }
|
||||
@Override public boolean cancel() { cancelled = true; return true; }
|
||||
@Override public OperationSubscription subscribe(Consumer<OperationSnapshot> observer) { observer.accept(snapshot()); return () -> {}; }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user