asset workspace progress

This commit is contained in:
2026-03-24 13:42:44 +00:00
parent 4c8190cc31
commit 59e1ad5ecf
286 changed files with 7156 additions and 8898 deletions
+2 -6
View File
@@ -1,11 +1,11 @@
plugins {
id("gradle.java-application-conventions")
id("gradle.java-library-conventions")
alias(libs.plugins.javafx)
}
dependencies {
implementation(project(":prometeu-infra"))
implementation(project(":prometeu-packer"))
implementation(project(":prometeu-packer:prometeu-packer-api"))
implementation(project(":prometeu-compiler:prometeu-compiler-core"))
implementation(project(":prometeu-compiler:prometeu-build-pipeline"))
implementation(project(":prometeu-compiler:prometeu-frontend-registry"))
@@ -18,7 +18,3 @@ javafx {
version = libs.versions.javafx.get()
modules("javafx.controls", "javafx.fxml")
}
application {
mainClass = "p.studio.App"
}
@@ -1,23 +0,0 @@
package p.studio;
import javafx.application.Application;
import javafx.stage.Stage;
import p.studio.window.StudioWindowCoordinator;
public class App extends Application {
@Override
public void init() throws Exception {
super.init();
Container.init();
}
@Override
public void start(Stage stage) {
new StudioWindowCoordinator(stage).showLauncher();
}
public static void main(String[] args) {
launch();
}
}
@@ -1,26 +1,98 @@
package p.studio;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.events.StudioEventBus;
import p.studio.utilities.ThemeService;
import p.studio.utilities.i18n.I18nService;
public class Container {
private static final I18nService i18nService;
private static final ThemeService themeService;
private static final StudioEventBus studioEventBus;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
static {
i18nService = new I18nService();
themeService = new ThemeService();
studioEventBus = new StudioEventBus();
public interface Container {
I18nService getI18n();
ThemeService getTheme();
StudioEventBus getEventBus();
ObjectMapper getMapper();
Packer getPacker();
StudioBackgroundTasks getBackgroundTasks();
void shutdownContainer();
static void install(Container container) {
final Container candidate = Objects.requireNonNull(container, "container");
final Container current = Holder.CURRENT.get();
if (current == null) {
if (Holder.CURRENT.compareAndSet(null, candidate)) {
return;
}
}
if (Holder.CURRENT.get() != candidate) {
throw new IllegalStateException("Container already installed.");
}
}
public static void init() {
static Container current() {
final Container container = Holder.CURRENT.get();
if (container == null) {
throw new IllegalStateException("Container has not been installed.");
}
return container;
}
public static I18nService i18n() { return i18nService; }
static I18nService i18n() {
return current().getI18n();
}
public static ThemeService theme() { return new ThemeService(); }
static ThemeService theme() {
return current().getTheme();
}
public static StudioEventBus events() { return studioEventBus; }
static StudioEventBus eventBus() {
return current().getEventBus();
}
static ObjectMapper mapper() {
return current().getMapper();
}
static Packer packer() {
return current().getPacker();
}
static StudioBackgroundTasks backgroundTasks() {
return current().getBackgroundTasks();
}
static void shutdown() {
final Container container = Holder.CURRENT.get();
if (container != null) {
container.shutdownContainer();
}
}
record Packer(
p.packer.PackerWorkspaceService workspaceService,
Runnable shutdownAction) {
public Packer {
Objects.requireNonNull(workspaceService, "workspaceService");
Objects.requireNonNull(shutdownAction, "shutdownAction");
}
public void shutdown() {
shutdownAction.run();
}
}
final class Holder {
private static final AtomicReference<Container> CURRENT = new AtomicReference<>();
private Holder() {
}
}
}
@@ -0,0 +1,30 @@
package p.studio;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public final class StudioBackgroundTasks {
private final ExecutorService executorService;
public StudioBackgroundTasks(ExecutorService executorService) {
this.executorService = Objects.requireNonNull(executorService, "executorService");
}
public Future<?> submit(Runnable task) {
return executorService.submit(Objects.requireNonNull(task, "task"));
}
public void shutdown() {
executorService.shutdown();
try {
if (!executorService.awaitTermination(2, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
} catch (InterruptedException interruptedException) {
executorService.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
@@ -0,0 +1,53 @@
package p.studio.controls.forms;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import p.studio.Container;
import p.studio.utilities.i18n.I18n;
public final class StudioFormActionBar extends HBox {
private final Button changeButton = createButton(I18n.FORM_ACTION_CHANGE);
private final Button applyButton = createButton(I18n.FORM_ACTION_APPLY);
private final Button resetButton = createButton(I18n.FORM_ACTION_RESET);
private final Button cancelButton = createButton(I18n.FORM_ACTION_CANCEL);
public StudioFormActionBar(
Runnable onChange,
Runnable onApply,
Runnable onReset,
Runnable onCancel) {
setSpacing(8);
getStyleClass().add("studio-form-actions");
changeButton.getStyleClass().add("studio-button-secondary");
applyButton.getStyleClass().add("studio-button-primary");
resetButton.getStyleClass().add("studio-button-secondary");
cancelButton.getStyleClass().add("studio-button-cancel");
changeButton.setOnAction(ignored -> onChange.run());
applyButton.setOnAction(ignored -> onApply.run());
resetButton.setOnAction(ignored -> onReset.run());
cancelButton.setOnAction(ignored -> onCancel.run());
getChildren().setAll(changeButton, applyButton, resetButton, cancelButton);
}
public void updateState(StudioFormMode mode, boolean dirty) {
final boolean editing = mode == StudioFormMode.EDITING;
setVisibleManaged(changeButton, !editing);
setVisibleManaged(applyButton, editing);
setVisibleManaged(resetButton, editing);
setVisibleManaged(cancelButton, editing);
applyButton.setDisable(!dirty);
resetButton.setDisable(!dirty);
}
private Button createButton(I18n label) {
final Button button = new Button();
button.textProperty().bind(Container.i18n().bind(label));
button.getStyleClass().add("studio-button");
return button;
}
private void setVisibleManaged(Button button, boolean visible) {
button.setVisible(visible);
button.setManaged(visible);
}
}
@@ -0,0 +1,6 @@
package p.studio.controls.forms;
public enum StudioFormMode {
READ_ONLY,
EDITING
}
@@ -0,0 +1,58 @@
package p.studio.controls.forms;
import java.util.Objects;
import java.util.function.UnaryOperator;
public final class StudioFormSession<T> {
private T source;
private T draft;
private StudioFormMode mode;
public StudioFormSession(T source) {
replaceSource(source);
}
public void replaceSource(T source) {
this.source = Objects.requireNonNull(source, "source");
this.draft = source;
this.mode = StudioFormMode.READ_ONLY;
}
public T source() {
return source;
}
public T draft() {
return draft;
}
public StudioFormMode mode() {
return mode;
}
public boolean isDirty() {
return !Objects.equals(source, draft);
}
public void beginEdit() {
mode = StudioFormMode.EDITING;
}
public void setDraft(T draft) {
this.draft = Objects.requireNonNull(draft, "draft");
}
public void updateDraft(UnaryOperator<T> update) {
draft = Objects.requireNonNull(update, "update").apply(draft);
draft = Objects.requireNonNull(draft, "draft");
}
public void resetDraft() {
draft = source;
}
public void cancelEdit() {
resetDraft();
mode = StudioFormMode.READ_ONLY;
}
}
@@ -1,6 +1,9 @@
package p.studio.controls.shell;
import p.studio.events.*;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshFailedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshStartedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshedEvent;
import java.util.Optional;
@@ -10,12 +13,12 @@ public final class StudioActivityEventMapper {
public static Optional<StudioActivityEntry> map(StudioEvent event) {
return switch (event) {
case StudioProjectOpenedEvent opened ->
Optional.of(new StudioActivityEntry("Studio", "Project opened: " + opened.project().name(), StudioActivityEntrySeverity.SUCCESS, false));
case StudioProjectLoadingStartedEvent started ->
Optional.of(new StudioActivityEntry("Studio", "Project loading started: " + started.project().name(), StudioActivityEntrySeverity.INFO, false));
case StudioProjectLoadingCompletedEvent completed ->
Optional.of(new StudioActivityEntry("Studio", "Project ready: " + completed.project().name(), StudioActivityEntrySeverity.SUCCESS, false));
case StudioProjectOpenedEvent ignored ->
Optional.of(new StudioActivityEntry("Studio", "Project opened", StudioActivityEntrySeverity.SUCCESS, false));
case StudioProjectLoadingStartedEvent ignored ->
Optional.of(new StudioActivityEntry("Studio", "Project loading started", StudioActivityEntrySeverity.INFO, false));
case StudioProjectLoadingCompletedEvent ignored ->
Optional.of(new StudioActivityEntry("Studio", "Project ready", StudioActivityEntrySeverity.SUCCESS, false));
case StudioProjectLoadingFailedEvent failed ->
Optional.of(new StudioActivityEntry("Studio", failed.message(), StudioActivityEntrySeverity.ERROR, true));
case StudioAssetsWorkspaceRefreshStartedEvent ignored ->
@@ -24,22 +27,15 @@ public final class StudioActivityEventMapper {
Optional.of(new StudioActivityEntry("Assets", refreshed.assetCount() + " assets loaded", StudioActivityEntrySeverity.SUCCESS, false));
case StudioAssetsWorkspaceRefreshFailedEvent failed ->
Optional.of(new StudioActivityEntry("Assets", failed.message(), StudioActivityEntrySeverity.ERROR, true));
case StudioAssetsMutationPreviewReadyEvent previewReady ->
Optional.of(new StudioActivityEntry("Assets", "Preview ready: " + previewReady.action().name().toLowerCase(), StudioActivityEntrySeverity.INFO, false));
case StudioAssetsMutationAppliedEvent applied ->
Optional.of(new StudioActivityEntry("Assets", "Action applied: " + applied.action().name().toLowerCase(), StudioActivityEntrySeverity.SUCCESS, false));
case StudioAssetsMutationFailedEvent failed ->
Optional.of(new StudioActivityEntry("Assets", failed.message(), StudioActivityEntrySeverity.ERROR, true));
case StudioPackerOperationEvent packerEvent ->
Optional.of(new StudioActivityEntry("Assets", packerEvent.summary(), severity(packerEvent), packerEvent.kind() == p.packer.api.events.PackerEventKind.ACTION_FAILED));
Optional.of(new StudioActivityEntry("Assets", packerEvent.summary(), severity(packerEvent), packerEvent.kind() == p.packer.events.PackerEventKind.ACTION_FAILED));
default -> Optional.empty();
};
}
private static StudioActivityEntrySeverity severity(StudioPackerOperationEvent event) {
return switch (event.kind()) {
case BUILD_FINISHED, CACHE_HIT -> StudioActivityEntrySeverity.SUCCESS;
case DIAGNOSTICS_UPDATED, CACHE_MISS, BUILD_STARTED, ASSET_DISCOVERED, ASSET_CHANGED, PROGRESS_UPDATED -> StudioActivityEntrySeverity.INFO;
case ACTION_APPLIED -> StudioActivityEntrySeverity.SUCCESS;
case ACTION_FAILED -> StudioActivityEntrySeverity.ERROR;
default -> StudioActivityEntrySeverity.INFO;
};
@@ -14,21 +14,34 @@ import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.*;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshFailedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshStartedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshedEvent;
import p.studio.utilities.events.EventSubscription;
import p.studio.utilities.i18n.I18n;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class StudioActivityFeedControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioActivityStorageService storageService;
private final ObservableList<StudioActivityEntry> entries = FXCollections.observableArrayList();
private final List<EventSubscription> subscriptions = new ArrayList<>();
private final Label progressLabel = new Label();
private final ProgressBar progressBar = new ProgressBar();
private final ListView<StudioActivityEntry> listView = new ListView<>(entries);
public StudioActivityFeedControl() {
public StudioActivityFeedControl(ProjectReference projectReference) {
this(projectReference, new StudioActivityStorageService());
}
StudioActivityFeedControl(ProjectReference projectReference, StudioActivityStorageService storageService) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.storageService = Objects.requireNonNull(storageService, "storageService");
getStyleClass().add("studio-activity-feed");
setSpacing(10);
setPadding(new Insets(12));
@@ -42,12 +55,16 @@ public final class StudioActivityFeedControl extends VBox implements StudioContr
listView.getStyleClass().add("studio-activity-list");
listView.setCellFactory(ignored -> new ActivityCell());
entries.setAll(this.storageService.load(projectReference));
getChildren().addAll(progressLabel, progressBar, listView);
}
@Override
public void subscribe() {
final StudioEventBus eventBus = Container.events();
if (!subscriptions.isEmpty()) {
return;
}
final StudioEventBus eventBus = Container.eventBus();
subscriptions.add(eventBus.subscribe(StudioProjectOpenedEvent.class, this::onEvent));
subscriptions.add(eventBus.subscribe(StudioProjectLoadingStartedEvent.class, this::onEvent));
subscriptions.add(eventBus.subscribe(StudioProjectLoadingProgressEvent.class, this::onProjectLoadingProgress));
@@ -56,9 +73,6 @@ public final class StudioActivityFeedControl extends VBox implements StudioContr
subscriptions.add(eventBus.subscribe(StudioAssetsWorkspaceRefreshStartedEvent.class, this::onAssetsRefreshStarted));
subscriptions.add(eventBus.subscribe(StudioAssetsWorkspaceRefreshedEvent.class, this::onAssetsRefreshFinished));
subscriptions.add(eventBus.subscribe(StudioAssetsWorkspaceRefreshFailedEvent.class, this::onAssetsRefreshFailed));
subscriptions.add(eventBus.subscribe(StudioAssetsMutationPreviewReadyEvent.class, this::onEvent));
subscriptions.add(eventBus.subscribe(StudioAssetsMutationAppliedEvent.class, this::onEvent));
subscriptions.add(eventBus.subscribe(StudioAssetsMutationFailedEvent.class, this::onEvent));
subscriptions.add(eventBus.subscribe(StudioPackerOperationEvent.class, this::onPackerOperation));
}
@@ -124,10 +138,9 @@ public final class StudioActivityFeedControl extends VBox implements StudioContr
progressBar.setManaged(true);
progressBar.setProgress(event.indeterminate() ? ProgressBar.INDETERMINATE_PROGRESS : event.progress());
});
if (event.kind() == p.packer.api.events.PackerEventKind.BUILD_FINISHED) {
clearProgress();
}
} else if (event.kind() == p.packer.api.events.PackerEventKind.BUILD_FINISHED) {
}
if (event.kind() == p.packer.events.PackerEventKind.ACTION_APPLIED
|| event.kind() == p.packer.events.PackerEventKind.ACTION_FAILED) {
clearProgress();
}
}
@@ -143,17 +156,18 @@ public final class StudioActivityFeedControl extends VBox implements StudioContr
private void appendEntry(StudioActivityEntry entry) {
Platform.runLater(() -> {
if (!entries.isEmpty()) {
final StudioActivityEntry last = entries.getLast();
if (last.source().equals(entry.source())
&& last.message().equals(entry.message())
&& last.severity() == entry.severity()) {
final StudioActivityEntry latest = entries.getFirst();
if (latest.source().equals(entry.source())
&& latest.message().equals(entry.message())
&& latest.severity() == entry.severity()) {
return;
}
}
entries.addFirst(entry);
while (entries.size() > 100) {
while (entries.size() > StudioActivityStorageService.MAX_HISTORY) {
entries.removeLast();
}
storageService.save(projectReference, List.copyOf(entries));
});
}
@@ -0,0 +1,106 @@
package p.studio.controls.shell;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.projects.ProjectReference;
import p.studio.projects.ProjectStudioPaths;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public final class StudioActivityStorageService {
public static final int MAX_HISTORY = 500;
private static final ObjectMapper MAPPER = new ObjectMapper();
public List<StudioActivityEntry> load(ProjectReference projectReference) {
final Path activitiesPath = ProjectStudioPaths.activitiesPath(projectReference);
if (!Files.isRegularFile(activitiesPath)) {
return List.of();
}
try {
final PersistedActivityEntry[] persistedEntries = MAPPER.readValue(
activitiesPath.toFile(),
PersistedActivityEntry[].class);
final List<StudioActivityEntry> entries = new ArrayList<>();
for (PersistedActivityEntry persistedEntry : persistedEntries) {
final StudioActivityEntry mapped = map(persistedEntry);
if (mapped != null) {
entries.add(mapped);
}
}
return bounded(entries);
} catch (IOException | RuntimeException ignored) {
return List.of();
}
}
public void save(ProjectReference projectReference, List<StudioActivityEntry> entries) {
final Path activitiesPath = ProjectStudioPaths.activitiesPath(projectReference);
final List<StudioActivityEntry> boundedEntries = bounded(entries);
final List<PersistedActivityEntry> persistedEntries = boundedEntries.stream()
.map(entry -> new PersistedActivityEntry(
entry.source(),
entry.message(),
entry.severity().name(),
entry.sticky()))
.toList();
try {
Files.createDirectories(activitiesPath.getParent());
MAPPER.writerWithDefaultPrettyPrinter().writeValue(activitiesPath.toFile(), persistedEntries);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
public List<StudioActivityEntry> bounded(List<StudioActivityEntry> entries) {
final List<StudioActivityEntry> normalized = List.copyOf(Objects.requireNonNull(entries, "entries"));
if (normalized.size() <= MAX_HISTORY) {
return normalized;
}
return List.copyOf(normalized.subList(0, MAX_HISTORY));
}
private StudioActivityEntry map(PersistedActivityEntry persistedEntry) {
if (persistedEntry == null
|| persistedEntry.source == null
|| persistedEntry.message == null
|| persistedEntry.severity == null) {
return null;
}
try {
return new StudioActivityEntry(
persistedEntry.source,
persistedEntry.message,
StudioActivityEntrySeverity.valueOf(persistedEntry.severity.trim()),
persistedEntry.sticky);
} catch (RuntimeException ignored) {
return null;
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static final class PersistedActivityEntry {
public String source;
public String message;
public String severity;
public boolean sticky;
public PersistedActivityEntry() {
}
private PersistedActivityEntry(String source, String message, String severity, boolean sticky) {
this.source = source;
this.message = message;
this.severity = severity;
this.sticky = sticky;
}
}
}
@@ -1,15 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceAssetSummary;
import java.util.Objects;
public record StudioAssetsAssetSummaryPatchedEvent(
ProjectReference project,
AssetWorkspaceAssetSummary summary) implements StudioEvent {
public StudioAssetsAssetSummaryPatchedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(summary, "summary");
}
}
@@ -1,16 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceAction;
import java.util.Objects;
public record StudioAssetsMutationAppliedEvent(
ProjectReference project,
AssetWorkspaceAction action,
int affectedAssets) implements StudioEvent {
public StudioAssetsMutationAppliedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(action, "action");
}
}
@@ -1,17 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceAction;
import java.util.Objects;
public record StudioAssetsMutationFailedEvent(
ProjectReference project,
AssetWorkspaceAction action,
String message) implements StudioEvent {
public StudioAssetsMutationFailedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(action, "action");
Objects.requireNonNull(message, "message");
}
}
@@ -1,16 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceAction;
import java.util.Objects;
public record StudioAssetsMutationPreviewReadyEvent(
ProjectReference project,
AssetWorkspaceAction action,
int affectedAssets) implements StudioEvent {
public StudioAssetsMutationPreviewReadyEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(action, "action");
}
}
@@ -1,15 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceNavigatorViewState;
import java.util.Objects;
public record StudioAssetsNavigatorViewStateChangedEvent(
ProjectReference project,
AssetWorkspaceNavigatorViewState viewState) implements StudioEvent {
public StudioAssetsNavigatorViewStateChangedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(viewState, "viewState");
}
}
@@ -1,16 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceSelectionKey;
import java.util.Objects;
public record StudioAssetsStructuralSyncRequestedEvent(
ProjectReference project,
AssetWorkspaceSelectionKey preferredSelectionKey,
String reason) implements StudioEvent {
public StudioAssetsStructuralSyncRequestedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(reason, "reason");
}
}
@@ -1,12 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioAssetsWorkspaceRefreshFailedEvent(ProjectReference project, String message) implements StudioEvent {
public StudioAssetsWorkspaceRefreshFailedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(message, "message");
}
}
@@ -1,11 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioAssetsWorkspaceRefreshStartedEvent(ProjectReference project) implements StudioEvent {
public StudioAssetsWorkspaceRefreshStartedEvent {
Objects.requireNonNull(project, "project");
}
}
@@ -1,14 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioAssetsWorkspaceRefreshedEvent(ProjectReference project, int assetCount) implements StudioEvent {
public StudioAssetsWorkspaceRefreshedEvent {
Objects.requireNonNull(project, "project");
if (assetCount < 0) {
throw new IllegalArgumentException("assetCount must not be negative");
}
}
}
@@ -1,15 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceSelectionKey;
import java.util.Objects;
public record StudioAssetsWorkspaceSelectionChangedEvent(
ProjectReference project,
AssetWorkspaceSelectionKey selectionKey) implements StudioEvent {
public StudioAssetsWorkspaceSelectionChangedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(selectionKey, "selectionKey");
}
}
@@ -1,15 +0,0 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import p.studio.workspaces.assets.AssetWorkspaceSelectionKey;
import java.util.Objects;
public record StudioAssetsWorkspaceSelectionRequestedEvent(
ProjectReference project,
AssetWorkspaceSelectionKey selectionKey) implements StudioEvent {
public StudioAssetsWorkspaceSelectionRequestedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(selectionKey, "selectionKey");
}
}
@@ -1,39 +1,25 @@
package p.studio.events;
import p.packer.api.events.PackerEvent;
import p.packer.api.events.PackerEventKind;
import p.packer.api.events.PackerEventSink;
import p.studio.projects.ProjectReference;
import p.packer.events.PackerEvent;
import p.packer.events.PackerEventSink;
import java.util.Objects;
public final class StudioPackerEventAdapter implements PackerEventSink {
private final StudioWorkspaceEventBus eventBus;
private final ProjectReference projectReference;
private final StudioEventBus eventBus;
public StudioPackerEventAdapter(StudioWorkspaceEventBus eventBus, ProjectReference projectReference) {
public StudioPackerEventAdapter(StudioEventBus eventBus) {
this.eventBus = Objects.requireNonNull(eventBus, "eventBus");
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
}
@Override
public void publish(PackerEvent event) {
final PackerEvent packerEvent = Objects.requireNonNull(event, "event");
if (ignore(packerEvent.kind())) {
return;
}
eventBus.publish(new StudioPackerOperationEvent(
projectReference,
packerEvent.operationId(),
packerEvent.kind(),
packerEvent.summary(),
packerEvent.progress() == null ? null : packerEvent.progress().value(),
packerEvent.progress() == null || packerEvent.progress().indeterminate()));
}
private boolean ignore(PackerEventKind kind) {
return kind == PackerEventKind.PREVIEW_READY
|| kind == PackerEventKind.ACTION_APPLIED
|| kind == PackerEventKind.ACTION_FAILED;
}
}
@@ -1,12 +1,10 @@
package p.studio.events;
import p.packer.api.events.PackerEventKind;
import p.studio.projects.ProjectReference;
import p.packer.events.PackerEventKind;
import java.util.Objects;
public record StudioPackerOperationEvent(
ProjectReference project,
String operationId,
PackerEventKind kind,
String summary,
@@ -14,7 +12,6 @@ public record StudioPackerOperationEvent(
boolean indeterminate) implements StudioEvent {
public StudioPackerOperationEvent {
Objects.requireNonNull(project, "project");
operationId = Objects.requireNonNull(operationId, "operationId").trim();
Objects.requireNonNull(kind, "kind");
summary = Objects.requireNonNull(summary, "summary").trim();
@@ -1,6 +1,4 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
public record StudioProjectCreatedEvent(ProjectReference project) implements StudioEvent {
public record StudioProjectCreatedEvent() implements StudioEvent {
}
@@ -1,11 +1,4 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioProjectLoadingCompletedEvent(ProjectReference project) implements StudioEvent {
public StudioProjectLoadingCompletedEvent {
Objects.requireNonNull(project, "project");
}
public record StudioProjectLoadingCompletedEvent() implements StudioEvent {
}
@@ -1,16 +1,12 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioProjectLoadingFailedEvent(
ProjectReference project,
StudioProjectLoadingPhase phase,
String message) implements StudioEvent {
public StudioProjectLoadingFailedEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(phase, "phase");
Objects.requireNonNull(message, "message");
}
@@ -1,18 +1,14 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioProjectLoadingProgressEvent(
ProjectReference project,
StudioProjectLoadingPhase phase,
String message,
double progress,
boolean indeterminate) implements StudioEvent {
public StudioProjectLoadingProgressEvent {
Objects.requireNonNull(project, "project");
Objects.requireNonNull(phase, "phase");
Objects.requireNonNull(message, "message");
if (!indeterminate && (progress < 0.0d || progress > 1.0d)) {
@@ -1,11 +1,4 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
import java.util.Objects;
public record StudioProjectLoadingStartedEvent(ProjectReference project) implements StudioEvent {
public StudioProjectLoadingStartedEvent {
Objects.requireNonNull(project, "project");
}
public record StudioProjectLoadingStartedEvent() implements StudioEvent {
}
@@ -1,6 +1,4 @@
package p.studio.events;
import p.studio.projects.ProjectReference;
public record StudioProjectOpenedEvent(ProjectReference project) implements StudioEvent {
public record StudioProjectOpenedEvent() implements StudioEvent {
}
@@ -104,6 +104,12 @@ public final class ProjectCatalogService {
try {
Files.createDirectories(normalizedParent);
Files.createDirectories(projectRoot.resolve(".workspace"));
Files.createDirectories(ProjectStudioPaths.studioRoot(new ProjectReference(
displayName,
"1.0.0",
languageId,
request.stdlib(),
projectRoot)));
Files.createDirectories(projectRoot.resolve(sourceRoot));
Files.createDirectories(projectRoot.resolve("assets"));
Files.createDirectories(projectRoot.resolve("build"));
@@ -1,5 +1,8 @@
package p.studio.projects;
import org.apache.commons.lang3.StringUtils;
import p.packer.PackerProjectContext;
import java.nio.file.Path;
public record ProjectReference(
@@ -12,4 +15,24 @@ public record ProjectReference(
public String toString() {
return name;
}
private Path absoluteRootPath() {
return rootPath().toAbsolutePath().normalize();
}
private String displayRelativePath(final String resolve) {
final Path normalizedPath = rootPath.toAbsolutePath().normalize();
try {
final var path = StringUtils.isNotBlank(resolve)
? absoluteRootPath().resolve(resolve)
: absoluteRootPath();
return path.relativize(normalizedPath).toString().replace('\\', '/');
} catch (IllegalArgumentException ignored) {
return normalizedPath.toString().replace('\\', '/');
}
}
public PackerProjectContext toPackerProjectContext() {
return new PackerProjectContext(name, absoluteRootPath());
}
}
@@ -0,0 +1,27 @@
package p.studio.projects;
import java.nio.file.Path;
import java.util.Objects;
public final class ProjectStudioPaths {
private static final String STUDIO_DIR = ".studio";
private static final String ACTIVITIES_FILE = "activities.json";
private ProjectStudioPaths() {
}
public static Path studioRoot(ProjectReference projectReference) {
return Objects.requireNonNull(projectReference, "projectReference")
.rootPath()
.resolve(STUDIO_DIR)
.toAbsolutePath()
.normalize();
}
public static Path activitiesPath(ProjectReference projectReference) {
return studioRoot(projectReference)
.resolve(ACTIVITIES_FILE)
.toAbsolutePath()
.normalize();
}
}
@@ -79,12 +79,9 @@ public enum I18n {
WORKSPACE_ASSETS("workspace.assets"),
ASSETS_NAVIGATOR_TITLE("assets.navigator.title"),
ASSETS_NAVIGATOR_ACTION_REFRESH("assets.navigator.action.refresh"),
ASSETS_NAVIGATOR_ACTION_ADD("assets.navigator.action.add"),
ASSETS_NAVIGATOR_ACTION_DOCTOR("assets.navigator.action.doctor"),
ASSETS_NAVIGATOR_ACTION_PACK("assets.navigator.action.pack"),
ASSETS_DETAILS_TITLE("assets.details.title"),
ASSETS_SEARCH_PROMPT("assets.search.prompt"),
ASSETS_FILTER_REGISTERED("assets.filter.registered"),
ASSETS_FILTER_UNREGISTERED("assets.filter.unregistered"),
ASSETS_FILTER_DIAGNOSTICS("assets.filter.diagnostics"),
ASSETS_FILTER_PRELOAD("assets.filter.preload"),
@@ -99,6 +96,7 @@ public enum I18n {
ASSETS_BADGE_DIAGNOSTICS("assets.badge.diagnostics"),
ASSETS_SECTION_SUMMARY("assets.section.summary"),
ASSETS_SECTION_RUNTIME_CONTRACT("assets.section.runtimeContract"),
ASSETS_SUBSECTION_CODEC_CONFIGURATION("assets.subsection.codecConfiguration"),
ASSETS_SECTION_INPUTS_PREVIEW("assets.section.inputsPreview"),
ASSETS_SECTION_DIAGNOSTICS("assets.section.diagnostics"),
ASSETS_SECTION_ACTIONS("assets.section.actions"),
@@ -125,12 +123,17 @@ public enum I18n {
ASSETS_MUTATION_APPLY("assets.mutation.apply"),
ASSETS_MUTATION_CONFIRM_TITLE("assets.mutation.confirm.title"),
ASSETS_MUTATION_CONFIRM_HEADER("assets.mutation.confirm.header"),
FORM_ACTION_CHANGE("form.action.change"),
FORM_ACTION_APPLY("form.action.apply"),
FORM_ACTION_RESET("form.action.reset"),
FORM_ACTION_CANCEL("form.action.cancel"),
ASSETS_LABEL_NAME("assets.label.name"),
ASSETS_LABEL_REGISTRATION("assets.label.registration"),
ASSETS_LABEL_BUILD_PARTICIPATION("assets.label.buildParticipation"),
ASSETS_LABEL_ASSET_ID("assets.label.assetId"),
ASSETS_LABEL_TYPE("assets.label.type"),
ASSETS_LABEL_LOCATION("assets.label.location"),
ASSETS_LABEL_BANK("assets.label.bank"),
ASSETS_LABEL_TARGET_LOCATION("assets.label.targetLocation"),
ASSETS_LABEL_FORMAT("assets.label.format"),
ASSETS_LABEL_CODEC("assets.label.codec"),
@@ -163,6 +166,7 @@ public enum I18n {
ASSETS_DETAILS_EMPTY("assets.details.empty"),
ASSETS_DETAILS_READY("assets.details.ready"),
ASSETS_DETAILS_NO_SELECTION("assets.details.noSelection"),
ASSETS_DETAILS_CODEC_CONFIGURATION_EMPTY("assets.details.codecConfiguration.empty"),
ASSETS_ADD_WIZARD_TITLE("assets.addWizard.title"),
ASSETS_ADD_WIZARD_DESCRIPTION("assets.addWizard.description"),
ASSETS_ADD_WIZARD_STEP_ROOT_TITLE("assets.addWizard.step.root.title"),
@@ -186,6 +190,9 @@ public enum I18n {
ASSETS_ADD_WIZARD_BUTTON_CREATE("assets.addWizard.button.create"),
ASSETS_ADD_WIZARD_ERROR_NAME("assets.addWizard.error.name"),
ASSETS_ADD_WIZARD_ERROR_ROOT("assets.addWizard.error.root"),
ASSETS_ADD_WIZARD_ERROR_ROOT_RELATIVE("assets.addWizard.error.rootRelative"),
ASSETS_ADD_WIZARD_ERROR_ROOT_OUTSIDE_ASSETS("assets.addWizard.error.rootOutsideAssets"),
ASSETS_ADD_WIZARD_ERROR_ROOT_ALREADY_ASSET("assets.addWizard.error.rootAlreadyAsset"),
ASSETS_ADD_WIZARD_ERROR_TYPE("assets.addWizard.error.type"),
ASSETS_ADD_WIZARD_ERROR_FORMAT("assets.addWizard.error.format"),
ASSETS_ADD_WIZARD_ERROR_CODEC("assets.addWizard.error.codec"),
@@ -0,0 +1,63 @@
package p.studio.utilities.logspane;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.TextArea;
import javafx.scene.control.TitledPane;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import java.util.Objects;
public abstract class LogsPane implements StudioControlLifecycle {
private final TextArea textArea;
private final TitledPane pane;
protected LogsPane(
ObservableValue<String> titleBinding,
String workspace) {
this(titleBinding, workspace, true);
}
protected LogsPane(
ObservableValue<String> titleBinding,
String workspace,
boolean installLifecycle) {
final String workspaceName = Objects.requireNonNull(workspace, "workspace").trim();
if (workspaceName.isBlank()) {
throw new IllegalArgumentException("workspace must not be blank");
}
this.textArea = new TextArea();
textArea.setEditable(false);
textArea.setWrapText(true);
textArea.setPrefRowCount(8);
textArea.getStyleClass().add("%s-workspace-logs".formatted(workspaceName));
this.pane = new TitledPane();
pane.textProperty().bind(Objects.requireNonNull(titleBinding, "titleBinding"));
pane.setContent(textArea);
pane.setCollapsible(true);
pane.setExpanded(true);
pane.getStyleClass().add("%s-workspace-logs-pane".formatted(workspaceName));
if (installLifecycle) {
StudioControlLifecycleSupport.install(pane, this);
}
}
public final TitledPane getPane() {
return pane;
}
protected final void appendLine(String line) {
final String normalized = Objects.requireNonNullElse(line, "").stripTrailing();
if (normalized.isBlank()) {
return;
}
Platform.runLater(() -> textArea.appendText(normalized + System.lineSeparator()));
}
protected final void clearLogs() {
Platform.runLater(textArea::clear);
}
}
@@ -6,11 +6,10 @@ import p.studio.controls.shell.*;
import p.studio.events.StudioWorkspaceSelectedEvent;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.PlaceholderWorkspace;
import p.studio.workspaces.WorkspaceHost;
import p.studio.workspaces.WorkspaceId;
import p.studio.workspaces.assets.AssetWorkspace;
import p.studio.workspaces.builder.BuilderWorkspace;
import p.studio.workspaces.builder.ShipperWorkspace;
import p.studio.workspaces.editor.EditorWorkspace;
import java.util.List;
@@ -19,16 +18,16 @@ public final class MainView extends BorderPane {
private final WorkspaceHost host = new WorkspaceHost();
private final ProjectReference projectReference;
public MainView(ProjectReference projectReference) {
public MainView(final ProjectReference projectReference) {
this.projectReference = projectReference;
final var menuBar = new StudioShellMenuBarControl();
final var runSurface = new StudioRunSurfaceControl();
setTop(new StudioShellTopBarControl(menuBar));
host.register(new EditorWorkspace());
host.register(new AssetWorkspace(projectReference));
host.register(new BuilderWorkspace(projectReference));
host.register(new PlaceholderWorkspace(WorkspaceId.DEBUG, I18n.WORKSPACE_DEBUG, "Debug"));
host.register(new EditorWorkspace(projectReference));
// host.register(new PlaceholderWorkspace(WorkspaceId.DEBUG, I18n.WORKSPACE_DEBUG, "Debug"));
host.register(new ShipperWorkspace(projectReference));
final var workspaceRail = new StudioWorkspaceRailControl<>(
List.of(
@@ -37,25 +36,25 @@ public final class MainView extends BorderPane {
new StudioWorkspaceRailItem<>(WorkspaceId.DEBUG, "🎮", Container.i18n().bind(I18n.WORKSPACE_DEBUG)),
new StudioWorkspaceRailItem<>(WorkspaceId.SHIPPER, "⚙️", Container.i18n().bind(I18n.WORKSPACE_SHIPPER))
),
this::showWorkspace);
this::loadWorkspace);
setLeft(workspaceRail);
setCenter(host);
setRight(new StudioRightUtilityPanelControl(
runSurface,
Container.i18n().bind(I18n.SHELL_ACTIVITY),
new StudioActivityFeedControl()));
new StudioActivityFeedControl(projectReference)));
// default
workspaceRail.select(WorkspaceId.ASSETS);
showWorkspace(WorkspaceId.ASSETS);
loadWorkspace(WorkspaceId.ASSETS);
}
public ProjectReference projectReference() {
return projectReference;
}
private void showWorkspace(WorkspaceId workspaceId) {
host.show(workspaceId);
Container.events().publish(new StudioWorkspaceSelectedEvent(workspaceId));
private void loadWorkspace(WorkspaceId workspaceId) {
host.change(workspaceId);
Container.eventBus().publish(new StudioWorkspaceSelectedEvent(workspaceId));
}
}
@@ -1,11 +1,16 @@
package p.studio.window;
import javafx.animation.PauseTransition;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Duration;
import p.packer.messages.InitWorkspaceRequest;
import p.studio.Container;
import p.studio.events.StudioProjectLoadingCompletedEvent;
import p.studio.events.StudioProjectLoadingFailedEvent;
import p.studio.events.StudioProjectLoadingPhase;
import p.studio.events.StudioProjectLoadingProgressEvent;
import p.studio.events.StudioProjectLoadingStartedEvent;
import p.studio.events.StudioProjectCreatedEvent;
import p.studio.events.StudioProjectOpenedEvent;
import p.studio.projects.KnownProjectsService;
@@ -23,7 +28,6 @@ public final class StudioWindowCoordinator {
private static final double PROJECT_LOADING_HEIGHT = 250;
private static final double PROJECT_WIDTH = 1280;
private static final double PROJECT_HEIGHT = 840;
private static final Duration PROJECT_OPEN_DELAY = Duration.seconds(1.5);
private final Stage launcherStage;
private final ProjectCatalogService projectCatalogService;
@@ -67,14 +71,14 @@ public final class StudioWindowCoordinator {
private void openProject(ProjectReference projectReference) {
final ProjectReference opened = projectCatalogService.openProject(projectReference.rootPath());
knownProjectsService.remember(opened);
Container.events().publish(new StudioProjectOpenedEvent(opened));
Container.eventBus().publish(new StudioProjectOpenedEvent());
openProjectWindow(opened);
}
private void createProject(ProjectReference projectReference) {
knownProjectsService.remember(projectReference);
Container.events().publish(new StudioProjectCreatedEvent(projectReference));
Container.events().publish(new StudioProjectOpenedEvent(projectReference));
Container.eventBus().publish(new StudioProjectCreatedEvent());
Container.eventBus().publish(new StudioProjectOpenedEvent());
openProjectWindow(projectReference);
}
@@ -90,31 +94,12 @@ public final class StudioWindowCoordinator {
private void openProjectWindow(ProjectReference projectReference) {
final Stage loadingStage = createProjectLoadingStage(projectReference);
final Stage projectStage = new Stage();
final Scene scene = new Scene(new MainView(projectReference), PROJECT_WIDTH, PROJECT_HEIGHT);
scene.getStylesheets().add(Container.theme().getDefaultTheme());
projectStage.setTitle(Container.i18n().format(I18n.APP_PROJECT_TITLE, projectReference.name()));
projectStage.setScene(scene);
windowStateService.installProjectShellState(projectStage, projectReference, PROJECT_WIDTH, PROJECT_HEIGHT);
projectStage.setOnHidden(ignored -> {
launcherView.reloadProjects();
launcherStage.show();
launcherStage.centerOnScreen();
launcherStage.toFront();
});
launcherStage.hide();
loadingStage.show();
loadingStage.centerOnScreen();
loadingStage.toFront();
final PauseTransition delay = new PauseTransition(PROJECT_OPEN_DELAY);
delay.setOnFinished(ignored -> {
loadingStage.close();
projectStage.show();
projectStage.toFront();
});
delay.play();
publishProjectLoadingStarted(projectReference);
Container.backgroundTasks().submit(() -> initializeProjectAndOpenWindow(projectReference, loadingStage));
}
private Stage createProjectLoadingStage(ProjectReference projectReference) {
@@ -131,6 +116,88 @@ public final class StudioWindowCoordinator {
return loadingStage;
}
private void initializeProjectAndOpenWindow(ProjectReference projectReference, Stage loadingStage) {
try {
Container.eventBus().publish(new StudioProjectLoadingProgressEvent(
StudioProjectLoadingPhase.INITIALIZING_SERVICES,
Container.i18n().text(I18n.SHIELD_STATUS_INDEXING),
Progress.INITIALIZING_SERVICES,
false));
Container.packer()
.workspaceService()
.initWorkspace(new InitWorkspaceRequest(projectReference.toPackerProjectContext()));
Container.eventBus().publish(new StudioProjectLoadingProgressEvent(
StudioProjectLoadingPhase.RESTORING_WORKSPACES,
Container.i18n().text(I18n.SHIELD_STATUS_RESTORING),
Progress.RESTORING_WORKSPACES,
false));
Platform.runLater(() -> finishProjectOpen(projectReference, loadingStage));
} catch (RuntimeException exception) {
Platform.runLater(() -> failProjectOpen(projectReference, loadingStage, exception));
}
}
private void finishProjectOpen(ProjectReference projectReference, Stage loadingStage) {
final Stage projectStage = new Stage();
final Scene scene = new Scene(new MainView(projectReference), PROJECT_WIDTH, PROJECT_HEIGHT);
scene.getStylesheets().add(Container.theme().getDefaultTheme());
projectStage.setTitle(Container.i18n().format(I18n.APP_PROJECT_TITLE, projectReference.name()));
projectStage.setScene(scene);
windowStateService.installProjectShellState(projectStage, projectReference, PROJECT_WIDTH, PROJECT_HEIGHT);
projectStage.setOnHidden(ignored -> {
launcherView.reloadProjects();
launcherStage.show();
launcherStage.centerOnScreen();
launcherStage.toFront();
});
Container.eventBus().publish(new StudioProjectLoadingProgressEvent(
StudioProjectLoadingPhase.READY,
Container.i18n().format(I18n.APP_PROJECT_TITLE, projectReference.name()),
Progress.READY,
false));
Container.eventBus().publish(new StudioProjectLoadingCompletedEvent());
loadingStage.close();
projectStage.show();
projectStage.toFront();
}
private void failProjectOpen(
ProjectReference projectReference,
Stage loadingStage,
RuntimeException exception) {
final String message = exception.getMessage() == null || exception.getMessage().isBlank()
? "Unable to initialize project services for " + projectReference.name() + "."
: exception.getMessage();
Container.eventBus().publish(new StudioProjectLoadingFailedEvent(
StudioProjectLoadingPhase.INITIALIZING_SERVICES,
message));
loadingStage.close();
launcherStage.show();
launcherStage.centerOnScreen();
launcherStage.toFront();
}
private void publishProjectLoadingStarted(ProjectReference projectReference) {
Container.eventBus().publish(new StudioProjectLoadingStartedEvent());
Container.eventBus().publish(new StudioProjectLoadingProgressEvent(
StudioProjectLoadingPhase.RESOLVING_PROJECT,
Container.i18n().format(I18n.SHIELD_LOADING_PROJECT, projectReference.name()),
Progress.RESOLVING_PROJECT,
false));
}
private static final class Progress {
private static final double RESOLVING_PROJECT = 0.20d;
private static final double INITIALIZING_SERVICES = 0.58d;
private static final double RESTORING_WORKSPACES = 0.86d;
private static final double READY = 1.0d;
private Progress() {
}
}
private Path resolveDefaultProjectsRoot() {
Path cursor = Path.of(System.getProperty("user.dir")).toAbsolutePath().normalize();
while (cursor != null) {
@@ -1,22 +0,0 @@
package p.studio.workspaces;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import p.studio.utilities.i18n.I18n;
public final class PlaceholderWorkspace implements Workspace {
private final WorkspaceId id;
private final I18n title;
private final StackPane root = new StackPane();
public PlaceholderWorkspace(WorkspaceId id, I18n title, String label) {
this.id = id;
this.title = title;
root.getChildren().add(new Label(label + " (TODO)"));
}
@Override public WorkspaceId id() { return id; }
@Override public I18n title() { return title; }
@Override public Node root() { return root; }
}
@@ -0,0 +1,59 @@
package p.studio.workspaces;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Node;
import javafx.scene.Scene;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import java.util.List;
import java.util.Objects;
public final class StudioWorkspaceLifecycleSupport {
private StudioWorkspaceLifecycleSupport() {
}
public static void activate(Workspace workspace) {
final Workspace target = Objects.requireNonNull(workspace, "workspace");
final Node rootNode = target.rootNode();
final Scene scene = rootNode.getScene();
if (scene != null) {
activateNow(target);
return;
}
rootNode.sceneProperty().addListener(new ChangeListener<>() {
@Override
public void changed(
ObservableValue<? extends Scene> observable,
Scene oldScene,
Scene newScene) {
if (newScene == null) {
return;
}
rootNode.sceneProperty().removeListener(this);
activateNow(target);
}
});
}
public static void deactivate(Workspace workspace) {
final Workspace target = Objects.requireNonNull(workspace, "workspace");
target.unLoad();
final List<StudioControlLifecycle> participants = target.lifecycleParticipants();
for (int index = participants.size() - 1; index >= 0; index--) {
participants.get(index).unsubscribe();
}
}
private static void activateNow(Workspace workspace) {
Platform.runLater(() -> {
final List<StudioControlLifecycle> participants = workspace.lifecycleParticipants();
for (StudioControlLifecycle participant : participants) {
participant.subscribe();
}
workspace.load();
});
}
}
@@ -1,12 +1,29 @@
package p.studio.workspaces;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
public interface Workspace {
WorkspaceId id();
I18n title();
javafx.scene.Node root();
default void onShow() {}
default void onHide() {}
}
import java.util.List;
public abstract class Workspace {
protected final ProjectReference projectReference;
protected final StudioWorkspaceEventBus workspaceEventBus;
public Workspace(final ProjectReference projectReference) {
this.projectReference = projectReference;
this.workspaceEventBus = new StudioWorkspaceEventBus(workspaceId(), Container.eventBus());
}
public abstract WorkspaceId workspaceId();
public abstract I18n title();
public abstract javafx.scene.Node rootNode();
public abstract void load();
public abstract void unLoad();
public List<StudioControlLifecycle> lifecycleParticipants() {
return List.of();
}
}
@@ -2,44 +2,46 @@ package p.studio.workspaces;
import javafx.scene.Node;
import javafx.scene.layout.StackPane;
import lombok.Getter;
import java.util.EnumMap;
import java.util.Map;
public final class WorkspaceHost extends StackPane {
private final Map<WorkspaceId, Workspace> workspaces = new EnumMap<>(WorkspaceId.class);
private WorkspaceId active;
@Getter
private WorkspaceId currentWorkspaceId;
public void register(Workspace ws) {
workspaces.put(ws.id(), ws);
workspaces.put(ws.workspaceId(), ws);
Node r = ws.root();
Node r = ws.rootNode();
r.setVisible(false);
r.setManaged(false);
getChildren().add(r);
}
public void show(WorkspaceId id) {
if (active == id) return;
public void change(final WorkspaceId id) {
if (currentWorkspaceId == id) return;
if (active != null) {
Workspace old = workspaces.get(active);
old.onHide();
Node n = old.root();
if (currentWorkspaceId != null) {
final var oldWorkspace = workspaces.get(currentWorkspaceId);
StudioWorkspaceLifecycleSupport.deactivate(oldWorkspace);
final var n = oldWorkspace.rootNode();
n.setVisible(false);
n.setManaged(false);
}
Workspace next = workspaces.get(id);
if (next == null) throw new IllegalStateException("Workspace not registered: " + id);
final var nextWorkspace = workspaces.get(id);
if (nextWorkspace == null) {
throw new IllegalStateException("Workspace not registered: " + id);
}
Node n = next.root();
final var n = nextWorkspace.rootNode();
n.setVisible(true);
n.setManaged(true);
next.onShow();
active = id;
currentWorkspaceId = id;
StudioWorkspaceLifecycleSupport.activate(nextWorkspace);
}
public WorkspaceId active() { return active; }
}
@@ -1,67 +0,0 @@
package p.studio.workspaces.assets;
import java.util.List;
import java.util.Objects;
public final class AssetCreationCatalog {
private static final List<AssetTypeOption> TYPES = List.of(
new AssetTypeOption(
"image_bank",
List.of(
new AssetFormatOption("TILES/indexed_v1", List.of("RAW")),
new AssetFormatOption("SPRITES/indexed_v1", List.of("RAW")))),
new AssetTypeOption(
"sound_bank",
List.of(new AssetFormatOption("AUDIO/pcm_v1", List.of("RAW")))),
new AssetTypeOption(
"palette_bank",
List.of(new AssetFormatOption("PALETTE/indexed_v1", List.of("RAW")))));
private AssetCreationCatalog() {
}
public static List<String> assetTypes() {
return TYPES.stream().map(AssetTypeOption::assetType).toList();
}
public static List<String> outputFormatsFor(String assetType) {
return findType(assetType).formats().stream().map(AssetFormatOption::outputFormat).toList();
}
public static List<String> outputCodecsFor(String assetType, String outputFormat) {
final AssetTypeOption type = findType(assetType);
return type.formats().stream()
.filter(format -> format.outputFormat().equals(outputFormat))
.findFirst()
.map(AssetFormatOption::codecs)
.orElse(List.of());
}
public static boolean supports(String assetType, String outputFormat, String outputCodec) {
return outputCodecsFor(assetType, outputFormat).contains(outputCodec);
}
private static AssetTypeOption findType(String assetType) {
final String normalized = Objects.requireNonNullElse(assetType, "").trim();
return TYPES.stream()
.filter(type -> type.assetType().equals(normalized))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unsupported asset type: " + assetType));
}
record AssetTypeOption(
String assetType,
List<AssetFormatOption> formats) {
AssetTypeOption {
formats = List.copyOf(formats);
}
}
record AssetFormatOption(
String outputFormat,
List<String> codecs) {
AssetFormatOption {
codecs = List.copyOf(codecs);
}
}
}
@@ -1,27 +0,0 @@
package p.studio.workspaces.assets;
import java.util.Objects;
public record AssetCreationRequest(
String assetName,
String relativeRoot,
String assetType,
String outputFormat,
String outputCodec,
boolean preloadEnabled) {
public AssetCreationRequest {
assetName = Objects.requireNonNull(assetName, "assetName").trim();
relativeRoot = Objects.requireNonNull(relativeRoot, "relativeRoot").trim();
assetType = Objects.requireNonNull(assetType, "assetType").trim();
outputFormat = Objects.requireNonNull(outputFormat, "outputFormat").trim();
outputCodec = Objects.requireNonNull(outputCodec, "outputCodec").trim();
if (assetName.isBlank()
|| relativeRoot.isBlank()
|| assetType.isBlank()
|| outputFormat.isBlank()
|| outputCodec.isBlank()) {
throw new IllegalArgumentException("Asset creation fields must not be blank.");
}
}
}
@@ -1,14 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.Objects;
public record AssetCreationResult(
AssetWorkspaceSelectionKey selectionKey,
Path assetRoot) {
public AssetCreationResult {
selectionKey = Objects.requireNonNull(selectionKey, "selectionKey");
assetRoot = Objects.requireNonNull(assetRoot, "assetRoot").toAbsolutePath().normalize();
}
}
@@ -1,7 +0,0 @@
package p.studio.workspaces.assets;
import p.studio.projects.ProjectReference;
public interface AssetCreationService {
AssetCreationResult create(ProjectReference projectReference, AssetCreationRequest request);
}
@@ -1,354 +0,0 @@
package p.studio.workspaces.assets;
import javafx.collections.FXCollections;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import p.studio.Container;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import java.io.File;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public final class AssetCreationWizard {
private final AssetCreationService assetCreationService;
private final ProjectReference projectReference;
private final Stage stage;
private final AtomicReference<AssetCreationResult> result = new AtomicReference<>();
private final Label stepTitle = new Label();
private final Label stepDescription = new Label();
private final VBox stepBody = new VBox(12);
private final Label feedbackLabel = new Label();
private final TextField rootField = new TextField();
private final TextField nameField = new TextField();
private final ComboBox<String> typeCombo = new ComboBox<>();
private final ComboBox<String> formatCombo = new ComboBox<>();
private final ComboBox<String> codecCombo = new ComboBox<>();
private final CheckBox preloadField = new CheckBox();
private final Button backButton = new Button();
private final Button nextButton = new Button();
private final Button createButton = new Button();
private final Button cancelButton = new Button();
private int stepIndex = 0;
private AssetCreationWizard(
Window owner,
ProjectReference projectReference,
AssetCreationService assetCreationService) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.assetCreationService = Objects.requireNonNull(assetCreationService, "assetCreationService");
this.stage = new Stage();
stage.initOwner(owner);
stage.initModality(Modality.WINDOW_MODAL);
stage.setTitle(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_TITLE));
stage.setScene(new Scene(buildRoot(), 620, 460));
stage.getScene().getStylesheets().add(Container.theme().getDefaultTheme());
configureControls();
renderStep();
}
public static Optional<AssetCreationResult> showAndWait(
Window owner,
ProjectReference projectReference,
AssetCreationService assetCreationService) {
final AssetCreationWizard wizard = new AssetCreationWizard(owner, projectReference, assetCreationService);
wizard.stage.showAndWait();
return Optional.ofNullable(wizard.result.get());
}
private VBox buildRoot() {
stepTitle.getStyleClass().add("studio-launcher-section-title");
stepDescription.getStyleClass().add("studio-launcher-subtitle");
stepDescription.setWrapText(true);
feedbackLabel.getStyleClass().add("studio-launcher-feedback");
feedbackLabel.setWrapText(true);
backButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_BACK));
backButton.getStyleClass().addAll("studio-button", "studio-button-secondary");
backButton.setOnAction(ignored -> goBack());
nextButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_NEXT));
nextButton.getStyleClass().addAll("studio-button", "studio-button-primary");
nextButton.setOnAction(ignored -> goNext());
createButton.textProperty().bind(Container.i18n().bind(I18n.ASSETS_ADD_WIZARD_BUTTON_CREATE));
createButton.getStyleClass().addAll("studio-button", "studio-button-primary");
createButton.setOnAction(ignored -> createAsset());
cancelButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_CANCEL));
cancelButton.getStyleClass().addAll("studio-button", "studio-button-cancel");
cancelButton.setOnAction(ignored -> stage.close());
final Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
final HBox actions = new HBox(12, backButton, spacer, cancelButton, nextButton, createButton);
actions.setAlignment(Pos.CENTER_RIGHT);
final VBox root = new VBox(16, stepTitle, stepDescription, stepBody, feedbackLabel, actions);
root.setPadding(new Insets(24));
VBox.setVgrow(stepBody, Priority.ALWAYS);
return root;
}
private void configureControls() {
rootField.setPromptText("ui/new_asset");
nameField.setPromptText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_NAME));
typeCombo.setPromptText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_PROMPT_TYPE));
formatCombo.setPromptText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_PROMPT_FORMAT));
codecCombo.setPromptText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_PROMPT_CODEC));
typeCombo.setMaxWidth(Double.MAX_VALUE);
formatCombo.setMaxWidth(Double.MAX_VALUE);
codecCombo.setMaxWidth(Double.MAX_VALUE);
typeCombo.setItems(FXCollections.observableArrayList(AssetCreationCatalog.assetTypes()));
formatCombo.setDisable(true);
codecCombo.setDisable(true);
preloadField.setSelected(true);
preloadField.textProperty().bind(Container.i18n().bind(I18n.ASSETS_ADD_WIZARD_LABEL_PRELOAD));
typeCombo.valueProperty().addListener((ignored, oldValue, newValue) -> {
if (Objects.equals(oldValue, newValue)) {
return;
}
formatCombo.setItems(FXCollections.observableArrayList());
formatCombo.getSelectionModel().clearSelection();
codecCombo.setItems(FXCollections.observableArrayList());
codecCombo.getSelectionModel().clearSelection();
codecCombo.setDisable(true);
if (newValue == null || newValue.isBlank()) {
formatCombo.setDisable(true);
return;
}
formatCombo.setItems(FXCollections.observableArrayList(AssetCreationCatalog.outputFormatsFor(newValue)));
formatCombo.setDisable(false);
});
formatCombo.valueProperty().addListener((ignored, oldValue, newValue) -> {
if (Objects.equals(oldValue, newValue)) {
return;
}
codecCombo.setItems(FXCollections.observableArrayList());
codecCombo.getSelectionModel().clearSelection();
if (newValue == null || newValue.isBlank() || typeCombo.getValue() == null || typeCombo.getValue().isBlank()) {
codecCombo.setDisable(true);
return;
}
codecCombo.setItems(FXCollections.observableArrayList(AssetCreationCatalog.outputCodecsFor(typeCombo.getValue(), newValue)));
codecCombo.setDisable(false);
});
}
private void renderStep() {
feedbackLabel.setText("");
backButton.setDisable(stepIndex == 0);
nextButton.setVisible(stepIndex < 2);
nextButton.setManaged(stepIndex < 2);
createButton.setVisible(stepIndex == 2);
createButton.setManaged(stepIndex == 2);
switch (stepIndex) {
case 0 -> renderRootStep();
case 1 -> renderMetadataStep();
case 2 -> renderSummaryStep();
default -> throw new IllegalStateException("Unknown asset creation step: " + stepIndex);
}
}
private void renderRootStep() {
stepTitle.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_ROOT_TITLE));
stepDescription.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_ROOT_DESCRIPTION));
final Label assetsRootLabel = new Label(Container.i18n().format(
I18n.ASSETS_ADD_WIZARD_ASSETS_ROOT_HINT,
AssetRootValidator.assetsRoot(projectReference).toString()));
assetsRootLabel.getStyleClass().add("studio-launcher-subtitle");
assetsRootLabel.setWrapText(true);
final Button browseButton = new Button(Container.i18n().text(I18n.WIZARD_BROWSE));
browseButton.getStyleClass().addAll("studio-button", "studio-button-secondary");
browseButton.setOnAction(ignored -> browseForRoot());
final HBox row = new HBox(12, rootField, browseButton);
row.setAlignment(Pos.CENTER_LEFT);
HBox.setHgrow(rootField, Priority.ALWAYS);
stepBody.getChildren().setAll(
field(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_ROOT), row),
assetsRootLabel);
}
private void renderMetadataStep() {
stepTitle.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_DETAILS_TITLE));
stepDescription.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_DETAILS_DESCRIPTION));
stepBody.getChildren().setAll(
field(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_NAME), nameField),
field(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_TYPE), typeCombo),
field(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_FORMAT), formatCombo),
field(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_CODEC), codecCombo));
}
private void renderSummaryStep() {
stepTitle.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_SUMMARY_TITLE));
stepDescription.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_STEP_SUMMARY_DESCRIPTION));
final AssetRootValidationResult rootValidation = AssetRootValidator.validate(projectReference, rootField.getText().trim());
final VBox summary = new VBox(8);
summary.getChildren().addAll(
summaryRow(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_ROOT), rootValidation.normalizedRelativeRoot()),
summaryRow(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_NAME), nameField.getText().trim()),
summaryRow(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_TYPE), Objects.requireNonNullElse(typeCombo.getValue(), "—")),
summaryRow(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_FORMAT), Objects.requireNonNullElse(formatCombo.getValue(), "—")),
summaryRow(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_LABEL_CODEC), Objects.requireNonNullElse(codecCombo.getValue(), "—")));
final Label note = new Label(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_NOTE));
note.getStyleClass().add("studio-launcher-subtitle");
note.setWrapText(true);
stepBody.getChildren().setAll(summary, preloadField, note);
}
private VBox field(String labelText, Node control) {
final Label label = new Label(labelText);
final VBox box = new VBox(6, label, control);
VBox.setVgrow(control, Priority.NEVER);
return box;
}
private Node summaryRow(String key, String value) {
final HBox row = new HBox(12);
final Label keyLabel = new Label(key);
keyLabel.getStyleClass().add("assets-details-key");
final Label valueLabel = new Label(value == null || value.isBlank() ? "—" : value);
valueLabel.getStyleClass().add("assets-details-value");
valueLabel.setWrapText(true);
HBox.setHgrow(valueLabel, Priority.ALWAYS);
row.getChildren().addAll(keyLabel, valueLabel);
return row;
}
private void goBack() {
if (stepIndex == 0) {
return;
}
stepIndex -= 1;
renderStep();
}
private void goNext() {
if (!validateCurrentStep()) {
return;
}
stepIndex += 1;
renderStep();
}
private boolean validateCurrentStep() {
return switch (stepIndex) {
case 0 -> validateRootStep();
case 1 -> validateMetadataStep();
default -> true;
};
}
private boolean validateRootStep() {
final AssetRootValidationResult validation = AssetRootValidator.validate(projectReference, rootField.getText().trim());
if (!validation.valid()) {
feedbackLabel.setText(validation.message().isBlank()
? Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_ROOT)
: validation.message());
return false;
}
rootField.setText(validation.normalizedRelativeRoot());
return true;
}
private boolean validateMetadataStep() {
if (nameField.getText().trim().isBlank()) {
feedbackLabel.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_NAME));
return false;
}
if (typeCombo.getValue() == null || typeCombo.getValue().isBlank()) {
feedbackLabel.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_TYPE));
return false;
}
if (formatCombo.getValue() == null || formatCombo.getValue().isBlank()) {
feedbackLabel.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_FORMAT));
return false;
}
if (codecCombo.getValue() == null || codecCombo.getValue().isBlank()) {
feedbackLabel.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_CODEC));
return false;
}
if (!AssetCreationCatalog.supports(typeCombo.getValue(), formatCombo.getValue(), codecCombo.getValue())) {
feedbackLabel.setText(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_ERROR_UNSUPPORTED_COMBINATION));
return false;
}
return true;
}
private void createAsset() {
feedbackLabel.setText("");
if (!validateRootStep() || !validateMetadataStep()) {
return;
}
try {
result.set(assetCreationService.create(projectReference, new AssetCreationRequest(
nameField.getText().trim(),
rootField.getText().trim(),
typeCombo.getValue(),
formatCombo.getValue(),
codecCombo.getValue(),
preloadField.isSelected())));
stage.close();
} catch (RuntimeException runtimeException) {
feedbackLabel.setText(Objects.requireNonNullElse(runtimeException.getMessage(), "Unable to create asset."));
}
}
private void browseForRoot() {
final DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle(Container.i18n().text(I18n.ASSETS_ADD_WIZARD_BROWSE_TITLE));
final File initialDirectory = AssetRootValidator.assetsRoot(projectReference).toFile();
if (initialDirectory.isDirectory()) {
chooser.setInitialDirectory(initialDirectory);
} else if (projectReference.rootPath().toFile().isDirectory()) {
chooser.setInitialDirectory(projectReference.rootPath().toFile());
}
final File selected = chooser.showDialog(stage);
if (selected == null) {
return;
}
final AssetRootValidationResult validation = AssetRootValidator.fromAbsoluteDirectory(projectReference, selected.toPath());
if (!validation.valid()) {
feedbackLabel.setText(validation.message());
return;
}
rootField.setText(validation.normalizedRelativeRoot());
feedbackLabel.setText("");
}
}
@@ -0,0 +1,45 @@
package p.studio.workspaces.assets;
import p.studio.Container;
import p.studio.events.StudioPackerOperationEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.utilities.i18n.I18n;
import p.studio.utilities.logspane.LogsPane;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshFailedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshStartedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshedEvent;
import p.studio.workspaces.framework.StudioEventAware;
import p.studio.workspaces.framework.StudioEventBindings;
import java.util.Objects;
public final class AssetLogsPane extends LogsPane implements StudioEventAware {
private final StudioWorkspaceEventBus workspaceBus;
private final StudioEventBindings eventBindings = new StudioEventBindings();
public AssetLogsPane(StudioWorkspaceEventBus workspaceBus) {
super(Container.i18n().bind(I18n.ASSETS_LOGS_TITLE), "assets", false);
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
}
@Override
public StudioEventBindings eventBindings() {
return eventBindings;
}
@Override
public void registerEventSubscriptions() {
eventBindings.listen(workspaceBus, StudioAssetsWorkspaceRefreshStartedEvent.class).handle(event -> {
appendLine("[refresh] Asset scan started.");
});
eventBindings.listen(workspaceBus, StudioAssetsWorkspaceRefreshedEvent.class).handle(event -> {
appendLine("[refresh] " + event.assetCount() + " assets loaded.");
});
eventBindings.listen(workspaceBus, StudioAssetsWorkspaceRefreshFailedEvent.class).handle(event -> {
appendLine("[error] " + event.message());
});
eventBindings.listen(Container.eventBus(), StudioPackerOperationEvent.class).handle(event -> {
appendLine("[" + event.kind().name().toLowerCase() + "] " + event.summary());
});
}
}
@@ -1,8 +0,0 @@
package p.studio.workspaces.assets;
public enum AssetNavigatorFilter {
REGISTERED,
UNREGISTERED,
DIAGNOSTICS,
PRELOAD
}
@@ -1,113 +0,0 @@
package p.studio.workspaces.assets;
import p.studio.projects.ProjectReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
final class AssetRelocationTargetValidator {
private static final String CONTROL_DIR = ".prometeu";
private AssetRelocationTargetValidator() {
}
static AssetRootValidationResult validate(
ProjectReference projectReference,
Path currentAssetRoot,
String parentRelativeRootText,
String destinationName) {
final String normalizedName = normalizeDestinationName(destinationName);
if (normalizedName == null) {
return AssetRootValidationResult.failure("Destination folder name is required.");
}
final Path parentRelativeRoot;
try {
parentRelativeRoot = normalizeParentRelativeRoot(parentRelativeRootText);
} catch (RuntimeException runtimeException) {
return AssetRootValidationResult.failure("Destination parent must stay inside assets/.");
}
final String relativeRootText = parentRelativeRoot.getNameCount() == 0
? normalizedName
: parentRelativeRoot.resolve(normalizedName).toString().replace('\\', '/');
return validate(projectReference, currentAssetRoot, AssetRootValidator.assetsRoot(projectReference).resolve(relativeRootText));
}
static AssetRootValidationResult validate(
ProjectReference projectReference,
Path currentAssetRoot,
Path targetRoot) {
Objects.requireNonNull(projectReference, "projectReference");
Objects.requireNonNull(currentAssetRoot, "currentAssetRoot");
if (targetRoot == null) {
return AssetRootValidationResult.failure("Relocation target is required.");
}
final Path assetsRoot = AssetRootValidator.assetsRoot(projectReference);
final Path normalizedTargetRoot = targetRoot.toAbsolutePath().normalize();
if (!normalizedTargetRoot.startsWith(assetsRoot)) {
return AssetRootValidationResult.failure("Relocation target must stay inside assets/.");
}
final Path relativeRoot = assetsRoot.relativize(normalizedTargetRoot);
if (relativeRoot.getNameCount() == 0) {
return AssetRootValidationResult.failure("Relocation target must point to an asset root inside assets/.");
}
if (CONTROL_DIR.equals(relativeRoot.getName(0).toString())) {
return AssetRootValidationResult.failure("Relocation target must not use the reserved .prometeu directory.");
}
final Path normalizedCurrentRoot = currentAssetRoot.toAbsolutePath().normalize();
if (normalizedTargetRoot.equals(normalizedCurrentRoot)) {
return AssetRootValidationResult.failure("Relocation target must be different from the current asset root.");
}
if (normalizedTargetRoot.startsWith(normalizedCurrentRoot)) {
return AssetRootValidationResult.failure("Relocation target must not be inside the current asset root.");
}
if (Files.exists(normalizedTargetRoot)) {
return AssetRootValidationResult.failure("Relocation target already exists: "
+ relativeRoot.toString().replace('\\', '/'));
}
return AssetRootValidationResult.success(relativeRoot.toString().replace('\\', '/'), normalizedTargetRoot);
}
static String normalizeParentForDisplay(Path assetsRoot, Path parentDirectory) {
final Path normalizedAssetsRoot = Objects.requireNonNull(assetsRoot, "assetsRoot").toAbsolutePath().normalize();
final Path normalizedParent = Objects.requireNonNull(parentDirectory, "parentDirectory").toAbsolutePath().normalize();
if (!normalizedParent.startsWith(normalizedAssetsRoot)) {
throw new IllegalArgumentException("Parent directory must stay inside assets/");
}
final Path relativeParent = normalizedAssetsRoot.relativize(normalizedParent);
return relativeParent.getNameCount() == 0 ? "." : relativeParent.toString().replace('\\', '/');
}
private static Path normalizeParentRelativeRoot(String parentRelativeRootText) {
final String trimmed = Objects.requireNonNullElse(parentRelativeRootText, "").trim();
if (trimmed.isBlank() || ".".equals(trimmed)) {
return Path.of("");
}
final Path relativeRoot = Path.of(trimmed).normalize();
if (relativeRoot.isAbsolute() || relativeRoot.startsWith("..")) {
throw new IllegalArgumentException("Parent directory must stay inside assets/");
}
if (relativeRoot.getNameCount() > 0 && CONTROL_DIR.equals(relativeRoot.getName(0).toString())) {
throw new IllegalArgumentException("Reserved directory");
}
return relativeRoot;
}
private static String normalizeDestinationName(String destinationName) {
final String trimmed = Objects.requireNonNullElse(destinationName, "").trim();
if (trimmed.isBlank()) {
return null;
}
final Path segment = Path.of(trimmed).normalize();
if (segment.isAbsolute() || segment.getNameCount() != 1 || ".".equals(trimmed) || "..".equals(trimmed)) {
return null;
}
return segment.getFileName().toString();
}
}
@@ -1,417 +0,0 @@
package p.studio.workspaces.assets;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.Window;
import p.studio.Container;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import java.io.File;
import java.nio.file.Path;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public final class AssetRelocationWizard {
private final ProjectReference projectReference;
private final AssetWorkspaceAssetSummary asset;
private final AssetWorkspaceMutationService mutationService;
private final Stage stage;
private final AtomicReference<AssetWorkspaceMutationPreview> result = new AtomicReference<>();
private final Label stepTitle = new Label();
private final Label stepDescription = new Label();
private final VBox stepBody = new VBox(12);
private final TextField parentField = new TextField();
private final TextField nameField = new TextField();
private final Label targetRootValue = new Label("—");
private final Label feedbackLabel = new Label();
private final Button backButton = new Button();
private final Button nextButton = new Button();
private final Button confirmButton = new Button();
private final Button cancelButton = new Button();
private AssetWorkspaceMutationPreview preview;
private int stepIndex = 0;
private AssetRelocationWizard(
Window owner,
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceMutationService mutationService) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.asset = Objects.requireNonNull(asset, "asset");
this.mutationService = Objects.requireNonNull(mutationService, "mutationService");
this.stage = new Stage();
stage.initOwner(owner);
stage.initModality(Modality.WINDOW_MODAL);
stage.setTitle(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_TITLE));
stage.setScene(new Scene(buildRoot(), 640, 440));
stage.getScene().getStylesheets().add(Container.theme().getDefaultTheme());
configureDefaults();
configureValidation();
renderStep();
}
public static Optional<AssetWorkspaceMutationPreview> showAndWait(
Window owner,
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceMutationService mutationService) {
final AssetRelocationWizard wizard = new AssetRelocationWizard(owner, projectReference, asset, mutationService);
wizard.stage.showAndWait();
return Optional.ofNullable(wizard.result.get());
}
private VBox buildRoot() {
stepTitle.getStyleClass().add("studio-launcher-section-title");
stepDescription.getStyleClass().add("studio-launcher-subtitle");
stepDescription.setWrapText(true);
feedbackLabel.getStyleClass().add("studio-launcher-feedback");
feedbackLabel.setWrapText(true);
backButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_BACK));
backButton.getStyleClass().addAll("studio-button", "studio-button-secondary");
backButton.setOnAction(ignored -> goBack());
nextButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_NEXT));
nextButton.getStyleClass().addAll("studio-button", "studio-button-primary");
nextButton.setOnAction(ignored -> goNext());
confirmButton.textProperty().bind(Container.i18n().bind(I18n.ASSETS_RELOCATE_WIZARD_BUTTON_CONFIRM));
confirmButton.getStyleClass().addAll("studio-button", "studio-button-primary");
confirmButton.setOnAction(ignored -> confirm());
cancelButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_CANCEL));
cancelButton.getStyleClass().addAll("studio-button", "studio-button-cancel");
cancelButton.setOnAction(ignored -> stage.close());
final Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
final HBox actions = new HBox(12, backButton, spacer, cancelButton, nextButton, confirmButton);
actions.setAlignment(Pos.CENTER_RIGHT);
final VBox root = new VBox(16, stepTitle, stepDescription, stepBody, feedbackLabel, actions);
root.setPadding(new Insets(24));
VBox.setVgrow(stepBody, Priority.ALWAYS);
return root;
}
private Node field(String labelText, Node control) {
final Label label = new Label(labelText);
final VBox box = new VBox(6, label, control);
VBox.setVgrow(control, Priority.NEVER);
return box;
}
private void configureDefaults() {
final Path assetsRoot = AssetRootValidator.assetsRoot(projectReference);
final Path currentRoot = asset.assetRoot().toAbsolutePath().normalize();
final Path currentParent = currentRoot.getParent() == null ? assetsRoot : currentRoot.getParent();
parentField.setText(AssetRelocationTargetValidator.normalizeParentForDisplay(assetsRoot, currentParent));
nameField.setPromptText(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_PROMPT_DESTINATION_NAME));
final String currentLeaf = currentRoot.getFileName() == null ? "" : currentRoot.getFileName().toString();
nameField.setText(currentLeaf);
}
private void configureValidation() {
parentField.textProperty().addListener((ignored, oldValue, newValue) -> refreshValidation());
nameField.textProperty().addListener((ignored, oldValue, newValue) -> refreshValidation());
}
private void renderStep() {
feedbackLabel.setText("");
backButton.setDisable(stepIndex == 0);
nextButton.setVisible(stepIndex == 0);
nextButton.setManaged(stepIndex == 0);
confirmButton.setVisible(stepIndex == 1);
confirmButton.setManaged(stepIndex == 1);
switch (stepIndex) {
case 0 -> renderDestinationStep();
case 1 -> renderSummaryStep();
default -> throw new IllegalStateException("Unknown relocation step: " + stepIndex);
}
}
private void renderDestinationStep() {
stepTitle.setText(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_STEP_DESTINATION_TITLE));
stepDescription.setText(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_STEP_DESTINATION_DESCRIPTION));
final Button browseButton = new Button();
browseButton.textProperty().bind(Container.i18n().bind(I18n.WIZARD_BROWSE));
browseButton.getStyleClass().addAll("studio-button", "studio-button-secondary");
browseButton.setOnAction(ignored -> browseForParent());
final HBox parentRow = new HBox(12, parentField, browseButton);
parentRow.setAlignment(Pos.CENTER_LEFT);
HBox.setHgrow(parentField, Priority.ALWAYS);
final Label currentRootValue = new Label(relativeAssetPath(asset.assetRoot()));
currentRootValue.getStyleClass().add("assets-details-value");
currentRootValue.setWrapText(true);
targetRootValue.getStyleClass().add("assets-details-value");
targetRootValue.setWrapText(true);
stepBody.getChildren().setAll(
field(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_LABEL_CURRENT_ROOT), currentRootValue),
field(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_LABEL_DESTINATION_PARENT), parentRow),
field(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_LABEL_DESTINATION_NAME), nameField),
field(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_LABEL_TARGET_ROOT), targetRootValue));
refreshValidation();
}
private void renderSummaryStep() {
stepTitle.setText(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_STEP_SUMMARY_TITLE));
stepDescription.setText(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_STEP_SUMMARY_DESCRIPTION));
final AssetWorkspaceMutationPreview currentPreview = Objects.requireNonNull(preview, "preview");
final Label note = new Label(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_NOTE));
note.getStyleClass().add("studio-launcher-subtitle");
note.setWrapText(true);
final VBox summary = new VBox(10);
summary.getChildren().addAll(
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_AFFECTED_ASSET),
createAffectedAssetContent(currentPreview)),
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_REGISTRY_IMPACT),
createMutationChangesContent(
AssetWorkspaceMutationImpactViewModel.from(currentPreview).registryChanges(),
Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_REGISTRY_IMPACT))),
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_WORKSPACE_IMPACT),
createMutationChangesContent(
AssetWorkspaceMutationImpactViewModel.from(currentPreview).workspaceChanges(),
Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_WORKSPACE_IMPACT))),
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_BLOCKERS),
createMutationMessages(
currentPreview.blockers(),
"assets-mutation-message-blocker",
Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_BLOCKERS))),
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_WARNINGS),
createMutationMessages(
currentPreview.warnings(),
"assets-mutation-message-warning",
Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_WARNINGS))),
createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_SAFE_FIXES),
createMutationMessages(
currentPreview.safeFixes(),
"assets-mutation-message-safe-fix",
Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_SAFE_FIXES))),
note);
stepBody.getChildren().setAll(summary);
confirmButton.setDisable(!currentPreview.canApply());
}
private void refreshValidation() {
final AssetRootValidationResult validation = currentValidation();
if (!validation.valid()) {
targetRootValue.setText("—");
feedbackLabel.setText(validation.message());
nextButton.setDisable(true);
confirmButton.setDisable(true);
return;
}
targetRootValue.setText(validation.normalizedRelativeRoot());
feedbackLabel.setText("");
nextButton.setDisable(false);
confirmButton.setDisable(false);
}
private void browseForParent() {
final DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle(Container.i18n().text(I18n.ASSETS_RELOCATE_WIZARD_BROWSE_TITLE));
final File initialDirectory = initialParentDirectory().toFile();
if (initialDirectory.isDirectory()) {
chooser.setInitialDirectory(initialDirectory);
}
final File selected = chooser.showDialog(stage);
if (selected == null) {
return;
}
final Path selectedDirectory = selected.toPath().toAbsolutePath().normalize();
final Path assetsRoot = AssetRootValidator.assetsRoot(projectReference);
if (!selectedDirectory.startsWith(assetsRoot)) {
feedbackLabel.setText("Destination parent must stay inside assets/.");
return;
}
final Path relativeParent = assetsRoot.relativize(selectedDirectory);
if (relativeParent.getNameCount() > 0 && ".prometeu".equals(relativeParent.getName(0).toString())) {
feedbackLabel.setText("Destination parent must not use the reserved .prometeu directory.");
return;
}
parentField.setText(AssetRelocationTargetValidator.normalizeParentForDisplay(assetsRoot, selectedDirectory));
refreshValidation();
}
private Path initialParentDirectory() {
final Path assetsRoot = AssetRootValidator.assetsRoot(projectReference);
try {
final String parentText = parentField.getText();
if (parentText == null || parentText.isBlank() || ".".equals(parentText.trim())) {
return assetsRoot;
}
final Path candidate = assetsRoot.resolve(parentField.getText().trim()).toAbsolutePath().normalize();
return candidate.startsWith(assetsRoot) && candidate.toFile().isDirectory() ? candidate : assetsRoot;
} catch (RuntimeException runtimeException) {
return assetsRoot;
}
}
private void goBack() {
if (stepIndex == 0) {
return;
}
preview = null;
stepIndex -= 1;
renderStep();
}
private void goNext() {
final AssetRootValidationResult validation = currentValidation();
if (!validation.valid()) {
feedbackLabel.setText(validation.message());
nextButton.setDisable(true);
return;
}
try {
preview = mutationService.preview(projectReference, asset, AssetWorkspaceAction.RELOCATE, validation.assetRoot());
} catch (RuntimeException runtimeException) {
preview = null;
feedbackLabel.setText(Objects.requireNonNullElse(runtimeException.getMessage(), "Unable to preview relocation."));
return;
}
stepIndex = 1;
renderStep();
}
private void confirm() {
final AssetWorkspaceMutationPreview currentPreview = preview;
if (currentPreview == null) {
feedbackLabel.setText("Relocation preview is required before confirmation.");
confirmButton.setDisable(true);
return;
}
if (!currentPreview.canApply()) {
feedbackLabel.setText(currentPreview.blockers().isEmpty()
? "Relocation cannot be applied."
: currentPreview.blockers().getFirst());
confirmButton.setDisable(true);
return;
}
try {
mutationService.apply(projectReference, currentPreview);
result.set(currentPreview);
stage.close();
} catch (RuntimeException runtimeException) {
feedbackLabel.setText(Objects.requireNonNullElse(runtimeException.getMessage(), "Unable to apply relocation."));
}
}
private AssetRootValidationResult currentValidation() {
return AssetRelocationTargetValidator.validate(
projectReference,
asset.assetRoot(),
parentField.getText(),
nameField.getText());
}
private Node createMutationSection(String title, Node content) {
final VBox section = new VBox(6);
final Label label = new Label(title);
label.getStyleClass().add("assets-mutation-section-title");
section.getChildren().addAll(label, content);
return section;
}
private Node createAffectedAssetContent(AssetWorkspaceMutationPreview currentPreview) {
final VBox box = new VBox(6);
box.getChildren().add(keyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_NAME), currentPreview.asset().assetName()));
box.getChildren().add(keyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_LOCATION),
relativeAssetPath(currentPreview.asset().assetRoot())));
if (currentPreview.targetAssetRoot() != null) {
box.getChildren().add(keyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_TARGET_LOCATION),
relativeAssetPath(currentPreview.targetAssetRoot())));
}
return box;
}
private Node createMutationChangesContent(java.util.List<AssetWorkspaceMutationChange> changes, String emptyText) {
if (changes.isEmpty()) {
final Label label = new Label(emptyText);
label.setWrapText(true);
label.getStyleClass().add("assets-details-section-message");
return label;
}
final VBox box = new VBox(6);
for (AssetWorkspaceMutationChange change : changes) {
final Label label = new Label(change.verb() + " · " + change.target());
label.getStyleClass().add("assets-mutation-change");
box.getChildren().add(label);
}
return box;
}
private Node createMutationMessages(java.util.List<String> messages, String styleClass, String emptyText) {
if (messages.isEmpty()) {
final Label label = new Label(emptyText);
label.setWrapText(true);
label.getStyleClass().add("assets-details-section-message");
return label;
}
final VBox box = new VBox(6);
for (String message : messages) {
final Label label = new Label(message);
label.setWrapText(true);
label.getStyleClass().add(styleClass);
box.getChildren().add(label);
}
return box;
}
private Node keyValueRow(String key, String value) {
final HBox row = new HBox(12);
final Label keyLabel = new Label(key);
keyLabel.getStyleClass().add("assets-details-key");
final Label valueLabel = new Label(value == null || value.isBlank() ? "—" : value);
valueLabel.getStyleClass().add("assets-details-value");
valueLabel.setWrapText(true);
HBox.setHgrow(valueLabel, Priority.ALWAYS);
row.getChildren().addAll(keyLabel, valueLabel);
return row;
}
private String relativeAssetPath(Path assetRoot) {
final Path assetsRoot = AssetRootValidator.assetsRoot(projectReference);
final Path normalizedAssetRoot = assetRoot.toAbsolutePath().normalize();
if (!normalizedAssetRoot.startsWith(assetsRoot)) {
return normalizedAssetRoot.toString();
}
return assetsRoot.relativize(normalizedAssetRoot).toString().replace('\\', '/');
}
}
@@ -1,25 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.Objects;
public record AssetRootValidationResult(
boolean valid,
String normalizedRelativeRoot,
Path assetRoot,
String message) {
public AssetRootValidationResult {
normalizedRelativeRoot = Objects.requireNonNullElse(normalizedRelativeRoot, "");
message = Objects.requireNonNullElse(message, "");
assetRoot = assetRoot == null ? null : assetRoot.toAbsolutePath().normalize();
}
public static AssetRootValidationResult success(String normalizedRelativeRoot, Path assetRoot) {
return new AssetRootValidationResult(true, normalizedRelativeRoot, assetRoot, "");
}
public static AssetRootValidationResult failure(String message) {
return new AssetRootValidationResult(false, "", null, message);
}
}
@@ -1,60 +0,0 @@
package p.studio.workspaces.assets;
import p.packer.api.PackerProjectContext;
import p.packer.foundation.PackerWorkspacePaths;
import p.studio.projects.ProjectReference;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
final class AssetRootValidator {
private static final String ASSET_MANIFEST = "asset.json";
private static final String CONTROL_DIR = ".prometeu";
private AssetRootValidator() {
}
static Path assetsRoot(ProjectReference projectReference) {
final ProjectReference reference = Objects.requireNonNull(projectReference, "projectReference");
return PackerWorkspacePaths.assetsRoot(new PackerProjectContext(reference.name(), reference.rootPath()));
}
static AssetRootValidationResult validate(ProjectReference projectReference, String relativeRootText) {
final Path relativeRoot;
try {
relativeRoot = Path.of(Objects.requireNonNullElse(relativeRootText, "").trim()).normalize();
} catch (RuntimeException runtimeException) {
return AssetRootValidationResult.failure("Asset root must be a valid relative path.");
}
if (relativeRootText == null || relativeRootText.isBlank() || relativeRoot.getNameCount() == 0 || relativeRoot.isAbsolute() || relativeRoot.startsWith("..")) {
return AssetRootValidationResult.failure("Asset root must stay inside assets/.");
}
if (CONTROL_DIR.equals(relativeRoot.getName(0).toString())) {
return AssetRootValidationResult.failure("Asset root must not target the reserved .prometeu directory.");
}
final Path assetsRoot = assetsRoot(projectReference);
final Path assetRoot = assetsRoot.resolve(relativeRoot).toAbsolutePath().normalize();
if (!assetRoot.startsWith(assetsRoot)) {
return AssetRootValidationResult.failure("Asset root must stay inside assets/.");
}
if (Files.isRegularFile(assetRoot.resolve(ASSET_MANIFEST))) {
return AssetRootValidationResult.failure("asset.json already exists at: " + relativeRoot.toString().replace('\\', '/'));
}
return AssetRootValidationResult.success(relativeRoot.toString().replace('\\', '/'), assetRoot);
}
static AssetRootValidationResult fromAbsoluteDirectory(ProjectReference projectReference, Path directory) {
if (directory == null) {
return AssetRootValidationResult.failure("Asset root is required.");
}
final Path assetsRoot = assetsRoot(projectReference);
final Path normalized = directory.toAbsolutePath().normalize();
if (!normalized.startsWith(assetsRoot)) {
return AssetRootValidationResult.failure("Choose a directory inside assets/.");
}
return validate(projectReference, assetsRoot.relativize(normalized).toString().replace('\\', '/'));
}
}
File diff suppressed because it is too large Load Diff
@@ -1,9 +0,0 @@
package p.studio.workspaces.assets;
public enum AssetWorkspaceAction {
REGISTER,
INCLUDE_IN_BUILD,
EXCLUDE_FROM_BUILD,
RELOCATE,
REMOVE
}
@@ -1,13 +0,0 @@
package p.studio.workspaces.assets;
import java.util.List;
import java.util.Objects;
public record AssetWorkspaceActionSet(
List<AssetWorkspaceAction> primaryActions,
List<AssetWorkspaceAction> sensitiveActions) {
public AssetWorkspaceActionSet {
primaryActions = List.copyOf(Objects.requireNonNull(primaryActions, "primaryActions"));
sensitiveActions = List.copyOf(Objects.requireNonNull(sensitiveActions, "sensitiveActions"));
}
}
@@ -1,30 +0,0 @@
package p.studio.workspaces.assets;
import java.util.List;
import java.util.Objects;
public final class AssetWorkspaceActionSetBuilder {
private AssetWorkspaceActionSetBuilder() {
}
public static AssetWorkspaceActionSet forAsset(AssetWorkspaceAssetSummary summary) {
Objects.requireNonNull(summary, "summary");
return switch (summary.state()) {
case REGISTERED -> summary.buildParticipation() == AssetWorkspaceBuildParticipation.INCLUDED
? new AssetWorkspaceActionSet(
List.of(),
List.of(
AssetWorkspaceAction.EXCLUDE_FROM_BUILD,
AssetWorkspaceAction.RELOCATE,
AssetWorkspaceAction.REMOVE))
: new AssetWorkspaceActionSet(
List.of(AssetWorkspaceAction.INCLUDE_IN_BUILD),
List.of(
AssetWorkspaceAction.RELOCATE,
AssetWorkspaceAction.REMOVE));
case UNREGISTERED -> new AssetWorkspaceActionSet(
List.of(AssetWorkspaceAction.REGISTER),
List.of(AssetWorkspaceAction.RELOCATE));
};
}
}
@@ -1,22 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public record AssetWorkspaceAssetDetails(
AssetWorkspaceAssetSummary summary,
String outputFormat,
String outputCodec,
Map<String, List<Path>> inputsByRole,
List<AssetWorkspaceDiagnostic> diagnostics) {
public AssetWorkspaceAssetDetails {
Objects.requireNonNull(summary, "summary");
outputFormat = Objects.requireNonNullElse(outputFormat, "unknown");
outputCodec = Objects.requireNonNullElse(outputCodec, "unknown");
inputsByRole = Map.copyOf(Objects.requireNonNull(inputsByRole, "inputsByRole"));
diagnostics = List.copyOf(Objects.requireNonNull(diagnostics, "diagnostics"));
}
}
@@ -1,125 +0,0 @@
package p.studio.workspaces.assets;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.Objects;
final class AssetWorkspaceDetailsControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private final Label workspaceSummaryLabel = new Label();
private final VBox detailsContent = new VBox(12);
private final ScrollPane detailsScroll = new ScrollPane();
private final AssetWorkspaceSummaryActionsControl summaryActionsControl;
private final AssetWorkspaceRuntimeContractControl runtimeContractControl;
private final AssetWorkspaceInputsPreviewControl inputsPreviewControl;
private final AssetWorkspaceDiagnosticsControl diagnosticsControl;
private AssetWorkspaceDetailsViewState viewState;
private boolean readyMounted;
AssetWorkspaceDetailsControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.summaryActionsControl = new AssetWorkspaceSummaryActionsControl(projectReference, workspaceBus, interactions);
this.runtimeContractControl = new AssetWorkspaceRuntimeContractControl(projectReference, workspaceBus, interactions);
this.inputsPreviewControl = new AssetWorkspaceInputsPreviewControl(projectReference, workspaceBus, interactions);
this.diagnosticsControl = new AssetWorkspaceDiagnosticsControl(projectReference, workspaceBus);
getStyleClass().add("assets-workspace-pane");
setSpacing(10);
final Label detailsTitle = new Label();
detailsTitle.textProperty().bind(Container.i18n().bind(I18n.ASSETS_DETAILS_TITLE));
detailsTitle.getStyleClass().add("assets-workspace-pane-title");
workspaceSummaryLabel.getStyleClass().add("assets-workspace-summary");
detailsContent.getStyleClass().add("assets-workspace-details-content");
detailsScroll.setContent(detailsContent);
detailsScroll.setFitToWidth(true);
detailsScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
detailsScroll.getStyleClass().add("assets-workspace-details-scroll");
getChildren().addAll(detailsTitle, workspaceSummaryLabel, detailsScroll);
VBox.setVgrow(detailsScroll, Priority.ALWAYS);
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
viewState = event.viewState();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
void scrollToTop() {
detailsScroll.setVvalue(0.0d);
}
private void render() {
if (viewState == null) {
readyMounted = false;
workspaceSummaryLabel.setText(Container.i18n().text(I18n.ASSETS_SUMMARY_LOADING));
detailsContent.getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING)));
return;
}
switch (viewState.workspaceState().status()) {
case LOADING -> {
readyMounted = false;
workspaceSummaryLabel.setText(Container.i18n().text(I18n.ASSETS_SUMMARY_LOADING));
detailsContent.getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING)));
}
case EMPTY -> {
readyMounted = false;
workspaceSummaryLabel.setText(Container.i18n().text(I18n.ASSETS_SUMMARY_EMPTY));
detailsContent.getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY)));
}
case ERROR -> {
readyMounted = false;
workspaceSummaryLabel.setText(Container.i18n().text(I18n.ASSETS_SUMMARY_ERROR));
detailsContent.getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSectionMessage(viewState.workspaceState().errorMessage()));
}
case READY -> {
workspaceSummaryLabel.setText(Container.i18n().format(I18n.ASSETS_SUMMARY_READY, viewState.workspaceState().assets().size()));
if (viewState.workspaceState().selectedAsset().isEmpty()) {
readyMounted = false;
detailsContent.getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_NO_SELECTION)));
return;
}
if (!readyMounted) {
readyMounted = true;
detailsContent.getChildren().setAll(
summaryActionsControl,
runtimeContractControl,
inputsPreviewControl,
diagnosticsControl);
}
}
}
}
}
@@ -1,125 +0,0 @@
package p.studio.workspaces.assets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
final class AssetWorkspaceDetailsUiSupport {
private AssetWorkspaceDetailsUiSupport() {
}
static VBox createSection(String title, Node content) {
final VBox section = new VBox(10);
section.getStyleClass().add("assets-details-section");
final Label titleLabel = new Label(title);
titleLabel.getStyleClass().add("assets-details-section-title");
section.getChildren().addAll(titleLabel, content);
return section;
}
static Node createSectionMessage(String text) {
final Label label = new Label(text);
label.setWrapText(true);
label.getStyleClass().add("assets-details-section-message");
return label;
}
static Node createKeyValueRow(String key, String value) {
final Label valueLabel = new Label(value);
valueLabel.getStyleClass().add("assets-details-value");
valueLabel.setWrapText(true);
return createKeyValueRow(key, valueLabel);
}
static Node createKeyValueRow(String key, Node valueNode) {
final HBox row = new HBox(12);
row.setAlignment(Pos.TOP_LEFT);
final Label keyLabel = new Label(key);
keyLabel.getStyleClass().add("assets-details-key");
HBox.setHgrow(valueNode, Priority.ALWAYS);
row.getChildren().addAll(keyLabel, valueNode);
return row;
}
static String registrationLabel(AssetWorkspaceAssetState state) {
return switch (state) {
case REGISTERED -> Container.i18n().text(I18n.ASSETS_VALUE_REGISTERED);
case UNREGISTERED -> Container.i18n().text(I18n.ASSETS_VALUE_UNREGISTERED);
};
}
static String buildParticipationLabel(AssetWorkspaceBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_INCLUDED);
case EXCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_EXCLUDED);
};
}
static String yesNo(boolean value) {
return value ? Container.i18n().text(I18n.ASSETS_VALUE_YES) : Container.i18n().text(I18n.ASSETS_VALUE_NO);
}
static String projectRelativePath(ProjectReference projectReference, Path path) {
try {
return projectReference.rootPath().relativize(path.toAbsolutePath().normalize()).toString();
} catch (RuntimeException runtimeException) {
return path.toString();
}
}
static String actionLabel(AssetWorkspaceAction action) {
return switch (action) {
case REGISTER -> Container.i18n().text(I18n.ASSETS_ACTION_REGISTER);
case INCLUDE_IN_BUILD -> Container.i18n().text(I18n.ASSETS_ACTION_INCLUDE_IN_BUILD);
case EXCLUDE_FROM_BUILD -> Container.i18n().text(I18n.ASSETS_ACTION_EXCLUDE_FROM_BUILD);
case RELOCATE -> Container.i18n().text(I18n.ASSETS_ACTION_RELOCATE);
case REMOVE -> Container.i18n().text(I18n.ASSETS_ACTION_REMOVE);
};
}
static String actionButtonVariant(AssetWorkspaceAction action, boolean sensitive) {
if (!sensitive) {
return "studio-button-primary";
}
return switch (action) {
case RELOCATE -> "studio-button-warning";
case EXCLUDE_FROM_BUILD, REMOVE -> "studio-button-danger";
default -> "studio-button-secondary";
};
}
static boolean containsInput(AssetWorkspaceAssetDetails details, Path input) {
return details.inputsByRole().values().stream().flatMap(List::stream).anyMatch(input::equals);
}
static String extensionOf(Path input) {
final String fileName = input.getFileName().toString();
final int dot = fileName.lastIndexOf('.');
if (dot < 0 || dot == fileName.length() - 1) {
return "";
}
return fileName.substring(dot + 1).toLowerCase(Locale.ROOT);
}
static boolean isImage(String extension) {
return extension.equals("png") || extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif");
}
static boolean isText(String extension) {
return extension.equals("txt") || extension.equals("json") || extension.equals("md") || extension.equals("xml") || extension.equals("csv");
}
static boolean isAudio(String extension) {
return extension.equals("wav") || extension.equals("mp3") || extension.equals("ogg");
}
}
@@ -1,19 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.Objects;
public record AssetWorkspaceDetailsViewState(
AssetWorkspaceState workspaceState,
AssetWorkspaceDetailsStatus detailsStatus,
AssetWorkspaceAssetDetails selectedAssetDetails,
String detailsErrorMessage,
AssetWorkspaceMutationPreview stagedMutationPreview,
Path selectedPreviewInput,
int selectedPreviewZoom) {
public AssetWorkspaceDetailsViewState {
Objects.requireNonNull(workspaceState, "workspaceState");
Objects.requireNonNull(detailsStatus, "detailsStatus");
}
}
@@ -1,16 +0,0 @@
package p.studio.workspaces.assets;
import java.util.Objects;
public record AssetWorkspaceDiagnostic(
AssetWorkspaceDiagnosticSeverity severity,
String message) {
public AssetWorkspaceDiagnostic {
Objects.requireNonNull(severity, "severity");
message = Objects.requireNonNull(message, "message").trim();
if (message.isBlank()) {
throw new IllegalArgumentException("message must not be blank");
}
}
}
@@ -1,7 +0,0 @@
package p.studio.workspaces.assets;
public enum AssetWorkspaceDiagnosticSeverity {
BLOCKER,
WARNING,
HINT
}
@@ -1,85 +0,0 @@
package p.studio.workspaces.assets;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.Objects;
final class AssetWorkspaceDiagnosticsControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceDetailsViewState viewState;
AssetWorkspaceDiagnosticsControl(ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
viewState = event.viewState();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void render() {
if (viewState == null || viewState.workspaceState().selectedAsset().isEmpty()) {
getChildren().clear();
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.LOADING) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_DIAGNOSTICS),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING))));
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.ERROR || viewState.selectedAssetDetails() == null) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_DIAGNOSTICS),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Objects.requireNonNullElse(viewState.detailsErrorMessage(), Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY)))));
return;
}
if (viewState.selectedAssetDetails().diagnostics().isEmpty()) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_DIAGNOSTICS),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DIAGNOSTICS_EMPTY))));
return;
}
final VBox diagnosticsBox = new VBox(8);
for (AssetWorkspaceDiagnostic diagnostic : viewState.selectedAssetDetails().diagnostics()) {
final VBox card = new VBox(4);
card.getStyleClass().add("assets-details-diagnostic-card");
card.getStyleClass().add("assets-details-diagnostic-" + diagnostic.severity().name().toLowerCase());
final Label severity = new Label(diagnostic.severity().name());
severity.getStyleClass().add("assets-details-diagnostic-severity");
final Label message = new Label(diagnostic.message());
message.getStyleClass().add("assets-details-diagnostic-message");
message.setWrapText(true);
card.getChildren().addAll(severity, message);
diagnosticsBox.getChildren().add(card);
}
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_DIAGNOSTICS), diagnosticsBox));
}
}
@@ -1,202 +0,0 @@
package p.studio.workspaces.assets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;
final class AssetWorkspaceInputsPreviewControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final AssetWorkspaceInteractionPort interactions;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceDetailsViewState viewState;
AssetWorkspaceInputsPreviewControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.interactions = Objects.requireNonNull(interactions, "interactions");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
viewState = event.viewState();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void render() {
if (viewState == null || viewState.workspaceState().selectedAsset().isEmpty()) {
getChildren().clear();
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.LOADING) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_INPUTS_PREVIEW),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING))));
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.ERROR || viewState.selectedAssetDetails() == null) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_INPUTS_PREVIEW),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Objects.requireNonNullElse(viewState.detailsErrorMessage(), Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY)))));
return;
}
final AssetWorkspaceAssetDetails details = viewState.selectedAssetDetails();
if (details.inputsByRole().isEmpty()) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_INPUTS_PREVIEW),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_INPUTS_EMPTY))));
return;
}
final Path selectedPreviewInput = resolveSelectedPreviewInput(details);
final VBox inputsList = new VBox(8);
for (Map.Entry<String, List<Path>> entry : details.inputsByRole().entrySet()) {
final VBox roleBox = new VBox(6);
final Label roleLabel = new Label(entry.getKey());
roleLabel.getStyleClass().add("assets-details-role-label");
roleBox.getChildren().add(roleLabel);
for (Path input : entry.getValue()) {
final Button inputButton = new Button(input.getFileName().toString());
inputButton.getStyleClass().addAll("assets-details-input-button", "studio-button", "studio-button-secondary");
if (input.equals(selectedPreviewInput)) {
inputButton.getStyleClass().add("studio-button-active");
}
inputButton.setMaxWidth(Double.MAX_VALUE);
inputButton.setOnAction(event -> interactions.updatePreviewInput(input));
roleBox.getChildren().add(inputButton);
}
inputsList.getChildren().add(roleBox);
}
final SplitPane splitPane = new SplitPane(inputsList, createPreviewPane(selectedPreviewInput));
splitPane.setOrientation(Orientation.HORIZONTAL);
splitPane.setDividerPositions(0.34);
splitPane.getStyleClass().add("assets-details-input-preview-split");
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_INPUTS_PREVIEW), splitPane));
}
private Path resolveSelectedPreviewInput(AssetWorkspaceAssetDetails details) {
final Path selectedPreviewInput = viewState.selectedPreviewInput();
if (selectedPreviewInput == null || !AssetWorkspaceDetailsUiSupport.containsInput(details, selectedPreviewInput)) {
return details.inputsByRole().values().stream().flatMap(List::stream).findFirst().orElse(null);
}
return selectedPreviewInput;
}
private Node createPreviewPane(Path input) {
final VBox previewBox = new VBox(10);
previewBox.getStyleClass().add("assets-details-preview-pane");
if (input == null) {
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_PREVIEW_EMPTY)));
return previewBox;
}
final Label title = new Label(input.getFileName().toString());
title.getStyleClass().add("assets-details-preview-title");
previewBox.getChildren().add(title);
final String extension = AssetWorkspaceDetailsUiSupport.extensionOf(input);
if (AssetWorkspaceDetailsUiSupport.isImage(extension)) {
try {
final Image image = new Image(input.toUri().toString(), false);
final ImageView imageView = new ImageView(image);
imageView.setPreserveRatio(true);
imageView.setSmooth(false);
imageView.getStyleClass().add("assets-details-preview-image");
previewBox.getChildren().add(createPreviewZoomBar(image));
AssetWorkspace.applyPreviewScale(image, imageView, viewState.selectedPreviewZoom());
previewBox.getChildren().add(imageView);
} catch (RuntimeException runtimeException) {
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_PREVIEW_IMAGE_ERROR)));
}
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_LOCATION), AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, input)));
return previewBox;
}
if (AssetWorkspaceDetailsUiSupport.isText(extension)) {
final TextArea textArea = new TextArea(AssetWorkspace.readPreviewText(input));
textArea.setWrapText(true);
textArea.setEditable(false);
textArea.getStyleClass().add("assets-details-preview-text");
previewBox.getChildren().add(textArea);
return previewBox;
}
if (AssetWorkspaceDetailsUiSupport.isAudio(extension)) {
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().format(I18n.ASSETS_PREVIEW_AUDIO_PLACEHOLDER, input.getFileName().toString())));
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_LOCATION), AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, input)));
return previewBox;
}
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().format(I18n.ASSETS_PREVIEW_GENERIC_PLACEHOLDER, input.getFileName().toString())));
previewBox.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_LOCATION), AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, input)));
return previewBox;
}
private Node createPreviewZoomBar(Image image) {
final HBox zoomBar = new HBox(8);
zoomBar.setAlignment(Pos.CENTER_LEFT);
zoomBar.getStyleClass().add("assets-details-preview-zoom-bar");
final Label zoomLabel = new Label(Container.i18n().text(I18n.ASSETS_PREVIEW_ZOOM));
zoomLabel.getStyleClass().add("assets-details-preview-zoom-label");
zoomBar.getChildren().add(zoomLabel);
final ToggleGroup zoomGroup = new ToggleGroup();
final int maxZoom = AssetWorkspace.maxPreviewZoom(image);
for (int zoom : List.of(1, 2, 4, 8)) {
final ToggleButton button = new ToggleButton("x" + zoom);
button.getStyleClass().addAll(
"assets-details-preview-zoom-button",
"studio-button",
"studio-button-secondary",
"studio-button-pill",
"studio-button-toggle");
button.setToggleGroup(zoomGroup);
button.setSelected(viewState.selectedPreviewZoom() == zoom);
button.setDisable(zoom > maxZoom);
button.setOnAction(event -> interactions.updatePreviewZoom(zoom));
zoomBar.getChildren().add(button);
}
return zoomBar;
}
}
@@ -1,18 +0,0 @@
package p.studio.workspaces.assets;
import javafx.scene.control.CheckBox;
import java.nio.file.Path;
import java.util.EnumSet;
interface AssetWorkspaceInteractionPort {
void updateSearchQuery(String searchQuery);
void updateActiveFilters(EnumSet<AssetNavigatorFilter> filters);
void selectAsset(AssetWorkspaceSelectionKey selectionKey);
void requestMutationPreview(AssetWorkspaceAction action);
void cancelStagedMutationPreview();
void applyStagedMutation(AssetWorkspaceMutationPreview preview);
void updatePreviewInput(Path input);
void updatePreviewZoom(int zoom);
void updatePreload(AssetWorkspaceAssetDetails details, boolean preloadEnabled, CheckBox checkBox);
}
@@ -1,18 +0,0 @@
package p.studio.workspaces.assets;
import java.util.Objects;
public record AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope scope,
String verb,
String target) {
public AssetWorkspaceMutationChange {
Objects.requireNonNull(scope, "scope");
verb = Objects.requireNonNull(verb, "verb").trim();
target = Objects.requireNonNull(target, "target").trim();
if (verb.isBlank() || target.isBlank()) {
throw new IllegalArgumentException("verb and target must not be blank");
}
}
}
@@ -1,6 +0,0 @@
package p.studio.workspaces.assets;
public enum AssetWorkspaceMutationChangeScope {
REGISTRY,
WORKSPACE
}
@@ -1,25 +0,0 @@
package p.studio.workspaces.assets;
import java.util.List;
import java.util.Objects;
public record AssetWorkspaceMutationImpactViewModel(
List<AssetWorkspaceMutationChange> registryChanges,
List<AssetWorkspaceMutationChange> workspaceChanges) {
public AssetWorkspaceMutationImpactViewModel {
registryChanges = List.copyOf(Objects.requireNonNull(registryChanges, "registryChanges"));
workspaceChanges = List.copyOf(Objects.requireNonNull(workspaceChanges, "workspaceChanges"));
}
public static AssetWorkspaceMutationImpactViewModel from(AssetWorkspaceMutationPreview preview) {
Objects.requireNonNull(preview, "preview");
return new AssetWorkspaceMutationImpactViewModel(
preview.changes().stream()
.filter(change -> change.scope() == AssetWorkspaceMutationChangeScope.REGISTRY)
.toList(),
preview.changes().stream()
.filter(change -> change.scope() == AssetWorkspaceMutationChangeScope.WORKSPACE)
.toList());
}
}
@@ -1,30 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
public record AssetWorkspaceMutationPreview(
AssetWorkspaceAction action,
AssetWorkspaceAssetSummary asset,
List<String> blockers,
List<String> warnings,
List<String> safeFixes,
List<AssetWorkspaceMutationChange> changes,
boolean highRisk,
Path targetAssetRoot) {
public AssetWorkspaceMutationPreview {
Objects.requireNonNull(action, "action");
Objects.requireNonNull(asset, "asset");
blockers = List.copyOf(Objects.requireNonNull(blockers, "blockers"));
warnings = List.copyOf(Objects.requireNonNull(warnings, "warnings"));
safeFixes = List.copyOf(Objects.requireNonNull(safeFixes, "safeFixes"));
changes = List.copyOf(Objects.requireNonNull(changes, "changes"));
targetAssetRoot = targetAssetRoot == null ? null : targetAssetRoot.toAbsolutePath().normalize();
}
public boolean canApply() {
return blockers.isEmpty();
}
}
@@ -1,22 +0,0 @@
package p.studio.workspaces.assets;
import p.studio.projects.ProjectReference;
import java.nio.file.Path;
public interface AssetWorkspaceMutationService {
default AssetWorkspaceMutationPreview preview(
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceAction action) {
return preview(projectReference, asset, action, null);
}
AssetWorkspaceMutationPreview preview(
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceAction action,
Path targetRoot);
void apply(ProjectReference projectReference, AssetWorkspaceMutationPreview preview);
}
@@ -1,15 +0,0 @@
package p.studio.workspaces.assets;
import java.util.Objects;
public final class AssetWorkspaceMutationUpdatePlanner {
private AssetWorkspaceMutationUpdatePlanner() {
}
public static AssetWorkspaceMutationUpdateStrategy forSuccessfulAction(AssetWorkspaceAction action) {
return switch (Objects.requireNonNull(action, "action")) {
case INCLUDE_IN_BUILD, EXCLUDE_FROM_BUILD -> AssetWorkspaceMutationUpdateStrategy.LOCAL_PATCH;
case REGISTER, RELOCATE, REMOVE -> AssetWorkspaceMutationUpdateStrategy.STRUCTURAL_SYNC;
};
}
}
@@ -1,6 +0,0 @@
package p.studio.workspaces.assets;
public enum AssetWorkspaceMutationUpdateStrategy {
LOCAL_PATCH,
STRUCTURAL_SYNC
}
@@ -1,187 +0,0 @@
package p.studio.workspaces.assets;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsNavigatorViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.nio.file.Path;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.Map;
import java.util.Objects;
final class AssetWorkspaceNavigatorControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final Path projectRoot;
private final StudioWorkspaceEventBus workspaceBus;
private final AssetWorkspaceInteractionPort interactions;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private final TextField searchField = new TextField();
private final FlowPane filterBar = new FlowPane();
private final Label navigatorStateLabel = new Label();
private final VBox navigatorContent = new VBox(8);
private final Map<AssetNavigatorFilter, ToggleButton> filterButtons = new EnumMap<>(AssetNavigatorFilter.class);
private AssetWorkspaceNavigatorViewState viewState;
private EnumSet<AssetNavigatorFilter> activeFilters = EnumSet.noneOf(AssetNavigatorFilter.class);
private String projectionSignature = "";
AssetWorkspaceNavigatorControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.projectRoot = this.projectReference.rootPath();
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.interactions = Objects.requireNonNull(interactions, "interactions");
getStyleClass().add("assets-workspace-pane");
setSpacing(8);
final Label navigatorTitle = new Label();
navigatorTitle.textProperty().bind(Container.i18n().bind(I18n.ASSETS_NAVIGATOR_TITLE));
navigatorTitle.getStyleClass().add("assets-workspace-pane-title");
searchField.setPromptText(Container.i18n().text(I18n.ASSETS_SEARCH_PROMPT));
searchField.getStyleClass().add("assets-workspace-search");
searchField.textProperty().addListener((ignored, oldValue, newValue) -> {
final String current = newValue == null ? "" : newValue;
if (!Objects.equals(oldValue, current)) {
interactions.updateSearchQuery(current);
}
});
configureFilterBar();
navigatorStateLabel.getStyleClass().add("assets-workspace-pane-body");
navigatorContent.getStyleClass().add("assets-workspace-navigator-content");
final ScrollPane navigatorScroll = new ScrollPane(navigatorContent);
navigatorScroll.setFitToWidth(true);
navigatorScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
navigatorScroll.getStyleClass().add("assets-workspace-navigator-scroll");
getChildren().addAll(navigatorTitle, searchField, filterBar, navigatorStateLabel, navigatorScroll);
VBox.setVgrow(navigatorScroll, Priority.ALWAYS);
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsNavigatorViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
applyViewState(event.viewState());
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void applyViewState(AssetWorkspaceNavigatorViewState viewState) {
this.viewState = viewState;
render();
}
private void configureFilterBar() {
filterBar.setHgap(6);
filterBar.setVgap(6);
filterBar.setPadding(new Insets(4, 0, 4, 0));
filterBar.getStyleClass().add("assets-workspace-filter-bar");
addFilterButton(AssetNavigatorFilter.REGISTERED, I18n.ASSETS_FILTER_REGISTERED);
addFilterButton(AssetNavigatorFilter.UNREGISTERED, I18n.ASSETS_FILTER_UNREGISTERED);
addFilterButton(AssetNavigatorFilter.DIAGNOSTICS, I18n.ASSETS_FILTER_DIAGNOSTICS);
addFilterButton(AssetNavigatorFilter.PRELOAD, I18n.ASSETS_FILTER_PRELOAD);
}
private void addFilterButton(AssetNavigatorFilter filter, I18n i18n) {
final ToggleButton button = new ToggleButton();
button.textProperty().bind(Container.i18n().bind(i18n));
button.getStyleClass().addAll("studio-button", "studio-button-secondary", "studio-button-pill", "studio-button-toggle");
button.selectedProperty().addListener((ignored, oldValue, selected) -> {
if (selected) {
activeFilters.add(filter);
} else {
activeFilters.remove(filter);
}
interactions.updateActiveFilters(activeFilters.isEmpty() ? EnumSet.noneOf(AssetNavigatorFilter.class) : EnumSet.copyOf(activeFilters));
});
filterButtons.put(filter, button);
filterBar.getChildren().add(button);
}
private void render() {
if (viewState == null) {
navigatorStateLabel.setText(Container.i18n().text(I18n.ASSETS_STATE_LOADING));
navigatorContent.getChildren().setAll(createMessage(Container.i18n().text(I18n.ASSETS_STATE_LOADING)));
return;
}
navigatorStateLabel.setText(viewState.message());
if (!viewState.hasProjection()) {
projectionSignature = "";
navigatorContent.getChildren().setAll(createMessage(viewState.message()));
return;
}
final String nextSignature = projectionSignature(viewState.projection());
if (Objects.equals(projectionSignature, nextSignature)) {
return;
}
projectionSignature = nextSignature;
navigatorContent.getChildren().clear();
for (AssetNavigatorGroup group : viewState.projection().groups()) {
final VBox groupBox = new VBox(6);
groupBox.getStyleClass().add("assets-workspace-group");
final Label groupLabel = new Label(group.label());
groupLabel.getStyleClass().add("assets-workspace-group-label");
groupBox.getChildren().add(groupLabel);
for (AssetWorkspaceAssetSummary asset : group.assets()) {
groupBox.getChildren().add(new AssetWorkspaceNavigatorRowControl(
projectReference,
workspaceBus,
interactions,
asset,
asset.selectionKey().equals(viewState.workspaceState().selectedKey())));
}
navigatorContent.getChildren().add(groupBox);
}
}
private Node createMessage(String text) {
final Label label = new Label(text);
label.getStyleClass().add("assets-workspace-empty-state");
label.setWrapText(true);
return label;
}
private String projectionSignature(AssetNavigatorProjection projection) {
final StringBuilder signature = new StringBuilder();
for (AssetNavigatorGroup group : projection.groups()) {
signature.append(group.label()).append('|');
for (AssetWorkspaceAssetSummary asset : group.assets()) {
signature.append(asset.selectionKey().stableKey()).append(',');
}
signature.append(';');
}
return signature.toString();
}
}
@@ -1,153 +0,0 @@
package p.studio.workspaces.assets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsAssetSummaryPatchedEvent;
import p.studio.events.StudioAssetsWorkspaceSelectionChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.nio.file.Path;
import java.util.Objects;
final class AssetWorkspaceNavigatorRowControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final Path projectRoot;
private final StudioWorkspaceEventBus workspaceBus;
private final AssetWorkspaceInteractionPort interactions;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceAssetSummary summary;
private boolean selected;
AssetWorkspaceNavigatorRowControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions,
AssetWorkspaceAssetSummary summary,
boolean selected) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.projectRoot = this.projectReference.rootPath();
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.interactions = Objects.requireNonNull(interactions, "interactions");
this.summary = Objects.requireNonNull(summary, "summary");
this.selected = selected;
render();
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsWorkspaceSelectionChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
updateSelection(event.selectionKey().equals(summary.selectionKey()));
}
}));
subscriptions.add(workspaceBus.subscribe(StudioAssetsAssetSummaryPatchedEvent.class, event -> {
if (projectReference.equals(event.project())
&& summary.selectionKey().equals(event.summary().selectionKey())) {
summary = event.summary();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void updateSelection(boolean selected) {
if (this.selected == selected) {
return;
}
this.selected = selected;
renderSelection();
}
private void render() {
getChildren().clear();
getStyleClass().setAll("assets-workspace-asset-row", assetRowToneClass(summary.assetFamily()));
renderSelection();
final HBox topLine = new HBox(8);
topLine.setAlignment(Pos.CENTER_LEFT);
final Label name = new Label(summary.assetName());
name.getStyleClass().addAll("assets-workspace-asset-name", assetNameToneClass(summary.assetFamily()));
final Region spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
final HBox badges = new HBox(6);
badges.setAlignment(Pos.CENTER_RIGHT);
badges.getStyleClass().add("assets-workspace-asset-badges");
populateBadges(badges);
topLine.getChildren().addAll(name, spacer, badges);
final Label path = new Label(AssetNavigatorProjectionBuilder.relativeRoot(summary, projectRoot));
path.getStyleClass().add("assets-workspace-asset-path");
getChildren().setAll(topLine, path);
setOnMouseClicked(event -> interactions.selectAsset(summary.selectionKey()));
}
private void renderSelection() {
getStyleClass().remove("assets-workspace-asset-row-selected");
if (selected) {
getStyleClass().add("assets-workspace-asset-row-selected");
}
}
private void populateBadges(HBox badges) {
if (summary.state() == AssetWorkspaceAssetState.UNREGISTERED) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_UNREGISTERED), "assets-workspace-badge-orphan"));
} else if (summary.buildParticipation() == AssetWorkspaceBuildParticipation.INCLUDED) {
badges.getChildren().add(createBadge(buildParticipationLabel(summary.buildParticipation()), "assets-workspace-badge-preload"));
if (summary.preload()) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_PRELOAD), "assets-workspace-badge-preload"));
}
} else {
badges.getChildren().add(createBadge(buildParticipationLabel(summary.buildParticipation()), "assets-workspace-badge-diagnostics"));
}
if (summary.hasDiagnostics()) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_DIAGNOSTICS), "assets-workspace-badge-diagnostics"));
}
}
private Label createBadge(String text, String styleClass) {
final Label badge = new Label(text);
badge.getStyleClass().addAll("assets-workspace-badge", styleClass);
return badge;
}
private String buildParticipationLabel(AssetWorkspaceBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_INCLUDED);
case EXCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_EXCLUDED);
};
}
private String assetRowToneClass(String assetFamily) {
return switch (assetFamily == null ? "" : assetFamily.toLowerCase()) {
case "image_bank" -> "assets-workspace-asset-row-image";
case "palette_bank" -> "assets-workspace-asset-row-palette";
case "sound_bank" -> "assets-workspace-asset-row-sound";
default -> "assets-workspace-asset-row-generic";
};
}
private String assetNameToneClass(String assetFamily) {
return switch (assetFamily == null ? "" : assetFamily.toLowerCase()) {
case "image_bank" -> "assets-workspace-asset-name-image";
case "palette_bank" -> "assets-workspace-asset-name-palette";
case "sound_bank" -> "assets-workspace-asset-name-sound";
default -> "assets-workspace-asset-name-generic";
};
}
}
@@ -1,87 +0,0 @@
package p.studio.workspaces.assets;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.Objects;
final class AssetWorkspaceRuntimeContractControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final AssetWorkspaceInteractionPort interactions;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceDetailsViewState viewState;
AssetWorkspaceRuntimeContractControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.interactions = Objects.requireNonNull(interactions, "interactions");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
viewState = event.viewState();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void render() {
if (viewState == null || viewState.workspaceState().selectedAsset().isEmpty()) {
getChildren().clear();
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.LOADING) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_RUNTIME_CONTRACT),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING))));
return;
}
if (viewState.detailsStatus() == AssetWorkspaceDetailsStatus.ERROR || viewState.selectedAssetDetails() == null) {
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_RUNTIME_CONTRACT),
AssetWorkspaceDetailsUiSupport.createSectionMessage(Objects.requireNonNullElse(viewState.detailsErrorMessage(), Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY)))));
return;
}
final AssetWorkspaceAssetDetails details = viewState.selectedAssetDetails();
final VBox content = new VBox(8);
content.getChildren().addAll(
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_PRELOAD), createPreloadToggle(details)),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_FORMAT), details.outputFormat()),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_CODEC), details.outputCodec()));
getChildren().setAll(AssetWorkspaceDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_RUNTIME_CONTRACT), content));
}
private CheckBox createPreloadToggle(AssetWorkspaceAssetDetails details) {
final boolean currentValue = details.summary().preload();
final CheckBox checkBox = new CheckBox(AssetWorkspaceDetailsUiSupport.yesNo(currentValue));
checkBox.setSelected(currentValue);
checkBox.setFocusTraversable(false);
checkBox.getStyleClass().add("assets-details-readonly-check");
checkBox.selectedProperty().addListener((ignored, previous, selected) -> checkBox.setText(AssetWorkspaceDetailsUiSupport.yesNo(selected)));
checkBox.setOnAction(event -> interactions.updatePreload(details, checkBox.isSelected(), checkBox));
return checkBox;
}
}
@@ -1,32 +0,0 @@
package p.studio.workspaces.assets;
import java.nio.file.Path;
import java.util.Objects;
public sealed interface AssetWorkspaceSelectionKey permits AssetWorkspaceSelectionKey.ManagedAsset, AssetWorkspaceSelectionKey.OrphanAsset {
String stableKey();
record ManagedAsset(int assetId) implements AssetWorkspaceSelectionKey {
public ManagedAsset {
if (assetId <= 0) {
throw new IllegalArgumentException("assetId must be positive");
}
}
@Override
public String stableKey() {
return "managed:" + assetId;
}
}
record OrphanAsset(Path assetRoot) implements AssetWorkspaceSelectionKey {
public OrphanAsset {
assetRoot = Objects.requireNonNull(assetRoot, "assetRoot").toAbsolutePath().normalize();
}
@Override
public String stableKey() {
return "orphan:" + assetRoot;
}
}
}
@@ -1,9 +0,0 @@
package p.studio.workspaces.assets;
import p.studio.projects.ProjectReference;
public interface AssetWorkspaceService {
AssetWorkspaceSnapshot loadWorkspace(ProjectReference projectReference);
AssetWorkspaceAssetDetails loadAssetDetails(ProjectReference projectReference, AssetWorkspaceSelectionKey selectionKey);
}
@@ -1,10 +0,0 @@
package p.studio.workspaces.assets;
import java.util.List;
import java.util.Objects;
public record AssetWorkspaceSnapshot(List<AssetWorkspaceAssetSummary> assets) {
public AssetWorkspaceSnapshot {
assets = List.copyOf(Objects.requireNonNull(assets, "assets"));
}
}
@@ -1,5 +1,9 @@
package p.studio.workspaces.assets;
import p.packer.assets.AssetReference;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.messages.AssetWorkspaceStatus;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@@ -8,7 +12,7 @@ import java.util.Optional;
public record AssetWorkspaceState(
AssetWorkspaceStatus status,
List<AssetWorkspaceAssetSummary> assets,
AssetWorkspaceSelectionKey selectedKey,
AssetReference selectedAssetReference,
String errorMessage) {
public AssetWorkspaceState {
@@ -20,12 +24,12 @@ public record AssetWorkspaceState(
if (previous == null) {
return new AssetWorkspaceState(AssetWorkspaceStatus.LOADING, List.of(), null, null);
}
return new AssetWorkspaceState(AssetWorkspaceStatus.LOADING, previous.assets(), previous.selectedKey(), null);
return new AssetWorkspaceState(AssetWorkspaceStatus.LOADING, previous.assets(), previous.selectedAssetReference(), null);
}
public static AssetWorkspaceState ready(List<AssetWorkspaceAssetSummary> assets, AssetWorkspaceSelectionKey preferredSelectionKey) {
public static AssetWorkspaceState ready(List<AssetWorkspaceAssetSummary> assets, AssetReference preferredAssetReference) {
final List<AssetWorkspaceAssetSummary> normalizedAssets = normalizeAssets(assets);
final AssetWorkspaceSelectionKey resolvedSelection = reconcileSelection(normalizedAssets, preferredSelectionKey);
final AssetReference resolvedSelection = reconcileSelection(normalizedAssets, preferredAssetReference);
final AssetWorkspaceStatus status = normalizedAssets.isEmpty() ? AssetWorkspaceStatus.EMPTY : AssetWorkspaceStatus.READY;
return new AssetWorkspaceState(status, normalizedAssets, resolvedSelection, null);
}
@@ -34,38 +38,38 @@ public record AssetWorkspaceState(
return new AssetWorkspaceState(
AssetWorkspaceStatus.ERROR,
previous == null ? List.of() : previous.assets(),
previous == null ? null : previous.selectedKey(),
previous == null ? null : previous.selectedAssetReference(),
Objects.requireNonNullElse(errorMessage, "Unknown asset workspace error"));
}
public Optional<AssetWorkspaceAssetSummary> selectedAsset() {
if (selectedKey == null) {
if (selectedAssetReference == null) {
return Optional.empty();
}
return assets.stream()
.filter(asset -> asset.selectionKey().equals(selectedKey))
.filter(asset -> asset.assetReference().equals(selectedAssetReference))
.findFirst();
}
public AssetWorkspaceState withSelection(AssetWorkspaceSelectionKey nextSelectionKey) {
final AssetWorkspaceSelectionKey resolvedSelection = reconcileSelection(assets, nextSelectionKey);
public AssetWorkspaceState withSelection(AssetReference nextAssetReference) {
final AssetReference resolvedSelection = reconcileSelection(assets, nextAssetReference);
return new AssetWorkspaceState(status, assets, resolvedSelection, errorMessage);
}
static AssetWorkspaceSelectionKey reconcileSelection(
static AssetReference reconcileSelection(
List<AssetWorkspaceAssetSummary> assets,
AssetWorkspaceSelectionKey preferredSelectionKey) {
AssetReference preferredAssetReference) {
if (assets.isEmpty()) {
return null;
}
if (preferredSelectionKey != null) {
if (preferredAssetReference != null) {
for (AssetWorkspaceAssetSummary asset : assets) {
if (asset.selectionKey().equals(preferredSelectionKey)) {
return preferredSelectionKey;
if (asset.assetReference().equals(preferredAssetReference)) {
return preferredAssetReference;
}
}
}
return assets.getFirst().selectionKey();
return assets.getFirst().assetReference();
}
private static List<AssetWorkspaceAssetSummary> normalizeAssets(List<AssetWorkspaceAssetSummary> assets) {
@@ -1,203 +0,0 @@
package p.studio.workspaces.assets;
import javafx.scene.Node;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.List;
import java.util.Objects;
final class AssetWorkspaceSummaryActionsControl extends HBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final AssetWorkspaceInteractionPort interactions;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceDetailsViewState viewState;
AssetWorkspaceSummaryActionsControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceInteractionPort interactions) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.interactions = Objects.requireNonNull(interactions, "interactions");
setSpacing(12);
getStyleClass().add("assets-details-summary-actions-row");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
if (projectReference.equals(event.project())) {
viewState = event.viewState();
render();
}
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void render() {
getChildren().clear();
if (viewState == null) {
return;
}
final AssetWorkspaceAssetSummary summary = viewState.workspaceState().selectedAsset().orElse(null);
if (summary == null) {
return;
}
final VBox summarySection = createSummarySection(summary);
final VBox actionsSection = createActionsSection(summary);
HBox.setHgrow(summarySection, Priority.ALWAYS);
HBox.setHgrow(actionsSection, Priority.NEVER);
summarySection.setMaxWidth(Double.MAX_VALUE);
summarySection.setMinWidth(0);
actionsSection.setPrefWidth(280);
actionsSection.setMinWidth(240);
actionsSection.setMaxWidth(320);
getChildren().setAll(summarySection, actionsSection);
}
private VBox createSummarySection(AssetWorkspaceAssetSummary summary) {
final VBox content = new VBox(8);
content.getChildren().addAll(
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_NAME), summary.assetName()),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_REGISTRATION), AssetWorkspaceDetailsUiSupport.registrationLabel(summary.state())),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_BUILD_PARTICIPATION), AssetWorkspaceDetailsUiSupport.buildParticipationLabel(summary.buildParticipation())),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_ASSET_ID), summary.assetId() == null ? "—" : String.valueOf(summary.assetId())),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_TYPE), summary.assetFamily()),
AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_LOCATION), AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, summary.assetRoot())));
return AssetWorkspaceDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_SUMMARY), content);
}
private VBox createActionsSection(AssetWorkspaceAssetSummary summary) {
final AssetWorkspaceActionSet actionSet = AssetWorkspaceActionSetBuilder.forAsset(summary);
final VBox content = new VBox(12);
for (AssetWorkspaceAction action : actionSet.primaryActions()) {
content.getChildren().add(createActionButton(action, false));
}
for (AssetWorkspaceAction action : actionSet.sensitiveActions()) {
content.getChildren().add(createActionButton(action, true));
}
if (viewState.stagedMutationPreview() != null
&& viewState.stagedMutationPreview().asset().selectionKey().equals(summary.selectionKey())) {
content.getChildren().add(createStagedMutationPanel(viewState.stagedMutationPreview()));
}
return AssetWorkspaceDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_ACTIONS), content);
}
private Button createActionButton(AssetWorkspaceAction action, boolean sensitive) {
final Button button = new Button(AssetWorkspaceDetailsUiSupport.actionLabel(action));
button.getStyleClass().addAll("studio-button", AssetWorkspaceDetailsUiSupport.actionButtonVariant(action, sensitive));
button.setMaxWidth(Double.MAX_VALUE);
button.setOnAction(event -> interactions.requestMutationPreview(action));
return button;
}
private Node createStagedMutationPanel(AssetWorkspaceMutationPreview preview) {
final VBox panel = new VBox(10);
panel.getStyleClass().add("assets-mutation-panel");
final Label title = new Label(Container.i18n().format(I18n.ASSETS_MUTATION_PREVIEW_TITLE, AssetWorkspaceDetailsUiSupport.actionLabel(preview.action())));
title.getStyleClass().add("assets-mutation-panel-title");
panel.getChildren().add(title);
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_AFFECTED_ASSET),
createAffectedAssetContent(preview)));
final AssetWorkspaceMutationImpactViewModel impacts = AssetWorkspaceMutationImpactViewModel.from(preview);
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_REGISTRY_IMPACT),
createMutationChangesContent(impacts.registryChanges(), Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_REGISTRY_IMPACT))));
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_WORKSPACE_IMPACT),
createMutationChangesContent(impacts.workspaceChanges(), Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_WORKSPACE_IMPACT))));
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_BLOCKERS),
createMutationMessages(preview.blockers(), "assets-mutation-message-blocker", Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_BLOCKERS))));
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_WARNINGS),
createMutationMessages(preview.warnings(), "assets-mutation-message-warning", Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_WARNINGS))));
panel.getChildren().add(createMutationSection(
Container.i18n().text(I18n.ASSETS_MUTATION_SECTION_SAFE_FIXES),
createMutationMessages(preview.safeFixes(), "assets-mutation-message-safe-fix", Container.i18n().text(I18n.ASSETS_MUTATION_EMPTY_SAFE_FIXES))));
final HBox actions = new HBox(8);
final Button cancel = new Button(Container.i18n().text(I18n.ASSETS_MUTATION_CANCEL));
cancel.getStyleClass().addAll("studio-button", "studio-button-cancel");
cancel.setOnAction(event -> interactions.cancelStagedMutationPreview());
final Button apply = new Button(Container.i18n().text(I18n.ASSETS_MUTATION_APPLY));
apply.getStyleClass().addAll("studio-button", "studio-button-primary");
apply.setDisable(!preview.canApply());
apply.setOnAction(event -> interactions.applyStagedMutation(preview));
actions.getChildren().addAll(cancel, apply);
panel.getChildren().add(actions);
return panel;
}
private Node createMutationSection(String title, Node content) {
final VBox section = new VBox(6);
final Label label = new Label(title);
label.getStyleClass().add("assets-mutation-section-title");
section.getChildren().addAll(label, content);
return section;
}
private Node createAffectedAssetContent(AssetWorkspaceMutationPreview preview) {
final VBox box = new VBox(6);
box.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_NAME), preview.asset().assetName()));
box.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_LOCATION),
AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, preview.asset().assetRoot())));
if (preview.targetAssetRoot() != null) {
box.getChildren().add(AssetWorkspaceDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_TARGET_LOCATION),
AssetWorkspaceDetailsUiSupport.projectRelativePath(projectReference, preview.targetAssetRoot())));
}
return box;
}
private Node createMutationChangesContent(List<AssetWorkspaceMutationChange> changes, String emptyText) {
if (changes.isEmpty()) {
return AssetWorkspaceDetailsUiSupport.createSectionMessage(emptyText);
}
final VBox box = new VBox(6);
for (AssetWorkspaceMutationChange change : changes) {
final Label label = new Label(change.verb() + " · " + change.target());
label.getStyleClass().add("assets-mutation-change");
box.getChildren().add(label);
}
return box;
}
private Node createMutationMessages(List<String> messages, String styleClass, String emptyText) {
if (messages.isEmpty()) {
return AssetWorkspaceDetailsUiSupport.createSectionMessage(emptyText);
}
final VBox box = new VBox(6);
for (String message : messages) {
final Label label = new Label(message);
label.setWrapText(true);
label.getStyleClass().add(styleClass);
box.getChildren().add(label);
}
return box;
}
}
@@ -1,305 +0,0 @@
package p.studio.workspaces.assets;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.projects.ProjectReference;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public final class FileSystemAssetWorkspaceMutationService implements AssetWorkspaceMutationService {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String PROMETEU_DIR = ".prometeu";
@Override
public AssetWorkspaceMutationPreview preview(
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceAction action,
Path targetRoot) {
Objects.requireNonNull(projectReference, "projectReference");
Objects.requireNonNull(asset, "asset");
Objects.requireNonNull(action, "action");
final List<String> blockers = new ArrayList<>();
final List<String> warnings = new ArrayList<>();
final List<String> safeFixes = new ArrayList<>();
final List<AssetWorkspaceMutationChange> changes = new ArrayList<>();
final Path assetsRoot = projectReference.rootPath().resolve("assets");
final String relativeRoot = relativeAssetRoot(asset.assetRoot(), assetsRoot);
Path targetAssetRoot = null;
if (!Files.exists(asset.assetRoot())) {
blockers.add("Asset root does not exist: " + asset.assetRoot());
}
switch (action) {
case REGISTER -> {
if (asset.state() == AssetWorkspaceAssetState.REGISTERED) {
blockers.add("Asset is already registered.");
} else {
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.REGISTRY,
"ADD",
relativeRoot));
if (asset.hasDiagnostics()) {
warnings.add("Asset currently reports diagnostics and will still be registered.");
}
}
}
case INCLUDE_IN_BUILD -> {
if (asset.state() != AssetWorkspaceAssetState.REGISTERED) {
blockers.add("Only registered assets can be included in builds.");
} else if (asset.buildParticipation() == AssetWorkspaceBuildParticipation.INCLUDED) {
blockers.add("Asset is already included in builds.");
} else {
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.REGISTRY,
"UPDATE",
relativeRoot));
warnings.add("The asset will remain registered and return to the build set.");
}
}
case EXCLUDE_FROM_BUILD -> {
if (asset.state() != AssetWorkspaceAssetState.REGISTERED) {
blockers.add("Only registered assets can be excluded from builds.");
} else if (asset.buildParticipation() == AssetWorkspaceBuildParticipation.EXCLUDED) {
blockers.add("Asset is already excluded from builds.");
} else {
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.REGISTRY,
"UPDATE",
relativeRoot));
warnings.add("The asset will remain registered but leave the build set.");
}
}
case RELOCATE -> {
targetAssetRoot = targetRoot == null
? relocationTarget(asset, assetsRoot)
: targetRoot.toAbsolutePath().normalize();
final AssetRootValidationResult validation = AssetRelocationTargetValidator.validate(
projectReference,
asset.assetRoot(),
targetAssetRoot);
if (!validation.valid()) {
blockers.add(validation.message());
} else {
targetAssetRoot = validation.assetRoot();
final String targetRelativeRoot = validation.normalizedRelativeRoot();
if (asset.state() == AssetWorkspaceAssetState.REGISTERED) {
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.REGISTRY,
"UPDATE",
relativeRoot + " -> " + targetRelativeRoot));
}
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.WORKSPACE,
"MOVE",
relativeRoot + " -> " + targetRelativeRoot));
warnings.add("Relocation preserves asset identity, but it changes the root path seen by the workspace.");
}
}
case REMOVE -> {
if (asset.state() == AssetWorkspaceAssetState.REGISTERED) {
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.REGISTRY,
"REMOVE",
relativeRoot));
}
changes.add(new AssetWorkspaceMutationChange(
AssetWorkspaceMutationChangeScope.WORKSPACE,
"DELETE",
relativeRoot));
warnings.add("Physical files inside the asset root will be deleted.");
}
}
final boolean highRisk = action == AssetWorkspaceAction.REMOVE || action == AssetWorkspaceAction.RELOCATE;
return new AssetWorkspaceMutationPreview(action, asset, blockers, warnings, safeFixes, changes, highRisk, targetAssetRoot);
}
@Override
public void apply(ProjectReference projectReference, AssetWorkspaceMutationPreview preview) {
Objects.requireNonNull(projectReference, "projectReference");
Objects.requireNonNull(preview, "preview");
if (!preview.canApply()) {
throw new IllegalStateException("Cannot apply mutation preview with blockers");
}
final Path assetsRoot = projectReference.rootPath().resolve("assets");
final Registry registry = loadRegistry(assetsRoot);
final Path assetRoot = preview.asset().assetRoot();
switch (preview.action()) {
case REGISTER -> {
if (registryContainsRoot(registry, assetRoot, assetsRoot)) {
return;
}
final RegistryEntry entry = new RegistryEntry();
entry.assetId = registry.nextAssetId <= 0 ? 1 : registry.nextAssetId;
entry.assetUuid = UUID.randomUUID().toString();
entry.root = relativeAssetRoot(assetRoot, assetsRoot);
registry.assets.add(entry);
registry.assets.sort(Comparator.comparingInt(value -> value.assetId));
registry.nextAssetId = entry.assetId + 1;
writeRegistry(assetsRoot, registry);
}
case INCLUDE_IN_BUILD, EXCLUDE_FROM_BUILD -> {
final boolean includedInBuild = preview.action() == AssetWorkspaceAction.INCLUDE_IN_BUILD;
registry.assets.stream()
.filter(entry -> entry.root != null && assetsRoot.resolve(entry.root).toAbsolutePath().normalize().equals(assetRoot))
.findFirst()
.ifPresent(entry -> entry.includedInBuild = includedInBuild);
writeRegistry(assetsRoot, registry);
}
case RELOCATE -> {
final Path targetAssetRoot = requireTargetAssetRoot(preview);
if (preview.asset().state() == AssetWorkspaceAssetState.REGISTERED) {
registry.assets.stream()
.filter(entry -> entry.root != null && assetsRoot.resolve(entry.root).toAbsolutePath().normalize().equals(assetRoot))
.findFirst()
.ifPresent(entry -> entry.root = relativeAssetRoot(targetAssetRoot, assetsRoot));
writeRegistry(assetsRoot, registry);
}
moveAssetRoot(assetRoot, targetAssetRoot);
}
case REMOVE -> {
registry.assets.removeIf(entry -> entry.root != null && assetsRoot.resolve(entry.root).toAbsolutePath().normalize().equals(assetRoot));
writeRegistry(assetsRoot, registry);
deleteRecursively(assetRoot);
}
}
}
private Registry loadRegistry(Path assetsRoot) {
final Path registryPath = assetsRoot.resolve(PROMETEU_DIR).resolve("index.json");
if (!Files.isRegularFile(registryPath)) {
final Registry registry = new Registry();
registry.schemaVersion = 1;
registry.nextAssetId = 1;
registry.assets = new ArrayList<>();
return registry;
}
try {
final Registry registry = MAPPER.readValue(registryPath.toFile(), Registry.class);
if (registry.assets == null) {
registry.assets = new ArrayList<>();
}
if (registry.schemaVersion <= 0) {
registry.schemaVersion = 1;
}
if (registry.nextAssetId <= 0) {
registry.nextAssetId = registry.assets.stream().mapToInt(entry -> entry.assetId).max().orElse(0) + 1;
}
return registry;
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
private void writeRegistry(Path assetsRoot, Registry registry) {
try {
final Path registryDir = assetsRoot.resolve(PROMETEU_DIR);
Files.createDirectories(registryDir);
MAPPER.writerWithDefaultPrettyPrinter().writeValue(registryDir.resolve("index.json").toFile(), registry);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
private boolean registryContainsRoot(Registry registry, Path assetRoot, Path assetsRoot) {
return registry.assets.stream()
.filter(entry -> entry.root != null)
.map(entry -> assetsRoot.resolve(entry.root).toAbsolutePath().normalize())
.anyMatch(assetRoot::equals);
}
private String relativeAssetRoot(Path assetRoot, Path assetsRoot) {
return assetsRoot.relativize(assetRoot.toAbsolutePath().normalize()).toString().replace('\\', '/');
}
private Path relocationTarget(AssetWorkspaceAssetSummary asset, Path assetsRoot) {
final Path assetRoot = asset.assetRoot();
final Path siblingParent = assetRoot.getParent() == null ? assetsRoot : assetRoot.getParent();
return nextAvailableSibling(siblingParent, assetRoot.getFileName().toString() + "-relocated");
}
private Path nextAvailableSibling(Path parent, String baseName) {
final Path normalizedParent = parent.toAbsolutePath().normalize();
Path candidate = normalizedParent.resolve(baseName);
int index = 2;
while (Files.exists(candidate)) {
candidate = normalizedParent.resolve(baseName + "-" + index);
index += 1;
}
return candidate;
}
private Path requireTargetAssetRoot(AssetWorkspaceMutationPreview preview) {
if (preview.targetAssetRoot() == null) {
throw new IllegalStateException("Mutation preview does not define a target asset root");
}
return preview.targetAssetRoot();
}
private void moveAssetRoot(Path sourceRoot, Path targetRoot) {
if (sourceRoot.equals(targetRoot)) {
return;
}
try {
Files.createDirectories(Objects.requireNonNull(targetRoot, "targetRoot").getParent());
Files.move(sourceRoot, targetRoot);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
private void deleteRecursively(Path root) {
if (!Files.exists(root)) {
return;
}
try (Stream<Path> stream = Files.walk(root)) {
stream.sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
});
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static final class Registry {
@JsonProperty("schema_version")
public int schemaVersion;
@JsonProperty("next_asset_id")
public int nextAssetId;
@JsonProperty("assets")
public List<RegistryEntry> assets = new ArrayList<>();
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static final class RegistryEntry {
@JsonProperty("asset_id")
public int assetId;
@JsonProperty("asset_uuid")
public String assetUuid;
@JsonProperty("root")
public String root;
@JsonProperty("included_in_build")
public boolean includedInBuild = true;
}
}
@@ -1,204 +0,0 @@
package p.studio.workspaces.assets;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.studio.projects.ProjectReference;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Stream;
public final class FileSystemAssetWorkspaceService implements AssetWorkspaceService {
private static final ObjectMapper MAPPER = new ObjectMapper();
@Override
public AssetWorkspaceSnapshot loadWorkspace(ProjectReference projectReference) {
final Path projectRoot = Objects.requireNonNull(projectReference, "projectReference").rootPath();
final Path assetsRoot = projectRoot.resolve("assets");
if (!Files.isDirectory(assetsRoot)) {
return new AssetWorkspaceSnapshot(List.of());
}
final Map<Path, RegistryEntry> registryByRoot = readRegistry(assetsRoot);
try (Stream<Path> paths = Files.find(assetsRoot, Integer.MAX_VALUE, (path, attrs) ->
attrs.isRegularFile() && path.getFileName().toString().equals("asset.json"))) {
final List<AssetWorkspaceAssetSummary> assets = paths
.map(assetManifestPath -> buildAssetSummary(assetManifestPath, registryByRoot))
.sorted(Comparator
.comparing((AssetWorkspaceAssetSummary asset) -> asset.assetRoot().toString(), String.CASE_INSENSITIVE_ORDER)
.thenComparing(AssetWorkspaceAssetSummary::assetName, String.CASE_INSENSITIVE_ORDER))
.toList();
return new AssetWorkspaceSnapshot(assets);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
@Override
public AssetWorkspaceAssetDetails loadAssetDetails(ProjectReference projectReference, AssetWorkspaceSelectionKey selectionKey) {
final Path projectRoot = Objects.requireNonNull(projectReference, "projectReference").rootPath();
final Path assetsRoot = projectRoot.resolve("assets");
final Map<Path, RegistryEntry> registryByRoot = readRegistry(assetsRoot);
final Path assetRoot = resolveAssetRoot(selectionKey, assetsRoot, registryByRoot);
final Path assetManifestPath = assetRoot.resolve("asset.json");
try {
final JsonNode root = MAPPER.readTree(assetManifestPath.toFile());
final AssetWorkspaceAssetSummary summary = buildAssetSummary(assetManifestPath, registryByRoot);
final String outputFormat = readText(root.path("output").path("format"), "unknown");
final String outputCodec = readText(root.path("output").path("codec"), "unknown");
final Map<String, List<Path>> inputsByRole = readInputs(root.path("inputs"), assetRoot);
return new AssetWorkspaceAssetDetails(summary, outputFormat, outputCodec, inputsByRole, List.of());
} catch (IOException ioException) {
final AssetWorkspaceAssetSummary summary = buildAssetSummary(assetManifestPath, registryByRoot);
return new AssetWorkspaceAssetDetails(
summary,
"unknown",
"unknown",
Map.of(),
List.of(new AssetWorkspaceDiagnostic(
AssetWorkspaceDiagnosticSeverity.BLOCKER,
"Unable to read asset.json for the selected asset.")));
}
}
private AssetWorkspaceAssetSummary buildAssetSummary(Path assetManifestPath, Map<Path, RegistryEntry> registryByRoot) {
final Path assetRoot = assetManifestPath.getParent().toAbsolutePath().normalize();
try {
final AssetManifest manifest = MAPPER.readValue(assetManifestPath.toFile(), AssetManifest.class);
final RegistryEntry registryEntry = registryByRoot.get(assetRoot);
final Integer assetId = registryEntry == null ? null : registryEntry.assetId();
final AssetWorkspaceAssetState state = assetId == null
? AssetWorkspaceAssetState.UNREGISTERED
: AssetWorkspaceAssetState.REGISTERED;
final AssetWorkspaceSelectionKey selectionKey = assetId == null
? new AssetWorkspaceSelectionKey.OrphanAsset(assetRoot)
: new AssetWorkspaceSelectionKey.ManagedAsset(assetId);
final String assetName = Optional.ofNullable(manifest.name())
.filter(name -> !name.isBlank())
.orElse(assetRoot.getFileName().toString());
final String assetFamily = Optional.ofNullable(manifest.type())
.filter(type -> !type.isBlank())
.orElse("unknown");
final boolean preload = manifest.preload() != null && Boolean.TRUE.equals(manifest.preload().enabled());
return new AssetWorkspaceAssetSummary(
selectionKey,
assetName,
state,
state == AssetWorkspaceAssetState.REGISTERED
? (registryEntry.includedInBuild() ? AssetWorkspaceBuildParticipation.INCLUDED : AssetWorkspaceBuildParticipation.EXCLUDED)
: AssetWorkspaceBuildParticipation.EXCLUDED,
assetId,
assetFamily,
assetRoot,
preload,
false);
} catch (IOException ioException) {
final AssetWorkspaceSelectionKey selectionKey = new AssetWorkspaceSelectionKey.OrphanAsset(assetRoot);
return new AssetWorkspaceAssetSummary(
selectionKey,
assetRoot.getFileName().toString(),
AssetWorkspaceAssetState.UNREGISTERED,
AssetWorkspaceBuildParticipation.EXCLUDED,
null,
"unknown",
assetRoot,
false,
true);
}
}
private Map<Path, RegistryEntry> readRegistry(Path assetsRoot) {
final Path registryPath = assetsRoot.resolve(".prometeu").resolve("index.json");
if (!Files.isRegularFile(registryPath)) {
return Map.of();
}
try {
final Registry registry = MAPPER.readValue(registryPath.toFile(), Registry.class);
if (registry.assets() == null || registry.assets().isEmpty()) {
return Map.of();
}
final Map<Path, RegistryEntry> registryByRoot = new HashMap<>();
for (RegistryEntry entry : registry.assets()) {
if (entry == null || entry.root() == null || entry.root().isBlank() || entry.assetId() == null) {
continue;
}
registryByRoot.put(assetsRoot.resolve(entry.root()).toAbsolutePath().normalize(), entry);
}
return Map.copyOf(registryByRoot);
} catch (IOException ioException) {
throw new UncheckedIOException(ioException);
}
}
private Path resolveAssetRoot(
AssetWorkspaceSelectionKey selectionKey,
Path assetsRoot,
Map<Path, RegistryEntry> registryByRoot) {
return switch (selectionKey) {
case AssetWorkspaceSelectionKey.ManagedAsset managedAsset -> registryByRoot.entrySet().stream()
.filter(entry -> managedAsset.assetId() == entry.getValue().assetId())
.map(Map.Entry::getKey)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("managed asset root not found for assetId " + managedAsset.assetId()));
case AssetWorkspaceSelectionKey.OrphanAsset orphanAsset -> orphanAsset.assetRoot();
};
}
private Map<String, List<Path>> readInputs(JsonNode inputsNode, Path assetRoot) {
if (inputsNode == null || !inputsNode.isObject()) {
return Map.of();
}
final Map<String, List<Path>> result = new LinkedHashMap<>();
final Iterator<Map.Entry<String, JsonNode>> fields = inputsNode.fields();
while (fields.hasNext()) {
final Map.Entry<String, JsonNode> entry = fields.next();
if (!entry.getValue().isArray()) {
continue;
}
final List<Path> resolvedInputs = new ArrayList<>();
for (JsonNode inputNode : entry.getValue()) {
if (!inputNode.isTextual()) {
continue;
}
resolvedInputs.add(assetRoot.resolve(inputNode.asText()).toAbsolutePath().normalize());
}
result.put(entry.getKey(), List.copyOf(resolvedInputs));
}
return Map.copyOf(result);
}
private String readText(JsonNode node, String fallback) {
if (node == null || !node.isTextual()) {
return fallback;
}
final String text = node.asText();
return text == null || text.isBlank() ? fallback : text;
}
@JsonIgnoreProperties(ignoreUnknown = true)
private record AssetManifest(String name, String type, Preload preload) {
}
@JsonIgnoreProperties(ignoreUnknown = true)
private record Preload(Boolean enabled) {
}
@JsonIgnoreProperties(ignoreUnknown = true)
private record Registry(List<RegistryEntry> assets) {
}
@JsonIgnoreProperties(ignoreUnknown = true)
private record RegistryEntry(Integer assetId, String root, boolean includedInBuild) {
private RegistryEntry(
@com.fasterxml.jackson.annotation.JsonProperty("asset_id") Integer assetId,
@com.fasterxml.jackson.annotation.JsonProperty("root") String root,
@com.fasterxml.jackson.annotation.JsonProperty("included_in_build") Boolean includedInBuild) {
this(assetId, root, includedInBuild == null || includedInBuild);
}
}
}
@@ -1,84 +0,0 @@
package p.studio.workspaces.assets;
import com.fasterxml.jackson.databind.ObjectMapper;
import p.packer.api.PackerProjectContext;
import p.packer.api.workspace.InitWorkspaceRequest;
import p.packer.foundation.PackerRegistryState;
import p.packer.foundation.PackerWorkspaceFoundation;
import p.studio.projects.ProjectReference;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public final class PackerBackedAssetCreationService implements AssetCreationService {
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final String ASSET_MANIFEST = "asset.json";
private final PackerWorkspaceFoundation workspaceFoundation;
public PackerBackedAssetCreationService() {
this(new PackerWorkspaceFoundation());
}
PackerBackedAssetCreationService(PackerWorkspaceFoundation workspaceFoundation) {
this.workspaceFoundation = Objects.requireNonNull(workspaceFoundation, "workspaceFoundation");
}
@Override
public AssetCreationResult create(ProjectReference projectReference, AssetCreationRequest request) {
final ProjectReference reference = Objects.requireNonNull(projectReference, "projectReference");
final AssetCreationRequest creation = Objects.requireNonNull(request, "request");
final PackerProjectContext project = new PackerProjectContext(reference.name(), reference.rootPath());
workspaceFoundation.initWorkspace(new InitWorkspaceRequest(project));
final AssetRootValidationResult rootValidation = AssetRootValidator.validate(reference, creation.relativeRoot());
if (!rootValidation.valid()) {
throw new IllegalArgumentException(rootValidation.message());
}
if (!AssetCreationCatalog.supports(creation.assetType(), creation.outputFormat(), creation.outputCodec())) {
throw new IllegalArgumentException("Selected asset type, output format, and codec combination is not supported.");
}
final Path assetRoot = rootValidation.assetRoot();
final Path manifestPath = assetRoot.resolve(ASSET_MANIFEST);
final PackerRegistryState registry = workspaceFoundation.loadRegistry(project);
if (workspaceFoundation.lookup().findByRoot(project, registry, assetRoot).isPresent()) {
throw new IllegalArgumentException("Asset root is already registered in the project: " + rootValidation.normalizedRelativeRoot());
}
if (Files.isRegularFile(manifestPath)) {
throw new IllegalArgumentException("asset.json already exists at: " + rootValidation.normalizedRelativeRoot());
}
try {
Files.createDirectories(assetRoot);
MAPPER.writerWithDefaultPrettyPrinter().writeValue(manifestPath.toFile(), manifestDocument(creation));
} catch (IOException exception) {
throw new IllegalStateException("Unable to create asset files: " + exception.getMessage(), exception);
}
final var entry = workspaceFoundation.allocateIdentity(project, registry, assetRoot);
workspaceFoundation.saveRegistry(project, workspaceFoundation.appendAllocatedEntry(registry, entry));
return new AssetCreationResult(new AssetWorkspaceSelectionKey.ManagedAsset(entry.assetId()), assetRoot);
}
private Map<String, Object> manifestDocument(AssetCreationRequest request) {
final Map<String, Object> root = new LinkedHashMap<>();
root.put("schema_version", 1);
root.put("name", request.assetName());
root.put("type", request.assetType());
root.put("inputs", Map.of());
final Map<String, Object> output = new LinkedHashMap<>();
output.put("format", request.outputFormat());
output.put("codec", request.outputCodec());
root.put("output", output);
final Map<String, Object> preload = new LinkedHashMap<>();
preload.put("enabled", request.preloadEnabled());
root.put("preload", preload);
return root;
}
}
@@ -1,199 +0,0 @@
package p.studio.workspaces.assets;
import p.packer.api.PackerOperationClass;
import p.packer.api.PackerProjectContext;
import p.packer.api.events.PackerEvent;
import p.packer.api.events.PackerEventKind;
import p.packer.api.mutations.PackerMutationPreview;
import p.packer.api.mutations.PackerMutationRequest;
import p.packer.api.mutations.PackerMutationType;
import p.packer.api.mutations.PackerProposedAction;
import p.packer.declarations.PackerAssetDetailsService;
import p.packer.foundation.PackerWorkspaceFoundation;
import p.packer.mutations.FileSystemPackerMutationService;
import p.packer.mutations.PackerProjectWriteCoordinator;
import p.studio.events.StudioAssetsMutationAppliedEvent;
import p.studio.events.StudioAssetsMutationFailedEvent;
import p.studio.events.StudioAssetsMutationPreviewReadyEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
public final class PackerBackedAssetWorkspaceMutationService implements AssetWorkspaceMutationService {
private final FileSystemPackerMutationService packerMutationService;
private final StudioWorkspaceEventBus eventBus;
private final ConcurrentMap<AssetWorkspaceMutationPreview, OperationSession> previewSessions = new ConcurrentHashMap<>();
private final ConcurrentMap<String, OperationSession> operationSessions = new ConcurrentHashMap<>();
public PackerBackedAssetWorkspaceMutationService(StudioWorkspaceEventBus eventBus) {
this(eventBus, new PackerWorkspaceFoundation(), new PackerAssetDetailsService(), new PackerProjectWriteCoordinator());
}
PackerBackedAssetWorkspaceMutationService(
StudioWorkspaceEventBus eventBus,
PackerWorkspaceFoundation workspaceFoundation,
PackerAssetDetailsService detailsService,
PackerProjectWriteCoordinator writeCoordinator) {
this.eventBus = Objects.requireNonNull(eventBus, "eventBus");
this.packerMutationService = new FileSystemPackerMutationService(
Objects.requireNonNull(workspaceFoundation, "workspaceFoundation"),
Objects.requireNonNull(detailsService, "detailsService"),
Objects.requireNonNull(writeCoordinator, "writeCoordinator"),
this::forwardLifecycleEvent);
}
@Override
public AssetWorkspaceMutationPreview preview(
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceAction action,
Path targetRoot) {
Objects.requireNonNull(projectReference, "projectReference");
Objects.requireNonNull(asset, "asset");
final Path validatedTargetRoot = validateTargetRoot(projectReference, asset, action, targetRoot);
if (action == AssetWorkspaceAction.RELOCATE && targetRoot != null && validatedTargetRoot == null) {
final AssetRootValidationResult validation = AssetRelocationTargetValidator.validate(projectReference, asset.assetRoot(), targetRoot);
final AssetWorkspaceMutationPreview preview = new AssetWorkspaceMutationPreview(
action,
asset,
List.of(validation.message()),
List.of(),
List.of(),
List.of(),
true,
targetRoot);
eventBus.publish(new StudioAssetsMutationPreviewReadyEvent(projectReference, action, 1));
return preview;
}
final PackerMutationPreview packerPreview = packerMutationService.preview(
new PackerMutationRequest(
project(projectReference),
mutationType(action),
assetReference(projectReference, asset),
validatedTargetRoot));
final AssetWorkspaceMutationPreview studioPreview = mapPreview(action, asset, packerPreview);
final OperationSession session = new OperationSession(projectReference, action, studioPreview, packerPreview);
previewSessions.put(studioPreview, session);
operationSessions.put(packerPreview.operationId(), session);
eventBus.publish(new StudioAssetsMutationPreviewReadyEvent(projectReference, action, 1));
return studioPreview;
}
@Override
public void apply(ProjectReference projectReference, AssetWorkspaceMutationPreview preview) {
Objects.requireNonNull(projectReference, "projectReference");
final OperationSession session = previewSessions.get(Objects.requireNonNull(preview, "preview"));
if (session == null) {
throw new IllegalStateException("Mutation preview is not backed by a packer preview.");
}
try {
packerMutationService.apply(session.packerPreview());
} catch (RuntimeException exception) {
throw exception;
}
}
void forwardLifecycleEvent(PackerEvent event) {
final OperationSession session = operationSessions.get(Objects.requireNonNull(event, "event").operationId());
if (session == null) {
return;
}
if (event.kind() == PackerEventKind.ACTION_APPLIED) {
previewSessions.remove(session.studioPreview());
operationSessions.remove(event.operationId());
eventBus.publish(new StudioAssetsMutationAppliedEvent(
session.projectReference(),
session.action(),
affectedAssetCount(event)));
return;
}
if (event.kind() == PackerEventKind.ACTION_FAILED) {
eventBus.publish(new StudioAssetsMutationFailedEvent(
session.projectReference(),
session.action(),
event.summary()));
}
}
private AssetWorkspaceMutationPreview mapPreview(
AssetWorkspaceAction action,
AssetWorkspaceAssetSummary asset,
PackerMutationPreview preview) {
final List<AssetWorkspaceMutationChange> changes = preview.proposedActions().stream()
.map(this::mapChange)
.toList();
return new AssetWorkspaceMutationPreview(
action,
asset,
preview.blockers(),
preview.warnings(),
preview.safeFixes(),
changes,
preview.highRisk(),
preview.targetAssetRoot());
}
private AssetWorkspaceMutationChange mapChange(PackerProposedAction action) {
return new AssetWorkspaceMutationChange(
scope(action.operationClass()),
action.verb(),
action.target());
}
private AssetWorkspaceMutationChangeScope scope(PackerOperationClass operationClass) {
return switch (operationClass) {
case REGISTRY_MUTATION -> AssetWorkspaceMutationChangeScope.REGISTRY;
case WORKSPACE_MUTATION, READ_ONLY -> AssetWorkspaceMutationChangeScope.WORKSPACE;
};
}
private PackerMutationType mutationType(AssetWorkspaceAction action) {
return switch (Objects.requireNonNull(action, "action")) {
case REGISTER -> PackerMutationType.REGISTER_ASSET;
case INCLUDE_IN_BUILD -> PackerMutationType.INCLUDE_ASSET_IN_BUILD;
case EXCLUDE_FROM_BUILD -> PackerMutationType.EXCLUDE_ASSET_FROM_BUILD;
case RELOCATE -> PackerMutationType.RELOCATE_ASSET;
case REMOVE -> PackerMutationType.REMOVE_ASSET;
};
}
private PackerProjectContext project(ProjectReference projectReference) {
return new PackerProjectContext(projectReference.name(), projectReference.rootPath());
}
private String assetReference(ProjectReference projectReference, AssetWorkspaceAssetSummary asset) {
if (asset.assetId() != null) {
return Integer.toString(asset.assetId());
}
final Path assetsRoot = projectReference.rootPath().resolve("assets").toAbsolutePath().normalize();
return assetsRoot.relativize(asset.assetRoot().toAbsolutePath().normalize()).toString().replace('\\', '/');
}
private int affectedAssetCount(PackerEvent event) {
return event.affectedAssets().isEmpty() ? 1 : event.affectedAssets().size();
}
private Path validateTargetRoot(
ProjectReference projectReference,
AssetWorkspaceAssetSummary asset,
AssetWorkspaceAction action,
Path targetRoot) {
if (targetRoot == null || action != AssetWorkspaceAction.RELOCATE) {
return targetRoot;
}
final AssetRootValidationResult validation = AssetRelocationTargetValidator.validate(projectReference, asset.assetRoot(), targetRoot);
return validation.valid() ? validation.assetRoot() : null;
}
private record OperationSession(
ProjectReference projectReference,
AssetWorkspaceAction action,
AssetWorkspaceMutationPreview studioPreview,
PackerMutationPreview packerPreview) {
}
}
@@ -1,110 +0,0 @@
package p.studio.workspaces.assets;
import p.packer.api.PackerProjectContext;
import p.packer.api.assets.PackerBuildParticipation;
import p.packer.api.assets.PackerAssetDetails;
import p.packer.api.assets.PackerAssetState;
import p.packer.api.assets.PackerAssetSummary;
import p.packer.api.diagnostics.PackerDiagnostic;
import p.packer.api.diagnostics.PackerDiagnosticSeverity;
import p.packer.api.workspace.GetAssetDetailsRequest;
import p.packer.api.workspace.ListAssetsRequest;
import p.packer.workspace.FileSystemPackerWorkspaceService;
import p.studio.projects.ProjectReference;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
public final class PackerBackedAssetWorkspaceService implements AssetWorkspaceService {
private final FileSystemPackerWorkspaceService packerWorkspaceService;
public PackerBackedAssetWorkspaceService() {
this(new FileSystemPackerWorkspaceService());
}
public PackerBackedAssetWorkspaceService(FileSystemPackerWorkspaceService packerWorkspaceService) {
this.packerWorkspaceService = Objects.requireNonNull(packerWorkspaceService, "packerWorkspaceService");
}
@Override
public AssetWorkspaceSnapshot loadWorkspace(ProjectReference projectReference) {
final var result = packerWorkspaceService.listAssets(new ListAssetsRequest(project(projectReference)));
final List<AssetWorkspaceAssetSummary> assets = result.assets().stream()
.map(this::mapSummary)
.toList();
return new AssetWorkspaceSnapshot(assets);
}
@Override
public AssetWorkspaceAssetDetails loadAssetDetails(ProjectReference projectReference, AssetWorkspaceSelectionKey selectionKey) {
final String assetReference = switch (selectionKey) {
case AssetWorkspaceSelectionKey.ManagedAsset managedAsset -> Integer.toString(managedAsset.assetId());
case AssetWorkspaceSelectionKey.OrphanAsset orphanAsset -> relativeAssetRoot(projectReference, orphanAsset.assetRoot());
};
final var result = packerWorkspaceService.getAssetDetails(new GetAssetDetailsRequest(project(projectReference), assetReference));
return mapDetails(result.details());
}
private AssetWorkspaceAssetSummary mapSummary(PackerAssetSummary summary) {
final AssetWorkspaceAssetState state = toStudioState(summary);
final AssetWorkspaceSelectionKey selectionKey = state == AssetWorkspaceAssetState.REGISTERED
? new AssetWorkspaceSelectionKey.ManagedAsset(summary.identity().assetId())
: new AssetWorkspaceSelectionKey.OrphanAsset(summary.identity().assetRoot());
return new AssetWorkspaceAssetSummary(
selectionKey,
summary.identity().assetName(),
state,
toBuildParticipation(summary.buildParticipation()),
summary.identity().assetId(),
summary.assetFamily(),
summary.identity().assetRoot(),
summary.preloadEnabled(),
summary.hasDiagnostics());
}
private AssetWorkspaceAssetDetails mapDetails(PackerAssetDetails details) {
return new AssetWorkspaceAssetDetails(
mapSummary(details.summary()),
details.outputFormat(),
details.outputCodec(),
details.inputsByRole(),
details.diagnostics().stream().map(this::mapDiagnostic).toList());
}
private AssetWorkspaceDiagnostic mapDiagnostic(PackerDiagnostic diagnostic) {
return new AssetWorkspaceDiagnostic(
switch (diagnostic.severity()) {
case ERROR -> AssetWorkspaceDiagnosticSeverity.BLOCKER;
case WARNING -> AssetWorkspaceDiagnosticSeverity.WARNING;
case INFO -> AssetWorkspaceDiagnosticSeverity.HINT;
},
diagnostic.message());
}
private AssetWorkspaceAssetState toStudioState(PackerAssetSummary summary) {
if (summary.state() == PackerAssetState.REGISTERED) {
return AssetWorkspaceAssetState.REGISTERED;
}
return AssetWorkspaceAssetState.UNREGISTERED;
}
private AssetWorkspaceBuildParticipation toBuildParticipation(PackerBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> AssetWorkspaceBuildParticipation.INCLUDED;
case EXCLUDED -> AssetWorkspaceBuildParticipation.EXCLUDED;
};
}
private PackerProjectContext project(ProjectReference projectReference) {
final ProjectReference reference = Objects.requireNonNull(projectReference, "projectReference");
return new PackerProjectContext(reference.name(), reference.rootPath());
}
private String relativeAssetRoot(ProjectReference projectReference, Path assetRoot) {
return projectReference.rootPath().resolve("assets").toAbsolutePath().normalize()
.relativize(assetRoot.toAbsolutePath().normalize())
.toString()
.replace('\\', '/');
}
}
@@ -0,0 +1,256 @@
package p.studio.workspaces.assets.details;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.packer.assets.AssetReference;
import p.packer.assets.PackerAssetDetails;
import p.packer.messages.GetAssetDetailsRequest;
import p.studio.Container;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.details.contract.AssetDetailsContractControl;
import p.studio.workspaces.assets.details.summary.AssetDetailsSummaryControl;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsStatus;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsViewState;
import p.studio.workspaces.assets.messages.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsRefreshRequestedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceSelectionRequestedEvent;
import p.studio.workspaces.framework.StudioEventAware;
import p.studio.workspaces.framework.StudioEventBindings;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
public final class AssetDetailsControl extends VBox implements StudioEventAware {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final StudioEventBindings eventBindings = new StudioEventBindings();
private final Label detailsTitleLabel = new Label();
private final Label workspaceSummaryLabel = new Label();
private final VBox detailsContent = new VBox(12);
private final ScrollPane detailsScroll = new ScrollPane();
private final AssetDetailsSummaryControl summaryControl;
private final AssetDetailsContractControl contractControl;
private final VBox actionsContent = new VBox(10);
private final ScrollPane actionsScroll = new ScrollPane();
private final VBox actionsSection;
private final HBox primarySectionsRow = new HBox(12);
private final AtomicLong loadGeneration = new AtomicLong();
private AssetWorkspaceDetailsViewState viewState = AssetDetailsViewStateFactory.empty();
private boolean readyMounted;
public AssetDetailsControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.summaryControl = new AssetDetailsSummaryControl(projectReference, workspaceBus);
this.contractControl = new AssetDetailsContractControl(workspaceBus);
this.actionsSection = createActionsSection();
getStyleClass().add("assets-workspace-pane");
setSpacing(10);
detailsTitleLabel.getStyleClass().addAll("assets-workspace-pane-title", "assets-workspace-details-title");
workspaceSummaryLabel.getStyleClass().add("assets-workspace-summary");
detailsContent.getStyleClass().add("assets-workspace-details-content");
primarySectionsRow.getStyleClass().add("assets-details-summary-actions-row");
primarySectionsRow.setFillHeight(true);
HBox.setHgrow(summaryControl, Priority.ALWAYS);
HBox.setHgrow(actionsSection, Priority.ALWAYS);
summaryControl.setMaxWidth(Double.MAX_VALUE);
actionsSection.setMaxWidth(Double.MAX_VALUE);
contractControl.setMaxWidth(Double.MAX_VALUE);
summaryControl.prefWidthProperty().bind(primarySectionsRow.widthProperty().multiply(0.70d));
actionsSection.prefWidthProperty().bind(primarySectionsRow.widthProperty().multiply(0.30d));
primarySectionsRow.getChildren().setAll(summaryControl, actionsSection);
summaryControl.heightProperty().addListener((ignored, oldValue, newValue) -> syncActionsSectionHeight(newValue.doubleValue()));
detailsScroll.setContent(detailsContent);
detailsScroll.setFitToWidth(true);
detailsScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
detailsScroll.getStyleClass().add("assets-workspace-details-scroll");
getChildren().addAll(detailsTitleLabel, workspaceSummaryLabel, detailsScroll);
VBox.setVgrow(detailsScroll, Priority.ALWAYS);
render();
}
@Override
public StudioEventBindings eventBindings() {
return eventBindings;
}
@Override
public void registerEventSubscriptions() {
eventBindings.listen(workspaceBus, StudioAssetsRefreshRequestedEvent.class).handle(event -> {
if (event.preferredAssetReference() == null) {
clearSelection();
}
});
eventBindings.listen(workspaceBus, StudioAssetsWorkspaceSelectionRequestedEvent.class).handle(event -> {
if (!isCurrentSelection(event.assetReference())) {
loadSelection(event.assetReference());
}
});
}
public void scrollToTop() {
detailsScroll.setVvalue(0.0d);
}
private void loadSelection(AssetReference assetReference) {
final long generation = loadGeneration.incrementAndGet();
publishViewState(AssetDetailsViewStateFactory.loading(assetReference));
Container.backgroundTasks().submit(() -> loadDetails(generation, assetReference));
}
private void clearSelection() {
loadGeneration.incrementAndGet();
publishViewState(AssetDetailsViewStateFactory.empty());
}
private boolean isCurrentSelection(AssetReference assetReference) {
if (!Objects.equals(viewState.selectedAssetReference(), assetReference)) {
return false;
}
return viewState.detailsStatus() == AssetWorkspaceDetailsStatus.READY
|| viewState.detailsStatus() == AssetWorkspaceDetailsStatus.LOADING;
}
private void loadDetails(long generation, AssetReference assetReference) {
try {
final var response = Container.packer()
.workspaceService()
.getAssetDetails(new GetAssetDetailsRequest(
projectReference.toPackerProjectContext(),
assetReference));
final AssetWorkspaceAssetDetails details = mapDetails(response.details());
Platform.runLater(() -> applyLoadedDetails(generation, assetReference, details));
} catch (RuntimeException exception) {
Platform.runLater(() -> applyLoadFailure(generation, assetReference, exception));
}
}
private void applyLoadedDetails(
long generation,
AssetReference assetReference,
AssetWorkspaceAssetDetails details) {
if (generation != loadGeneration.get()) {
return;
}
publishViewState(AssetDetailsViewStateFactory.ready(assetReference, details));
}
private void applyLoadFailure(
long generation,
AssetReference assetReference,
RuntimeException exception) {
if (generation != loadGeneration.get()) {
return;
}
final String message = exception.getMessage() == null || exception.getMessage().isBlank()
? Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY)
: exception.getMessage();
publishViewState(AssetDetailsViewStateFactory.error(assetReference, message));
}
private void publishViewState(AssetWorkspaceDetailsViewState nextViewState) {
viewState = Objects.requireNonNull(nextViewState, "nextViewState");
render();
workspaceBus.publish(new StudioAssetsDetailsViewStateChangedEvent(nextViewState));
}
private void render() {
switch (viewState.detailsStatus()) {
case EMPTY -> {
readyMounted = false;
setDetailsTitle(null);
setWorkspaceSummary(Container.i18n().text(I18n.ASSETS_SUMMARY_EMPTY));
detailsContent.getChildren().setAll(AssetDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_NO_SELECTION)));
}
case LOADING -> {
readyMounted = false;
setDetailsTitle(null);
setWorkspaceSummary(Container.i18n().text(I18n.ASSETS_SUMMARY_LOADING));
detailsContent.getChildren().setAll(AssetDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_LOADING)));
}
case ERROR -> {
readyMounted = false;
setDetailsTitle(null);
setWorkspaceSummary(Container.i18n().text(I18n.ASSETS_SUMMARY_ERROR));
detailsContent.getChildren().setAll(AssetDetailsUiSupport.createSectionMessage(
Objects.requireNonNullElse(viewState.detailsErrorMessage(), Container.i18n().text(I18n.ASSETS_DETAILS_EMPTY))));
}
case READY -> {
if (viewState.selectedAssetDetails() == null) {
readyMounted = false;
setDetailsTitle(null);
setWorkspaceSummary(null);
detailsContent.getChildren().setAll(AssetDetailsUiSupport.createSectionMessage(Container.i18n().text(I18n.ASSETS_DETAILS_NO_SELECTION)));
return;
}
setDetailsTitle(viewState.selectedAssetDetails().summary().assetName());
setWorkspaceSummary(null);
if (!readyMounted) {
readyMounted = true;
detailsContent.getChildren().setAll(primarySectionsRow, contractControl);
}
syncActionsSectionHeight(summaryControl.getHeight());
}
}
}
private VBox createActionsSection() {
actionsContent.getStyleClass().add("assets-details-actions-content");
actionsScroll.setContent(actionsContent);
actionsScroll.setFitToWidth(true);
actionsScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
actionsScroll.getStyleClass().add("assets-details-actions-scroll");
return AssetDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_ACTIONS),
actionsScroll);
}
private void syncActionsSectionHeight(double summaryHeight) {
if (summaryHeight <= 0.0d) {
return;
}
actionsSection.setMinHeight(summaryHeight);
actionsSection.setPrefHeight(summaryHeight);
actionsSection.setMaxHeight(summaryHeight);
}
private void setDetailsTitle(String text) {
detailsTitleLabel.setText(text == null ? "" : text);
final boolean visible = text != null && !text.isBlank();
detailsTitleLabel.setVisible(visible);
detailsTitleLabel.setManaged(visible);
}
private void setWorkspaceSummary(String text) {
workspaceSummaryLabel.setText(text == null ? "" : text);
final boolean visible = text != null && !text.isBlank();
workspaceSummaryLabel.setVisible(visible);
workspaceSummaryLabel.setManaged(visible);
}
private AssetWorkspaceAssetDetails mapDetails(PackerAssetDetails details) {
return new AssetWorkspaceAssetDetails(
AssetListPackerMappings.mapSummary(details.summary()),
details.outputFormat(),
details.outputCodec(),
details.availableOutputCodecs(),
details.codecConfigurationFieldsByCodec(),
Map.copyOf(details.inputsByRole()));
}
}
@@ -0,0 +1,115 @@
package p.studio.workspaces.assets.details;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.packer.assets.AssetFamilyCatalog;
import p.studio.Container;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetState;
import p.studio.workspaces.assets.messages.AssetWorkspaceBuildParticipation;
import java.nio.file.Path;
public final class AssetDetailsUiSupport {
private AssetDetailsUiSupport() {
}
public static VBox createSection(String title, Node content) {
final VBox section = new VBox(10);
section.getStyleClass().add("assets-details-section");
final Label titleLabel = new Label(title);
titleLabel.getStyleClass().add("assets-details-section-title");
section.getChildren().addAll(titleLabel, content);
return section;
}
public static Node createSectionMessage(String text) {
final Label label = new Label(text);
label.setWrapText(true);
label.getStyleClass().add("assets-details-section-message");
return label;
}
public static Node createKeyValueRow(String key, String value) {
final Label valueLabel = new Label(value);
valueLabel.getStyleClass().add("assets-details-value");
valueLabel.setWrapText(true);
return createKeyValueRow(key, valueLabel);
}
public static Node createKeyValueRow(String key, Node valueNode) {
final HBox row = new HBox(12);
row.setAlignment(Pos.TOP_LEFT);
final Label keyLabel = new Label(key);
keyLabel.getStyleClass().add("assets-details-key");
HBox.setHgrow(valueNode, Priority.ALWAYS);
row.getChildren().addAll(keyLabel, valueNode);
return row;
}
public static Label createChip(String toneClass, String text) {
final Label chip = new Label(text);
chip.getStyleClass().addAll("assets-details-chip", toneClass);
return chip;
}
public static String registrationLabel(AssetWorkspaceAssetState state) {
return switch (state) {
case REGISTERED -> Container.i18n().text(I18n.ASSETS_VALUE_REGISTERED);
case UNREGISTERED -> Container.i18n().text(I18n.ASSETS_VALUE_UNREGISTERED);
};
}
public static String buildParticipationLabel(AssetWorkspaceBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_INCLUDED);
case EXCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_EXCLUDED);
};
}
public static String booleanLabel(boolean value) {
return value
? Container.i18n().text(I18n.ASSETS_VALUE_YES)
: Container.i18n().text(I18n.ASSETS_VALUE_NO);
}
public static String typeLabel(AssetFamilyCatalog assetFamily) {
return assetFamily.displayName();
}
public static String typeChipTone(AssetFamilyCatalog assetFamily) {
return switch (assetFamily) {
case IMAGE_BANK -> "assets-details-chip-image";
case PALETTE_BANK -> "assets-details-chip-palette";
case SOUND_BANK -> "assets-details-chip-audio";
case UNKNOWN -> "assets-details-chip-generic";
};
}
public static String registrationChipTone(AssetWorkspaceAssetState state) {
return switch (state) {
case REGISTERED -> "assets-details-chip-registered";
case UNREGISTERED -> "assets-details-chip-unregistered";
};
}
public static String buildChipTone(AssetWorkspaceBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> "assets-details-chip-included";
case EXCLUDED -> "assets-details-chip-excluded";
};
}
public static String projectRelativePath(ProjectReference projectReference, Path path) {
try {
return projectReference.rootPath().relativize(path.toAbsolutePath().normalize()).toString();
} catch (RuntimeException runtimeException) {
return path.toString();
}
}
}
@@ -0,0 +1,49 @@
package p.studio.workspaces.assets.details;
import p.packer.assets.AssetReference;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsStatus;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsViewState;
import java.util.Objects;
public final class AssetDetailsViewStateFactory {
private AssetDetailsViewStateFactory() {
}
public static AssetWorkspaceDetailsViewState empty() {
return new AssetWorkspaceDetailsViewState(
AssetWorkspaceDetailsStatus.EMPTY,
null,
null,
null);
}
public static AssetWorkspaceDetailsViewState loading(AssetReference assetReference) {
return new AssetWorkspaceDetailsViewState(
AssetWorkspaceDetailsStatus.LOADING,
Objects.requireNonNull(assetReference, "assetReference"),
null,
null);
}
public static AssetWorkspaceDetailsViewState ready(
AssetReference assetReference,
AssetWorkspaceAssetDetails details) {
return new AssetWorkspaceDetailsViewState(
AssetWorkspaceDetailsStatus.READY,
Objects.requireNonNull(assetReference, "assetReference"),
Objects.requireNonNull(details, "details"),
null);
}
public static AssetWorkspaceDetailsViewState error(
AssetReference assetReference,
String message) {
return new AssetWorkspaceDetailsViewState(
AssetWorkspaceDetailsStatus.ERROR,
assetReference,
null,
Objects.requireNonNullElse(message, "Unknown asset details error"));
}
}
@@ -0,0 +1,32 @@
package p.studio.workspaces.assets.details;
import p.packer.assets.PackerAssetSummary;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetState;
import p.studio.workspaces.assets.messages.AssetWorkspaceBuildParticipation;
public final class AssetListPackerMappings {
private AssetListPackerMappings() {
}
public static AssetWorkspaceAssetSummary mapSummary(PackerAssetSummary summary) {
final AssetWorkspaceAssetState state = switch (summary.state()) {
case REGISTERED -> AssetWorkspaceAssetState.REGISTERED;
case UNREGISTERED -> AssetWorkspaceAssetState.UNREGISTERED;
};
final AssetWorkspaceBuildParticipation buildParticipation = switch (summary.buildParticipation()) {
case INCLUDED -> AssetWorkspaceBuildParticipation.INCLUDED;
case EXCLUDED -> AssetWorkspaceBuildParticipation.EXCLUDED;
};
return new AssetWorkspaceAssetSummary(
summary.assetReference(),
summary.identity().assetName(),
state,
buildParticipation,
summary.identity().assetId(),
summary.assetFamily(),
summary.identity().assetRoot(),
summary.preloadEnabled(),
summary.hasDiagnostics());
}
}
@@ -0,0 +1,58 @@
package p.studio.workspaces.assets.details.contract;
import p.packer.assets.AssetReference;
import p.packer.assets.OutputCodecCatalog;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
public record AssetContractDraft(
AssetReference assetReference,
boolean preload,
String bank,
OutputCodecCatalog selectedCodec,
Map<String, String> codecFieldValues) {
public AssetContractDraft {
Objects.requireNonNull(assetReference, "assetReference");
bank = Objects.requireNonNullElse(bank, "unknown");
selectedCodec = Objects.requireNonNullElse(selectedCodec, OutputCodecCatalog.UNKNOWN);
codecFieldValues = Map.copyOf(Objects.requireNonNull(codecFieldValues, "codecFieldValues"));
}
public static AssetContractDraft fromDetails(AssetWorkspaceAssetDetails details) {
final Map<String, String> codecFieldValues = new LinkedHashMap<>();
details.codecConfigurationFieldsByCodec().forEach((codec, fields) ->
fields.forEach(field -> codecFieldValues.put(keyOf(codec, field.key()), field.value())));
return new AssetContractDraft(
details.summary().assetReference(),
details.summary().preload(),
details.outputFormat(),
details.outputCodec(),
codecFieldValues);
}
public AssetContractDraft withPreload(boolean preload) {
return new AssetContractDraft(assetReference, preload, bank, selectedCodec, codecFieldValues);
}
public AssetContractDraft withSelectedCodec(OutputCodecCatalog selectedCodec) {
return new AssetContractDraft(assetReference, preload, bank, selectedCodec, codecFieldValues);
}
public AssetContractDraft withCodecFieldValue(OutputCodecCatalog codec, String fieldKey, String value) {
final Map<String, String> nextValues = new LinkedHashMap<>(codecFieldValues);
nextValues.put(keyOf(codec, fieldKey), Objects.requireNonNullElse(value, ""));
return new AssetContractDraft(assetReference, preload, bank, selectedCodec, nextValues);
}
public String codecFieldValue(OutputCodecCatalog codec, String fieldKey, String fallback) {
return codecFieldValues.getOrDefault(keyOf(codec, fieldKey), Objects.requireNonNullElse(fallback, ""));
}
private static String keyOf(OutputCodecCatalog codec, String fieldKey) {
return codec.name() + ":" + fieldKey;
}
}
@@ -0,0 +1,355 @@
package p.studio.workspaces.assets.details.contract;
import javafx.collections.FXCollections;
import javafx.scene.Node;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.packer.assets.OutputCodecCatalog;
import p.packer.assets.PackerCodecConfigurationField;
import p.studio.Container;
import p.studio.controls.forms.StudioFormActionBar;
import p.studio.controls.forms.StudioFormMode;
import p.studio.controls.forms.StudioFormSession;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.details.AssetDetailsUiSupport;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetDetails;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsViewState;
import p.studio.workspaces.assets.messages.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.Objects;
public final class AssetDetailsContractControl extends VBox implements StudioControlLifecycle {
private final StudioWorkspaceEventBus workspaceBus;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private final StudioFormActionBar actionBar = new StudioFormActionBar(
this::beginEdit,
this::applyDraft,
this::resetDraft,
this::cancelEdit);
private AssetWorkspaceDetailsViewState viewState;
private StudioFormSession<AssetContractDraft> formSession;
public AssetDetailsContractControl(StudioWorkspaceEventBus workspaceBus) {
StudioControlLifecycleSupport.install(this, this);
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
viewState = event.viewState();
syncFormSession();
render();
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void syncFormSession() {
if (viewState == null || viewState.selectedAssetDetails() == null) {
formSession = null;
return;
}
final AssetContractDraft source = AssetContractDraft.fromDetails(viewState.selectedAssetDetails());
if (formSession == null) {
formSession = new StudioFormSession<>(source);
return;
}
if (!Objects.equals(formSession.source(), source)) {
formSession.replaceSource(source);
}
}
private void render() {
if (viewState == null || viewState.selectedAssetDetails() == null) {
getChildren().clear();
return;
}
if (formSession == null) {
syncFormSession();
}
if (formSession == null) {
getChildren().clear();
return;
}
final AssetWorkspaceAssetDetails details = viewState.selectedAssetDetails();
final AssetContractDraft draft = formSession.draft();
final boolean editing = formSession.mode() == StudioFormMode.EDITING;
final VBox generalColumn = new VBox(8);
generalColumn.getStyleClass().add("assets-details-contract-column");
generalColumn.getChildren().setAll(
AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_PRELOAD),
createPreloadEditor(draft, editing)),
AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_BANK),
draft.bank()));
final VBox codecColumn = new VBox(10);
codecColumn.getStyleClass().addAll("assets-details-contract-column", "assets-details-contract-codec-column");
codecColumn.getChildren().setAll(
AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_CODEC),
createCodecEditor(details, draft, editing)),
createCodecConfigurationSection(details, draft, editing));
final HBox contractBody = new HBox(16);
contractBody.getStyleClass().add("assets-details-contract-body");
HBox.setHgrow(generalColumn, Priority.ALWAYS);
HBox.setHgrow(codecColumn, Priority.ALWAYS);
generalColumn.prefWidthProperty().bind(contractBody.widthProperty().subtract(16).multiply(0.5d));
codecColumn.prefWidthProperty().bind(contractBody.widthProperty().subtract(16).multiply(0.5d));
generalColumn.setMaxWidth(Double.MAX_VALUE);
codecColumn.setMaxWidth(Double.MAX_VALUE);
contractBody.getChildren().setAll(generalColumn, codecColumn);
final VBox content = new VBox(12);
content.getChildren().setAll(contractBody);
actionBar.updateState(formSession.mode(), formSession.isDirty());
content.getChildren().add(actionBar);
final VBox section = AssetDetailsUiSupport.createSection(
Container.i18n().text(I18n.ASSETS_SECTION_RUNTIME_CONTRACT),
content);
section.getStyleClass().add("assets-details-contract-section");
getChildren().setAll(section);
}
private Node createPreloadEditor(AssetContractDraft draft, boolean editing) {
final CheckBox checkBox = new CheckBox();
checkBox.getStyleClass().add("assets-details-readonly-check");
checkBox.setSelected(draft.preload());
if (editing) {
checkBox.selectedProperty().addListener((ignored, oldValue, newValue) -> {
if (!Objects.equals(oldValue, newValue)) {
formSession.updateDraft(current -> current.withPreload(newValue));
actionBar.updateState(formSession.mode(), formSession.isDirty());
}
});
} else {
configureReadOnlyControl(checkBox);
}
return checkBox;
}
private Node createCodecEditor(
AssetWorkspaceAssetDetails details,
AssetContractDraft draft,
boolean editing) {
final ComboBox<OutputCodecCatalog> codecCombo = new ComboBox<>(FXCollections.observableArrayList(details.availableOutputCodecs()));
codecCombo.getStyleClass().add("assets-details-combo");
codecCombo.setMaxWidth(Double.MAX_VALUE);
codecCombo.setCellFactory(ignored -> new javafx.scene.control.ListCell<>() {
@Override
protected void updateItem(OutputCodecCatalog item, boolean empty) {
super.updateItem(item, empty);
setText(empty || item == null ? null : item.displayName());
}
});
codecCombo.setButtonCell(new javafx.scene.control.ListCell<>() {
@Override
protected void updateItem(OutputCodecCatalog item, boolean empty) {
super.updateItem(item, empty);
setText(empty || item == null ? null : item.displayName());
}
});
codecCombo.getSelectionModel().select(draft.selectedCodec());
if (editing) {
codecCombo.valueProperty().addListener((ignored, oldValue, newValue) -> {
if (newValue != null && !Objects.equals(oldValue, newValue)) {
formSession.updateDraft(current -> current.withSelectedCodec(newValue));
render();
}
});
} else {
configureReadOnlyControl(codecCombo);
}
return codecCombo;
}
private Node createCodecConfigurationSection(
AssetWorkspaceAssetDetails details,
AssetContractDraft draft,
boolean editing) {
final VBox subsection = new VBox(8);
subsection.getStyleClass().add("assets-details-contract-metadata");
final Label title = new Label(Container.i18n().text(I18n.ASSETS_SUBSECTION_CODEC_CONFIGURATION));
title.getStyleClass().add("assets-details-subsection-title");
final VBox content = new VBox(8);
content.getStyleClass().add("assets-details-contract-metadata-content");
if (draft.selectedCodec() == OutputCodecCatalog.NONE || draft.selectedCodec() == OutputCodecCatalog.UNKNOWN) {
content.getChildren().add(AssetDetailsUiSupport.createSectionMessage(
Container.i18n().text(I18n.ASSETS_DETAILS_CODEC_CONFIGURATION_EMPTY)));
return createCodecMetadataPane(title, content);
}
final var fields = details.codecConfigurationFieldsByCodec().getOrDefault(draft.selectedCodec(), java.util.List.of());
if (fields.isEmpty()) {
content.getChildren().add(AssetDetailsUiSupport.createSectionMessage(
Container.i18n().text(I18n.ASSETS_DETAILS_CODEC_CONFIGURATION_EMPTY)));
return createCodecMetadataPane(title, content);
}
for (PackerCodecConfigurationField field : fields) {
content.getChildren().add(createCodecFieldRow(field, draft, editing));
}
return createCodecMetadataPane(title, content);
}
private Node createCodecMetadataPane(Label title, VBox content) {
final ScrollPane scrollPane = new ScrollPane(content);
scrollPane.setFitToWidth(true);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
scrollPane.getStyleClass().add("assets-details-contract-metadata-scroll");
final VBox container = new VBox(8);
container.getChildren().setAll(title, scrollPane);
VBox.setVgrow(scrollPane, Priority.ALWAYS);
return container;
}
private Node createCodecFieldRow(
PackerCodecConfigurationField field,
AssetContractDraft draft,
boolean editing) {
final Node valueNode = switch (field.fieldType()) {
case BOOLEAN -> createBooleanField(field, draft, editing);
case ENUM -> createEnumField(field, draft, editing);
case INTEGER, TEXT -> createTextField(field, draft, editing);
};
return AssetDetailsUiSupport.createKeyValueRow(field.label(), valueNode);
}
private Node createBooleanField(
PackerCodecConfigurationField field,
AssetContractDraft draft,
boolean editing) {
final CheckBox checkBox = new CheckBox();
checkBox.getStyleClass().add("assets-details-readonly-check");
checkBox.setSelected(Boolean.parseBoolean(currentValue(field, draft)));
if (editing) {
checkBox.selectedProperty().addListener((ignored, oldValue, newValue) -> {
if (!Objects.equals(oldValue, newValue)) {
formSession.updateDraft(current -> current.withCodecFieldValue(
current.selectedCodec(),
field.key(),
Boolean.toString(newValue)));
actionBar.updateState(formSession.mode(), formSession.isDirty());
}
});
} else {
configureReadOnlyControl(checkBox);
}
return checkBox;
}
private Node createEnumField(
PackerCodecConfigurationField field,
AssetContractDraft draft,
boolean editing) {
final ComboBox<String> comboBox = new ComboBox<>(FXCollections.observableArrayList(field.options()));
comboBox.getStyleClass().add("assets-details-combo");
comboBox.setMaxWidth(Double.MAX_VALUE);
comboBox.getSelectionModel().select(currentValue(field, draft));
if (editing) {
comboBox.valueProperty().addListener((ignored, oldValue, newValue) -> {
if (newValue != null && !Objects.equals(oldValue, newValue)) {
formSession.updateDraft(current -> current.withCodecFieldValue(
current.selectedCodec(),
field.key(),
newValue));
actionBar.updateState(formSession.mode(), formSession.isDirty());
}
});
} else {
configureReadOnlyControl(comboBox);
}
return comboBox;
}
private Node createTextField(
PackerCodecConfigurationField field,
AssetContractDraft draft,
boolean editing) {
final TextField textField = new TextField(currentValue(field, draft));
textField.getStyleClass().add("assets-workspace-search");
textField.setMaxWidth(Double.MAX_VALUE);
HBox.setHgrow(textField, Priority.ALWAYS);
if (editing) {
textField.textProperty().addListener((ignored, oldValue, newValue) -> {
if (!Objects.equals(oldValue, newValue)) {
formSession.updateDraft(current -> current.withCodecFieldValue(
current.selectedCodec(),
field.key(),
Objects.requireNonNullElse(newValue, "")));
actionBar.updateState(formSession.mode(), formSession.isDirty());
}
});
} else {
textField.setEditable(false);
configureReadOnlyControl(textField);
}
return textField;
}
private String currentValue(PackerCodecConfigurationField field, AssetContractDraft draft) {
return draft.codecFieldValue(draft.selectedCodec(), field.key(), field.value());
}
private void configureReadOnlyControl(javafx.scene.control.Control control) {
control.setMouseTransparent(true);
control.setFocusTraversable(false);
}
private void beginEdit() {
if (formSession == null) {
return;
}
formSession.beginEdit();
render();
}
private void applyDraft() {
if (formSession == null) {
return;
}
render();
}
private void resetDraft() {
if (formSession == null) {
return;
}
formSession.resetDraft();
render();
}
private void cancelEdit() {
if (formSession == null) {
return;
}
formSession.cancelEdit();
render();
}
}
@@ -0,0 +1,76 @@
package p.studio.workspaces.assets.details.summary;
import javafx.scene.layout.VBox;
import p.studio.Container;
import p.studio.controls.lifecycle.StudioControlLifecycle;
import p.studio.controls.lifecycle.StudioControlLifecycleSupport;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.details.AssetDetailsUiSupport;
import p.studio.workspaces.assets.messages.events.StudioAssetsDetailsViewStateChangedEvent;
import p.studio.workspaces.assets.messages.AssetWorkspaceDetailsViewState;
import p.studio.workspaces.framework.StudioSubscriptionBag;
import java.util.Objects;
public final class AssetDetailsSummaryControl extends VBox implements StudioControlLifecycle {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final StudioSubscriptionBag subscriptions = new StudioSubscriptionBag();
private AssetWorkspaceDetailsViewState viewState;
public AssetDetailsSummaryControl(ProjectReference projectReference, StudioWorkspaceEventBus workspaceBus) {
StudioControlLifecycleSupport.install(this, this);
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
}
@Override
public void subscribe() {
subscriptions.add(workspaceBus.subscribe(StudioAssetsDetailsViewStateChangedEvent.class, event -> {
viewState = event.viewState();
render();
}));
}
@Override
public void unsubscribe() {
subscriptions.clear();
}
private void render() {
if (viewState == null || viewState.selectedAssetDetails() == null) {
getChildren().clear();
return;
}
final AssetWorkspaceAssetSummary summary = viewState.selectedAssetDetails().summary();
if (summary == null) {
getChildren().clear();
return;
}
final VBox content = new VBox(8);
content.getChildren().setAll(
AssetDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_ASSET_ID), summary.assetId() == null ? "—" : String.valueOf(summary.assetId())),
AssetDetailsUiSupport.createKeyValueRow(Container.i18n().text(I18n.ASSETS_LABEL_LOCATION), AssetDetailsUiSupport.projectRelativePath(projectReference, summary.assetRoot())));
content.getChildren().add(AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_TYPE),
AssetDetailsUiSupport.createChip(
AssetDetailsUiSupport.typeChipTone(summary.assetFamily()),
AssetDetailsUiSupport.typeLabel(summary.assetFamily()))));
content.getChildren().add(AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_REGISTRATION),
AssetDetailsUiSupport.createChip(
AssetDetailsUiSupport.registrationChipTone(summary.state()),
AssetDetailsUiSupport.registrationLabel(summary.state()))));
content.getChildren().add(AssetDetailsUiSupport.createKeyValueRow(
Container.i18n().text(I18n.ASSETS_LABEL_BUILD_PARTICIPATION),
AssetDetailsUiSupport.createChip(
AssetDetailsUiSupport.buildChipTone(summary.buildParticipation()),
AssetDetailsUiSupport.buildParticipationLabel(summary.buildParticipation()))));
getChildren().setAll(AssetDetailsUiSupport.createSection(Container.i18n().text(I18n.ASSETS_SECTION_SUMMARY), content));
}
}
@@ -0,0 +1,312 @@
package p.studio.workspaces.assets.list;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import p.packer.assets.AssetReference;
import p.packer.assets.PackerAssetSummary;
import p.packer.messages.ListAssetsRequest;
import p.studio.Container;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.AssetWorkspaceState;
import p.studio.workspaces.assets.details.AssetListPackerMappings;
import p.studio.workspaces.assets.messages.AssetListGroup;
import p.studio.workspaces.assets.messages.AssetListProjection;
import p.studio.workspaces.assets.messages.AssetListViewState;
import p.studio.workspaces.assets.messages.AssetWorkspaceStatus;
import p.studio.workspaces.assets.messages.events.StudioAssetsNavigatorViewStateChangedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsRefreshRequestedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshFailedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshStartedEvent;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceRefreshedEvent;
import p.studio.workspaces.framework.StudioEventAware;
import p.studio.workspaces.framework.StudioEventBindings;
import java.util.EnumSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
public final class AssetListControl extends VBox implements StudioEventAware {
private final ProjectReference projectReference;
private final StudioWorkspaceEventBus workspaceBus;
private final StudioEventBindings eventBindings = new StudioEventBindings();
private final VBox navigatorContent = new VBox(8);
private final TextField searchField = new TextField();
private final ToggleButton unregisteredFilterButton = new ToggleButton();
private final ToggleButton diagnosticsFilterButton = new ToggleButton();
private final ToggleButton preloadFilterButton = new ToggleButton();
private final AtomicLong refreshGeneration = new AtomicLong();
private AssetListViewState viewState = new AssetListViewState(
AssetWorkspaceState.loading(null),
null,
Container.i18n().text(I18n.ASSETS_STATE_LOADING));
public AssetListControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
getStyleClass().add("assets-workspace-pane");
setSpacing(8);
navigatorContent.getStyleClass().add("assets-workspace-navigator-content");
getChildren().addAll(
createNavigatorTitle(),
createSearchField(),
createFilterBar(),
createNavigatorScroll());
installProjectionInputs();
render();
}
@Override
public StudioEventBindings eventBindings() {
return eventBindings;
}
@Override
public void registerEventSubscriptions() {
eventBindings.listen(workspaceBus, StudioAssetsRefreshRequestedEvent.class).handle(event -> {
requestRefresh(event.preferredAssetReference());
});
eventBindings.listen(workspaceBus, StudioAssetsNavigatorViewStateChangedEvent.class).handle(event -> {
viewState = event.viewState();
render();
});
}
private Label createNavigatorTitle() {
final var navigatorTitle = new Label();
navigatorTitle.textProperty().bind(Container.i18n().bind(I18n.ASSETS_NAVIGATOR_TITLE));
navigatorTitle.getStyleClass().add("assets-workspace-pane-title");
return navigatorTitle;
}
private TextField createSearchField() {
searchField.setPromptText(Container.i18n().text(I18n.ASSETS_SEARCH_PROMPT));
searchField.getStyleClass().add("assets-workspace-search");
return searchField;
}
private FlowPane createFilterBar() {
final var filterBar = new FlowPane();
filterBar.setHgap(6);
filterBar.setVgap(6);
filterBar.setPadding(new Insets(4, 0, 4, 0));
filterBar.getStyleClass().add("assets-workspace-filter-bar");
filterBar.getChildren().addAll(
configureFilterButton(unregisteredFilterButton, I18n.ASSETS_FILTER_UNREGISTERED),
configureFilterButton(diagnosticsFilterButton, I18n.ASSETS_FILTER_DIAGNOSTICS),
configureFilterButton(preloadFilterButton, I18n.ASSETS_FILTER_PRELOAD));
return filterBar;
}
private ToggleButton configureFilterButton(ToggleButton button, I18n i18n) {
button.textProperty().bind(Container.i18n().bind(i18n));
button.getStyleClass().addAll("studio-button", "studio-button-secondary", "studio-button-pill", "studio-button-toggle");
return button;
}
private ScrollPane createNavigatorScroll() {
final var navigatorScroll = new ScrollPane(navigatorContent);
navigatorScroll.setFitToWidth(true);
navigatorScroll.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
navigatorScroll.getStyleClass().add("assets-workspace-navigator-scroll");
VBox.setVgrow(navigatorScroll, Priority.ALWAYS);
return navigatorScroll;
}
private void installProjectionInputs() {
searchField.textProperty().addListener((ignored, oldValue, newValue) -> rebuildProjection());
unregisteredFilterButton.setOnAction(ignored -> rebuildProjection());
diagnosticsFilterButton.setOnAction(ignored -> rebuildProjection());
preloadFilterButton.setOnAction(ignored -> rebuildProjection());
}
private void requestRefresh(AssetReference preferredAssetReference) {
if (!Platform.isFxApplicationThread()) {
Platform.runLater(() -> requestRefresh(preferredAssetReference));
return;
}
final AssetWorkspaceState previousState = viewState.workspaceState();
final AssetReference assetReference = preferredAssetReference != null
? preferredAssetReference
: previousState.selectedAssetReference();
final long generation = refreshGeneration.incrementAndGet();
publishNavigatorViewState(new AssetListViewState(
AssetWorkspaceState.loading(previousState),
null,
Container.i18n().text(I18n.ASSETS_STATE_LOADING)));
workspaceBus.publish(new StudioAssetsWorkspaceRefreshStartedEvent());
Container.backgroundTasks().submit(() -> loadAssets(generation, assetReference));
}
private void loadAssets(
long generation,
AssetReference preferredAssetReference) {
try {
final var projectContext = projectReference.toPackerProjectContext();
final var response = Container.packer()
.workspaceService()
.listAssets(new ListAssetsRequest(projectContext));
final List<AssetWorkspaceAssetSummary> assets = response.assets().stream()
.map(this::mapAsset)
.toList();
final AssetWorkspaceState workspaceState = AssetWorkspaceState.ready(assets, preferredAssetReference);
Platform.runLater(() -> applyRefreshResult(generation, workspaceState));
} catch (RuntimeException exception) {
Platform.runLater(() -> applyRefreshFailure(generation, exception));
}
}
private void applyRefreshResult(long generation, AssetWorkspaceState workspaceState) {
if (generation != refreshGeneration.get()) {
return;
}
final AssetListProjection projection = AssetListProjectionBuilder.build(
workspaceState.assets(),
projectReference.rootPath(),
searchField.getText(),
currentFilters());
final AssetListViewState nextViewState = new AssetListViewState(
workspaceState,
projection,
buildViewMessage(workspaceState, projection));
publishNavigatorViewState(nextViewState);
workspaceBus.publish(new StudioAssetsWorkspaceRefreshedEvent(
nextViewState.workspaceState().assets().size()));
}
private void applyRefreshFailure(long generation, RuntimeException exception) {
if (generation != refreshGeneration.get()) {
return;
}
final String message = exception.getMessage() == null || exception.getMessage().isBlank()
? Container.i18n().text(I18n.ASSETS_STATE_ERROR)
: exception.getMessage();
publishNavigatorViewState(new AssetListViewState(
AssetWorkspaceState.error(viewState.workspaceState(), message),
viewState.projection(),
message));
workspaceBus.publish(new StudioAssetsWorkspaceRefreshFailedEvent(message));
}
private void rebuildProjection() {
if (!Platform.isFxApplicationThread()) {
Platform.runLater(this::rebuildProjection);
return;
}
final AssetWorkspaceState workspaceState = viewState.workspaceState();
if (workspaceState.status() == AssetWorkspaceStatus.LOADING || workspaceState.status() == AssetWorkspaceStatus.ERROR) {
return;
}
final AssetListProjection projection = AssetListProjectionBuilder.build(
workspaceState.assets(),
projectReference.rootPath(),
searchField.getText(),
currentFilters());
publishNavigatorViewState(new AssetListViewState(
workspaceState,
projection,
buildViewMessage(workspaceState, projection)));
}
private void publishNavigatorViewState(AssetListViewState nextViewState) {
viewState = Objects.requireNonNull(nextViewState, "nextViewState");
workspaceBus.publish(new StudioAssetsNavigatorViewStateChangedEvent(nextViewState));
}
private AssetWorkspaceAssetSummary mapAsset(PackerAssetSummary summary) {
return AssetListPackerMappings.mapSummary(summary);
}
private Set<AssetListFilter> currentFilters() {
final EnumSet<AssetListFilter> filters = EnumSet.noneOf(AssetListFilter.class);
if (unregisteredFilterButton.isSelected()) {
filters.add(AssetListFilter.UNREGISTERED);
}
if (diagnosticsFilterButton.isSelected()) {
filters.add(AssetListFilter.DIAGNOSTICS);
}
if (preloadFilterButton.isSelected()) {
filters.add(AssetListFilter.PRELOAD);
}
return filters;
}
private String buildViewMessage(AssetWorkspaceState workspaceState, AssetListProjection projection) {
return switch (workspaceState.status()) {
case LOADING -> Container.i18n().text(I18n.ASSETS_STATE_LOADING);
case EMPTY -> Container.i18n().text(I18n.ASSETS_STATE_EMPTY);
case ERROR -> workspaceState.errorMessage();
case READY -> projection == null || projection.isEmpty()
? Container.i18n().text(I18n.ASSETS_STATE_NO_RESULTS)
: Container.i18n().text(I18n.ASSETS_STATE_READY);
};
}
private void render() {
navigatorContent.getChildren().clear();
final AssetWorkspaceStatus status = viewState.workspaceState().status();
if (status == AssetWorkspaceStatus.LOADING) {
navigatorContent.getChildren().setAll(createMessageNode(viewState.message()));
return;
}
if (status == AssetWorkspaceStatus.ERROR) {
navigatorContent.getChildren().setAll(createMessageNode(viewState.message()));
return;
}
if (status == AssetWorkspaceStatus.EMPTY || !viewState.hasProjection()) {
navigatorContent.getChildren().setAll(createMessageNode(viewState.message()));
return;
}
for (AssetListGroup group : viewState.projection().groups()) {
final var groupBox = createGroupBox(group.label());
for (AssetWorkspaceAssetSummary asset : group.assets()) {
groupBox.getChildren().add(new AssetListItemControl(
projectReference,
workspaceBus,
asset));
}
navigatorContent.getChildren().add(groupBox);
}
}
private VBox createGroupBox(String label) {
final var groupBox = new VBox(6);
groupBox.getStyleClass().add("assets-workspace-group");
groupBox.getChildren().add(createGroupLabel(label));
return groupBox;
}
private Label createGroupLabel(String text) {
final var groupLabel = new Label(text);
groupLabel.getStyleClass().add("assets-workspace-group-label");
return groupLabel;
}
private Node createMessageNode(String text) {
final var label = new Label(text);
label.getStyleClass().add("assets-workspace-empty-state");
label.setWrapText(true);
return label;
}
}
@@ -0,0 +1,7 @@
package p.studio.workspaces.assets.list;
public enum AssetListFilter {
UNREGISTERED,
DIAGNOSTICS,
PRELOAD
}
@@ -0,0 +1,130 @@
package p.studio.workspaces.assets.list;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import p.packer.assets.AssetFamilyCatalog;
import p.studio.Container;
import p.studio.workspaces.assets.messages.events.StudioAssetsWorkspaceSelectionRequestedEvent;
import p.studio.events.StudioWorkspaceEventBus;
import p.studio.projects.ProjectReference;
import p.studio.utilities.i18n.I18n;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetState;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.messages.AssetWorkspaceBuildParticipation;
import java.nio.file.Path;
import java.util.Objects;
public final class AssetListItemControl extends VBox {
private final ProjectReference projectReference;
private final Path projectRoot;
private final StudioWorkspaceEventBus workspaceBus;
private AssetWorkspaceAssetSummary summary;
public AssetListItemControl(
ProjectReference projectReference,
StudioWorkspaceEventBus workspaceBus,
AssetWorkspaceAssetSummary summary) {
this.projectReference = Objects.requireNonNull(projectReference, "projectReference");
this.projectRoot = this.projectReference.rootPath();
this.workspaceBus = Objects.requireNonNull(workspaceBus, "workspaceBus");
this.summary = Objects.requireNonNull(summary, "summary");
render();
}
private void render() {
getChildren().clear();
getStyleClass().setAll("assets-workspace-asset-row", assetRowToneClass(summary.assetFamily()));
getChildren().setAll(createTopLine(), createPathLabel());
setOnMouseClicked(event -> workspaceBus.publish(
new StudioAssetsWorkspaceSelectionRequestedEvent(summary.assetReference())));
}
private HBox createTopLine() {
final var topLine = new HBox(8);
topLine.setAlignment(Pos.CENTER_LEFT);
topLine.getChildren().addAll(
createNameLabel(),
createSpacer(),
createBadgesBox());
return topLine;
}
private Label createNameLabel() {
final var name = new Label(summary.assetName());
name.getStyleClass().addAll("assets-workspace-asset-name", assetNameToneClass(summary.assetFamily()));
return name;
}
private Region createSpacer() {
final var spacer = new Region();
HBox.setHgrow(spacer, Priority.ALWAYS);
return spacer;
}
private HBox createBadgesBox() {
final var badges = new HBox(6);
badges.setAlignment(Pos.CENTER_RIGHT);
badges.getStyleClass().add("assets-workspace-asset-badges");
populateBadges(badges);
return badges;
}
private Label createPathLabel() {
final var path = new Label(AssetListProjectionBuilder.relativeRoot(summary, projectRoot));
path.getStyleClass().add("assets-workspace-asset-path");
return path;
}
private void populateBadges(HBox badges) {
if (summary.state() == AssetWorkspaceAssetState.UNREGISTERED) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_UNREGISTERED), "assets-workspace-badge-orphan"));
} else if (summary.buildParticipation() == AssetWorkspaceBuildParticipation.INCLUDED) {
badges.getChildren().add(createBadge(buildParticipationLabel(summary.buildParticipation()), "assets-workspace-badge-preload"));
if (summary.preload()) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_PRELOAD), "assets-workspace-badge-preload"));
}
} else {
badges.getChildren().add(createBadge(buildParticipationLabel(summary.buildParticipation()), "assets-workspace-badge-diagnostics"));
}
if (summary.hasDiagnostics()) {
badges.getChildren().add(createBadge(Container.i18n().text(I18n.ASSETS_BADGE_DIAGNOSTICS), "assets-workspace-badge-diagnostics"));
}
}
private Label createBadge(String text, String styleClass) {
final Label badge = new Label(text);
badge.getStyleClass().addAll("assets-workspace-badge", styleClass);
return badge;
}
private String buildParticipationLabel(AssetWorkspaceBuildParticipation buildParticipation) {
return switch (buildParticipation) {
case INCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_INCLUDED);
case EXCLUDED -> Container.i18n().text(I18n.ASSETS_VALUE_EXCLUDED);
};
}
private String assetRowToneClass(AssetFamilyCatalog assetFamily) {
return switch (assetFamily) {
case IMAGE_BANK -> "assets-workspace-asset-row-tone-image";
case PALETTE_BANK -> "assets-workspace-asset-row-tone-palette";
case SOUND_BANK -> "assets-workspace-asset-row-tone-audio";
default -> "assets-workspace-asset-row-tone-generic";
};
}
private String assetNameToneClass(AssetFamilyCatalog assetFamily) {
return switch (assetFamily) {
case IMAGE_BANK -> "assets-workspace-asset-name-tone-image";
case PALETTE_BANK -> "assets-workspace-asset-name-tone-palette";
case SOUND_BANK -> "assets-workspace-asset-name-tone-audio";
default -> "assets-workspace-asset-name-tone-generic";
};
}
}
@@ -1,22 +1,27 @@
package p.studio.workspaces.assets;
package p.studio.workspaces.assets.list;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetState;
import p.studio.workspaces.assets.messages.AssetWorkspaceAssetSummary;
import p.studio.workspaces.assets.messages.AssetListGroup;
import p.studio.workspaces.assets.messages.AssetListProjection;
import java.nio.file.Path;
import java.util.*;
public final class AssetNavigatorProjectionBuilder {
private AssetNavigatorProjectionBuilder() {
public final class AssetListProjectionBuilder {
private AssetListProjectionBuilder() {
}
public static AssetNavigatorProjection build(
public static AssetListProjection build(
List<AssetWorkspaceAssetSummary> assets,
Path projectRoot,
String searchQuery,
Set<AssetNavigatorFilter> filters) {
Set<AssetListFilter> filters) {
Objects.requireNonNull(assets, "assets");
final Path normalizedProjectRoot = Objects.requireNonNull(projectRoot, "projectRoot").toAbsolutePath().normalize();
final String normalizedQuery = normalizeQuery(searchQuery);
final Set<AssetNavigatorFilter> normalizedFilters = filters == null || filters.isEmpty()
? EnumSet.noneOf(AssetNavigatorFilter.class)
final Set<AssetListFilter> normalizedFilters = filters == null || filters.isEmpty()
? EnumSet.noneOf(AssetListFilter.class)
: EnumSet.copyOf(filters);
final Map<String, List<AssetWorkspaceAssetSummary>> grouped = new LinkedHashMap<>();
@@ -28,37 +33,35 @@ public final class AssetNavigatorProjectionBuilder {
.add(asset);
}
final List<AssetNavigatorGroup> groups = grouped.entrySet().stream()
.map(entry -> new AssetNavigatorGroup(entry.getKey(), entry.getValue()))
final List<AssetListGroup> groups = grouped.entrySet().stream()
.map(entry -> new AssetListGroup(entry.getKey(), entry.getValue()))
.toList();
final int visibleAssetCount = groups.stream().mapToInt(group -> group.assets().size()).sum();
return new AssetNavigatorProjection(groups, visibleAssetCount);
return new AssetListProjection(groups, visibleAssetCount);
}
static String relativeRoot(AssetWorkspaceAssetSummary asset, Path projectRoot) {
public static String relativeRoot(AssetWorkspaceAssetSummary asset, Path projectRoot) {
return relativize(asset.assetRoot(), projectRoot).toString().replace('\\', '/');
}
private static boolean matchesFilters(AssetWorkspaceAssetSummary asset, Set<AssetNavigatorFilter> filters) {
private static boolean matchesFilters(AssetWorkspaceAssetSummary asset, Set<AssetListFilter> filters) {
if (filters.isEmpty()) {
return true;
}
final boolean includeRegistered = filters.contains(AssetNavigatorFilter.REGISTERED);
final boolean includeUnregistered = filters.contains(AssetNavigatorFilter.UNREGISTERED);
if (includeRegistered || includeUnregistered) {
final boolean stateMatches = (includeRegistered && asset.state() == AssetWorkspaceAssetState.REGISTERED)
|| (includeUnregistered && asset.state() == AssetWorkspaceAssetState.UNREGISTERED);
final boolean includeUnregistered = filters.contains(AssetListFilter.UNREGISTERED);
if (includeUnregistered) {
final boolean stateMatches = asset.state() == AssetWorkspaceAssetState.UNREGISTERED;
if (!stateMatches) {
return false;
}
}
if (filters.contains(AssetNavigatorFilter.DIAGNOSTICS) && !asset.hasDiagnostics()) {
if (filters.contains(AssetListFilter.DIAGNOSTICS) && !asset.hasDiagnostics()) {
return false;
}
if (filters.contains(AssetNavigatorFilter.PRELOAD) && !asset.preload()) {
if (filters.contains(AssetListFilter.PRELOAD) && !asset.preload()) {
return false;
}
@@ -72,17 +75,14 @@ public final class AssetNavigatorProjectionBuilder {
final String relativeRoot = relativeRoot(asset, projectRoot);
return asset.assetName().toLowerCase(Locale.ROOT).contains(normalizedQuery)
|| asset.assetFamily().toLowerCase(Locale.ROOT).contains(normalizedQuery)
|| asset.assetFamily().matchesQuery(normalizedQuery)
|| relativeRoot.toLowerCase(Locale.ROOT).contains(normalizedQuery);
}
private static String groupLabel(AssetWorkspaceAssetSummary asset, Path projectRoot) {
final Path relativeRoot = relativize(asset.assetRoot(), projectRoot);
final Path parent = relativeRoot.getParent();
if (parent == null) {
return relativeRoot.toString().replace('\\', '/');
}
return parent.toString().replace('\\', '/');
return Objects.requireNonNullElse(parent, relativeRoot).toString().replace('\\', '/');
}
private static Path relativize(Path assetRoot, Path projectRoot) {
@@ -1,10 +1,10 @@
package p.studio.workspaces.assets;
package p.studio.workspaces.assets.messages;
import java.util.List;
import java.util.Objects;
public record AssetNavigatorGroup(String label, List<AssetWorkspaceAssetSummary> assets) {
public AssetNavigatorGroup {
public record AssetListGroup(String label, List<AssetWorkspaceAssetSummary> assets) {
public AssetListGroup {
label = Objects.requireNonNull(label, "label").trim();
assets = List.copyOf(Objects.requireNonNull(assets, "assets"));
if (label.isBlank()) {
@@ -1,10 +1,10 @@
package p.studio.workspaces.assets;
package p.studio.workspaces.assets.messages;
import java.util.List;
import java.util.Objects;
public record AssetNavigatorProjection(List<AssetNavigatorGroup> groups, int visibleAssetCount) {
public AssetNavigatorProjection {
public record AssetListProjection(List<AssetListGroup> groups, int visibleAssetCount) {
public AssetListProjection {
groups = List.copyOf(Objects.requireNonNull(groups, "groups"));
if (visibleAssetCount < 0) {
throw new IllegalArgumentException("visibleAssetCount must not be negative");
@@ -1,13 +1,14 @@
package p.studio.workspaces.assets;
package p.studio.workspaces.assets.messages;
import p.studio.workspaces.assets.AssetWorkspaceState;
import java.util.Objects;
public record AssetWorkspaceNavigatorViewState(
public record AssetListViewState(
AssetWorkspaceState workspaceState,
AssetNavigatorProjection projection,
AssetListProjection projection,
String message) {
public AssetWorkspaceNavigatorViewState {
public AssetListViewState {
Objects.requireNonNull(workspaceState, "workspaceState");
Objects.requireNonNull(message, "message");
}
@@ -0,0 +1,27 @@
package p.studio.workspaces.assets.messages;
import p.packer.assets.PackerCodecConfigurationField;
import p.packer.assets.OutputCodecCatalog;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.Objects;
public record AssetWorkspaceAssetDetails(
AssetWorkspaceAssetSummary summary,
String outputFormat,
OutputCodecCatalog outputCodec,
List<OutputCodecCatalog> availableOutputCodecs,
Map<OutputCodecCatalog, List<PackerCodecConfigurationField>> codecConfigurationFieldsByCodec,
Map<String, List<Path>> inputsByRole) {
public AssetWorkspaceAssetDetails {
Objects.requireNonNull(summary, "summary");
outputFormat = Objects.requireNonNullElse(outputFormat, "unknown");
outputCodec = Objects.requireNonNullElse(outputCodec, OutputCodecCatalog.UNKNOWN);
availableOutputCodecs = List.copyOf(Objects.requireNonNull(availableOutputCodecs, "availableOutputCodecs"));
codecConfigurationFieldsByCodec = Map.copyOf(Objects.requireNonNull(codecConfigurationFieldsByCodec, "codecConfigurationFieldsByCodec"));
inputsByRole = Map.copyOf(Objects.requireNonNull(inputsByRole, "inputsByRole"));
}
}
@@ -1,4 +1,4 @@
package p.studio.workspaces.assets;
package p.studio.workspaces.assets.messages;
public enum AssetWorkspaceAssetState {
REGISTERED,

Some files were not shown because too many files have changed in this diff Show More