Create and delete procedural objects from the studio's entry list

A view's entries can now be created from a starter tree in a chosen folder and deleted from the browser. Deleting lists the pack files that still name the entry, then moves it to the desktop trash, or the pack's .iris/trash where there is none. An EditableSceneView opts in with SceneCreation; the host does the writing.

v3: d6e6fc3ef
This commit is contained in:
piexel committed 2026-11-10 13:42:30 +01:00
1 parent 7eb45cebf6
commit 3c03bba7e7
19 files changed
+760 -32

No files matched your search

@@ -237,6 +237,9 @@ public final class StudioBridge implements AutoCloseable {
case "scene-file" -> sendJson(exchange, STATUS_OK, sceneFile(get(exchange).engine(), query));
case "scene-edit" -> sendJson(exchange, STATUS_OK, sceneEdit(exchange, query));
case "scene-write" -> sendJson(exchange, STATUS_OK, sceneWrite(exchange, query));
case "scene-create" -> sendJson(exchange, STATUS_OK, sceneCreate(exchange, query));
case "scene-uses" -> sendJson(exchange, STATUS_OK, sceneUses(get(exchange).engine(), query));
case "scene-delete" -> sendJson(exchange, STATUS_OK, sceneDelete(exchange, query));
case "suggestions" -> sendJson(exchange, STATUS_OK, suggestions(get(exchange).engine(), query));
case "scene-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query));
case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query));
@@ -343,7 +346,7 @@ public final class StudioBridge implements AutoCloseable {
StudioEditors editors = StudioEditors.of(engine);
StudioScenes scenes = StudioScenes.of(engine);
return scenes.views().stream()
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id())))
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id()), editors.edits(view.id()) && editors.creates(view.id()), scenes.isBaked(view.id()), scenes.hasParts(view.id())))
.toList();
}
@@ -369,8 +372,25 @@ public final class StudioBridge implements AutoCloseable {
});
}
private MessageBody sceneCreate(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
return editing(() -> {
StudioEditors.of(engine).create(query.text("view"), query.text("key"));
return new MessageBody("Created " + query.text("key"));
});
}
private static UsesBody sceneUses(Engine engine, Query query) throws IOException {
return editing(() -> new UsesBody(StudioEditors.of(engine).usesOf(query.text("view"), query.text("key"))));
}
private TrashedBody sceneDelete(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
return editing(() -> new TrashedBody(StudioEditors.of(engine).delete(query.text("view"), query.text("key"))));
}
// A refused edit is the user's to fix, so it answers with why rather than as a failure of the bridge.
private static StudioEditors.EditorState editing(EditorTask task) throws IOException {
private static <T> T editing(EditorTask<T> task) throws IOException {
try {
return task.run();
} catch (NoSuchElementException unknown) {
@@ -385,8 +405,8 @@ public final class StudioBridge implements AutoCloseable {
}
@FunctionalInterface
private interface EditorTask {
StudioEditors.EditorState run() throws IOException;
private interface EditorTask<T> {
T run() throws IOException;
}
private static String readBody(HttpExchange exchange) throws IOException {
@@ -783,8 +803,14 @@ public final class StudioBridge implements AutoCloseable {
private record ErrorBody(String error) {
}
/** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */
private record SceneViewInfo(String id, String label, String description, boolean editable, boolean baked, boolean parts) {
/** A scene view as the studio lists it; {@code editable} when its entries can be edited as nodes, {@code creatable} when they can also be created and deleted, {@code baked} when their bake can be timed, {@code parts} when the blocks of a scene can be told by the part that placed them. */
private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked, boolean parts) {
}
private record UsesBody(List<String> files) {
}
private record TrashedBody(String to) {
}
/** A {@link SceneEntry} as the studio reads it, with a blank group for none. */
@@ -0,0 +1,157 @@
/*
* Iris is a World Generator for Minecraft Servers
* Copyright (c) 2026 Arcane Arts (Volmit Software)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package art.arcane.iris.core.studio.scene;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.SceneCreation;
import java.awt.Desktop;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.regex.Pattern;
/**
* Creates the files of a scene view's entries and removes them safely: a new entry starts from the view's starter text,
* what still names an entry is found before it goes, and a removed entry goes to the trash rather than away for good.
* Keys are confined to folder-safe names, so no file outside the kind's folder of the pack is ever touched.
*/
final class SceneFiles {
private static final Pattern KEY = Pattern.compile("[a-z0-9_-]+(/[a-z0-9_-]+)*");
private static final String FILE_EXTENSION = ".json";
private static final String WRITING_SUFFIX = ".tmp";
private static final String GENERATED_FOLDER_PREFIX = ".";
private static final String PACK_TRASH = ".iris/trash";
private static final String DESKTOP_TRASH = "the trash";
/** Where the desktop moves a file to its trash; absent a desktop it moves nothing. */
@FunctionalInterface
interface DesktopTrash {
/** @return whether the desktop took {@code file} to its trash */
boolean take(Path file);
}
private final Path packFolder;
private final SceneCreation creation;
private final DesktopTrash desktopTrash;
SceneFiles(Path packFolder, SceneCreation creation, DesktopTrash desktopTrash) {
this.packFolder = packFolder;
this.creation = creation;
this.desktopTrash = desktopTrash;
}
static DesktopTrash systemTrash() {
return file -> Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.MOVE_TO_TRASH)
&& Desktop.getDesktop().moveToTrash(file.toFile());
}
/** @return why {@code key} can't name an entry, or null when it can */
static String refusalOfKey(String key) {
if (key.isBlank()) {
return "Give it a name";
}
return KEY.matcher(key).matches() ? null : "Use lower case letters, digits, - and _, with / between folders";
}
Path fileOf(String key) {
String refusal = refusalOfKey(key);
if (refusal != null) {
throw new IllegalArgumentException(refusal);
}
return packFolder.resolve(creation.kind().folder()).resolve(key + FILE_EXTENSION);
}
/**
* Writes a new entry from the starter text at {@code key}.
*
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry or the starter is not JSON
*/
Path create(String key) throws IOException {
Path file = fileOf(key);
if (Files.exists(file)) {
throw new IllegalArgumentException(key + " already exists");
}
JsonText.parse(creation.starter());
Files.createDirectories(file.getParent());
Path written = file.resolveSibling(file.getFileName() + WRITING_SUFFIX);
Files.writeString(written, creation.starter(), StandardCharsets.UTF_8);
Files.move(written, file, StandardCopyOption.ATOMIC_MOVE);
return file;
}
/**
* The pack's files that name the entry at {@code key}, such as the biomes that place it, below the pack. Folders
* starting with a dot hold what the studio generates, like the schema, and are left out.
*/
List<String> usesOf(String key) throws IOException {
String reference = "\"" + creation.referencePrefix() + key + "\"";
Path own = fileOf(key);
List<String> using = new ArrayList<>();
Files.walkFileTree(packFolder, new SimpleFileVisitor<>() {
@Override
public FileVisitResult preVisitDirectory(Path folder, BasicFileAttributes attributes) {
boolean generated = !folder.equals(packFolder) && folder.getFileName().toString().startsWith(GENERATED_FOLDER_PREFIX);
return generated ? FileVisitResult.SKIP_SUBTREE : FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
if (!file.equals(own) && file.getFileName().toString().endsWith(FILE_EXTENSION) && namesIn(file, reference)) {
using.add(packFolder.relativize(file).toString().replace('\\', '/'));
}
return FileVisitResult.CONTINUE;
}
});
using.sort(null);
return using;
}
private static boolean namesIn(Path file, String reference) throws IOException {
return new String(Files.readAllBytes(file), StandardCharsets.UTF_8).contains(reference);
}
/**
* Moves the entry at {@code key} to the desktop's trash, or where the desktop has none, to the pack's
* {@code .iris/trash}; returns where it went, to tell.
*
* @throws NoSuchElementException when the entry has no file
*/
String moveToTrash(String key) throws IOException {
Path file = fileOf(key);
if (!Files.isRegularFile(file)) {
throw new NoSuchElementException("Entry " + key + " has no file at " + packFolder.relativize(file));
}
if (desktopTrash.take(file)) {
return DESKTOP_TRASH;
}
Path trashed = packFolder.resolve(PACK_TRASH).resolve(key.replace('/', '_') + "-" + System.currentTimeMillis() + FILE_EXTENSION);
Files.createDirectories(trashed.getParent());
Files.move(file, trashed);
return PACK_TRASH;
}
}
@@ -25,6 +25,7 @@ import com.volmit.tooling.GraphNode;
import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.NodeGraph;
import com.volmit.tooling.SceneCreation;
import com.volmit.tooling.SceneFile;
import java.io.IOException;
@@ -118,6 +119,49 @@ public final class StudioEditors {
return save(viewId, key, file, text);
}
/** Whether entries of {@code viewId} can be created and removed from the studio. */
public boolean creates(String viewId) {
return views.ask(viewId, "tell whether entries are created", view -> view.creation().isPresent());
}
/**
* Writes a new entry {@code key} of the view from its starter text. The entry shows once the pack has reloaded.
*
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException naming why, when {@code key} can't name a new entry
* @throws NoSuchElementException when there is no such view, or its entries can't be created
*/
public void create(String viewId, String key) throws IOException {
requireStudioWorld();
files(viewId).create(key);
}
/**
* The files of the pack that still name entry {@code key}, which a removal would leave without it.
*
* @throws NoSuchElementException when there is no such view, or its entries can't be removed
*/
public List<String> usesOf(String viewId, String key) throws IOException {
return files(viewId).usesOf(key);
}
/**
* Moves entry {@code key} to the trash and tells where it went.
*
* @throws EditsLockedException when the world is not a studio world
* @throws NoSuchElementException when there is no such view, or the entry has no file
*/
public String delete(String viewId, String key) throws IOException {
requireStudioWorld();
return files(viewId).moveToTrash(key);
}
private SceneFiles files(String viewId) {
SceneCreation creation = views.ask(viewId, "tell how entries are created", EditableSceneView::creation)
.orElseThrow(() -> new NoSuchElementException("The entries of " + viewId + " can't be created or removed"));
return new SceneFiles(packFolder, creation, SceneFiles.systemTrash());
}
private void requireStudioWorld() {
if (!studioWorld) {
throw new EditsLockedException(LOCKED_OUTSIDE_STUDIO);
@@ -0,0 +1,131 @@
package art.arcane.iris.core.studio.scene;
import art.arcane.iris.core.modules.JsonFormsCodecs;
import art.arcane.iris.engine.procedural.ProceduralObjectCatalog;
import art.arcane.iris.engine.procedural.part.PartOutline;
import art.arcane.iris.engine.procedural.part.ProceduralObject;
import art.arcane.iris.modules.objects.ProceduralObjectScenes;
import com.google.gson.GsonBuilder;
import com.volmit.tooling.SceneCreation;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class SceneFilesTest {
private static final SceneCreation CREATION = new ProceduralObjectScenes().creation().orElseThrow();
@Rule
public TemporaryFolder temporary = new TemporaryFolder();
private SceneFiles files(Path pack, SceneFiles.DesktopTrash trash) {
return new SceneFiles(pack, CREATION, trash);
}
@Test
public void keysMustBePlainFolderSafeNames() {
assertEquals(null, SceneFiles.refusalOfKey("trees/oak-2"));
assertEquals("Give it a name", SceneFiles.refusalOfKey(" "));
for (String key : List.of("Trees/Oak", "trees//oak", "/oak", "oak/", "../oak", "trees/../oak", "oak.json", "trees\\oak")) {
assertTrue(key, SceneFiles.refusalOfKey(key).startsWith("Use lower case"));
}
}
@Test
public void theStarterIsATreeWithAPartToGrowFrom() {
ProceduralObject tree = new GsonBuilder().registerTypeAdapterFactory(new JsonFormsCodecs()).create().fromJson(CREATION.starter(), ProceduralObject.class);
assertEquals(2, PartOutline.of(tree).nodeCount());
assertEquals(2, tree.materials().size());
}
@Test
public void aNewEntryIsWrittenInTheKindsFolderFromTheStarter() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
Path created = files(pack, file -> false).create("trees/oak");
assertEquals(pack.resolve(ProceduralObjectCatalog.DEFINITIONS.folder()).resolve("trees/oak.json"), created);
assertEquals(CREATION.starter(), Files.readString(created));
try (var folder = Files.list(created.getParent())) {
assertEquals(List.of(created), folder.toList());
}
}
@Test
public void anEntryThatExistsOrHasNoPlainKeyIsNotCreated() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
Path created = files.create("trees/oak");
Files.writeString(created, "{}");
assertEquals("trees/oak already exists", assertThrows(IllegalArgumentException.class, () -> files.create("trees/oak")).getMessage());
assertEquals("{}", Files.readString(created));
assertThrows(IllegalArgumentException.class, () -> files.create("../escape"));
assertFalse(Files.exists(pack.resolveSibling("escape.json")));
}
@Test
public void usesAreTheJsonFilesNamingTheEntryOutsideItsOwnAndGeneratedFolders() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
files.create("trees/oak");
Files.createDirectories(pack.resolve("biomes/temperate"));
Files.writeString(pack.resolve("biomes/temperate/forest.json"), "{\"objects\": [\"procedural/trees/oak\"]}");
Files.writeString(pack.resolve("biomes/plains.json"), "{\"objects\": [\"procedural/trees/oak-tall\"]}");
Files.writeString(pack.resolve("biomes/notes.txt"), "procedural/trees/oak");
Files.createDirectories(pack.resolve(".iris/schema"));
Files.writeString(pack.resolve(".iris/schema/biome.json"), "{\"enum\": [\"procedural/trees/oak\"]}");
assertEquals(List.of("biomes/temperate/forest.json"), files.usesOf("trees/oak"));
}
@Test
public void aDeletedEntryGoesToThePacksTrashWhenTheDesktopHasNone() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> false);
Path created = files.create("trees/oak");
assertEquals(".iris/trash", files.moveToTrash("trees/oak"));
assertFalse(Files.exists(created));
try (var trashed = Files.list(pack.resolve(".iris/trash"))) {
assertTrue(trashed.anyMatch(file -> file.getFileName().toString().startsWith("trees_oak-")));
}
}
@Test
public void aDeletedEntryTheDesktopTookIsLeftToIt() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
SceneFiles files = files(pack, file -> {
try {
Files.delete(file);
} catch (java.io.IOException failed) {
throw new java.io.UncheckedIOException(failed);
}
return true;
});
Path created = files.create("trees/oak");
assertEquals("the trash", files.moveToTrash("trees/oak"));
assertFalse(Files.exists(created));
assertFalse(Files.exists(pack.resolve(".iris/trash")));
}
@Test
public void anEntryWithoutAFileCannotBeDeleted() throws Exception {
Path pack = temporary.newFolder("pack").toPath();
assertThrows(NoSuchElementException.class, () -> files(pack, file -> false).moveToTrash("trees/oak"));
}
}