Edit procedural objects from the studio bridge

New routes scene-file, scene-edit and scene-write read an editable
entry's file as nodes with the schema types its forms need, apply graph
edits (set, unset, append, add item, delete, duplicate, move) keeping the
file's formatting, and write whole texts back for undo. An edit made on
an older revision is refused with 409. Edits are refused with 403
outside a studio world, which alone hotloads its pack. Files are
written beside themselves and moved over, so the pack watcher never
reads one half written.
This commit is contained in:
piexel committed 2026-11-06 05:06:25 +01:00
1 parent 7eff4d0754
commit db2962a25e
10 files changed
+858 -9

No files matched your search

@@ -0,0 +1,94 @@
/*
* 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.bridge;
import art.arcane.iris.core.studio.scene.GraphEdit;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.volmit.tooling.JsonPath;
import java.util.ArrayList;
import java.util.List;
/**
* The body of an edit the studio sends, read into a {@link GraphEdit}:
* <pre>
* {"revision": "…", "edit": {"op": "set", "object": ["parts", 0, "stem"], "key": "length", "literal": "6"}}
* </pre>
* Ops: {@code set} (object, key, literal), {@code unset} (object, key), {@code append} (list, literal), {@code addItem}
* (list), {@code delete} (path), {@code duplicate} (path), {@code move} (path, toList).
*/
record GraphEditRequest(String revision, GraphEdit edit) {
/** @throws IllegalArgumentException naming what is missing or wrong */
static GraphEditRequest parse(String body) {
JsonObject root = object(JsonParser.parseString(body), "The body");
JsonObject edit = object(root.get("edit"), "edit");
GraphEdit parsed = switch (text(edit, "op")) {
case "set" -> new GraphEdit.Set(path(edit, "object"), text(edit, "key"), text(edit, "literal"));
case "unset" -> new GraphEdit.Unset(path(edit, "object"), text(edit, "key"));
case "append" -> new GraphEdit.Append(path(edit, "list"), text(edit, "literal"));
case "addItem" -> new GraphEdit.AddItem(path(edit, "list"));
case "delete" -> new GraphEdit.Delete(path(edit, "path"));
case "duplicate" -> new GraphEdit.Duplicate(path(edit, "path"));
case "move" -> new GraphEdit.Move(path(edit, "path"), path(edit, "toList"));
default -> throw new IllegalArgumentException("Unknown edit: " + text(edit, "op"));
};
return new GraphEditRequest(text(root, "revision"), parsed);
}
/** A whole-file write, as undoing and redoing send it: {@code {"revision": "…", "text": "…"}}. */
record FileWrite(String revision, String text) {
static FileWrite parse(String body) {
JsonObject root = object(JsonParser.parseString(body), "The body");
return new FileWrite(GraphEditRequest.text(root, "revision"), GraphEditRequest.text(root, "text"));
}
}
private static JsonObject object(JsonElement element, String name) {
if (element == null || !element.isJsonObject()) {
throw new IllegalArgumentException(name + " must be a JSON object");
}
return element.getAsJsonObject();
}
private static String text(JsonObject object, String key) {
JsonElement value = object.get(key);
if (value == null || !value.isJsonPrimitive() || !value.getAsJsonPrimitive().isString()) {
throw new IllegalArgumentException(key + " must be a string");
}
return value.getAsString();
}
private static JsonPath path(JsonObject object, String key) {
if (!(object.get(key) instanceof JsonArray steps)) {
throw new IllegalArgumentException(key + " must be an array of member names and indices");
}
List<Object> path = new ArrayList<>();
for (JsonElement step : steps) {
if (!(step instanceof JsonPrimitive primitive)) {
throw new IllegalArgumentException(key + " holds " + step + ", not a name or an index");
}
path.add(primitive.isNumber() ? Integer.valueOf(primitive.getAsInt()) : primitive.getAsString());
}
return new JsonPath(path);
}
}
@@ -33,6 +33,7 @@ import art.arcane.iris.core.studio.saved.SavedBiomeLabels;
import art.arcane.iris.core.studio.saved.SavedTile;
import art.arcane.iris.core.studio.saved.SavedWorld;
import art.arcane.iris.core.studio.saved.SavedWorlds;
import art.arcane.iris.core.studio.scene.StudioEditors;
import art.arcane.iris.core.studio.scene.StudioPatterns;
import art.arcane.iris.core.studio.scene.StudioScenes;
import art.arcane.iris.engine.framework.Engine;
@@ -42,6 +43,7 @@ import art.arcane.iris.spi.IrisLogging;
import art.arcane.volmlib.util.function.NoiseProvider;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonParseException;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
@@ -94,6 +96,8 @@ public final class StudioBridge implements AutoCloseable {
private static final int TOKEN_BYTES = 24;
private static final int DEFAULT_TILE_SIZE = 128;
private static final int LARGEST_TILE_SIZE = 512;
// A procedural object's file is a few kilobytes; this leaves room for any pack file without holding a flood.
private static final int LARGEST_BODY_BYTES = 4 * 1024 * 1024;
private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D;
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
// Each pixel reads the chunk it lands in, so a saved world is shown no farther out than a pixel per chunk.
@@ -107,8 +111,10 @@ public final class StudioBridge implements AutoCloseable {
private static final int STATUS_NO_CONTENT = 204;
private static final int STATUS_BAD_REQUEST = 400;
private static final int STATUS_UNAUTHORIZED = 401;
private static final int STATUS_FORBIDDEN = 403;
private static final int STATUS_NOT_FOUND = 404;
private static final int STATUS_METHOD_NOT_ALLOWED = 405;
private static final int STATUS_CONFLICT = 409;
private static final int STATUS_UNPROCESSABLE = 422;
private static final int STATUS_SERVER_ERROR = 500;
private static final int STATUS_UNAVAILABLE = 503;
@@ -222,7 +228,10 @@ public final class StudioBridge implements AutoCloseable {
case "picks" -> sendJson(exchange, STATUS_OK, picks(get(exchange).engine(), query));
case "regions" -> sendJson(exchange, STATUS_OK, regions(get(exchange).engine()));
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
case "scenes" -> sendJson(exchange, STATUS_OK, StudioScenes.of(get(exchange).engine()).views());
case "scenes" -> sendJson(exchange, STATUS_OK, sceneViews(get(exchange).engine()));
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-entries" -> sendJson(exchange, STATUS_OK, sceneEntries(get(exchange).engine(), query));
case "scene" -> sendBytes(exchange, "application/octet-stream", scene(get(exchange).engine(), query));
case "saved-worlds" -> sendJson(exchange, STATUS_OK, savedWorlds(exchange));
@@ -322,6 +331,63 @@ public final class StudioBridge implements AutoCloseable {
}
}
private static List<SceneViewInfo> sceneViews(Engine engine) {
StudioEditors editors = StudioEditors.of(engine);
return StudioScenes.of(engine).views().stream()
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), editors.edits(view.id())))
.toList();
}
private static StudioEditors.EditorState sceneFile(Engine engine, Query query) throws IOException {
return editing(() -> StudioEditors.of(engine).read(query.text("view"), query.text("key")));
}
private StudioEditors.EditorState sceneEdit(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
String body = readBody(exchange);
return editing(() -> {
GraphEditRequest request = GraphEditRequest.parse(body);
return StudioEditors.of(engine).edit(query.text("view"), query.text("key"), request.revision(), request.edit());
});
}
private StudioEditors.EditorState sceneWrite(HttpExchange exchange, Query query) throws IOException {
Engine engine = post(exchange).engine();
String body = readBody(exchange);
return editing(() -> {
GraphEditRequest.FileWrite write = GraphEditRequest.FileWrite.parse(body);
return StudioEditors.of(engine).write(query.text("view"), query.text("key"), write.revision(), write.text());
});
}
// 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 {
try {
return task.run();
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
} catch (StudioEditors.StaleEditException stale) {
throw new RequestError(STATUS_CONFLICT, stale.getMessage());
} catch (StudioEditors.EditsLockedException locked) {
throw new RequestError(STATUS_FORBIDDEN, locked.getMessage());
} catch (IllegalArgumentException | JsonParseException refused) {
throw new RequestError(STATUS_UNPROCESSABLE, refused.getMessage());
}
}
@FunctionalInterface
private interface EditorTask {
StudioEditors.EditorState run() throws IOException;
}
private static String readBody(HttpExchange exchange) throws IOException {
byte[] body = exchange.getRequestBody().readNBytes(LARGEST_BODY_BYTES + 1);
if (body.length > LARGEST_BODY_BYTES) {
throw new RequestError(STATUS_BAD_REQUEST, "The body is over " + LARGEST_BODY_BYTES + " bytes");
}
return new String(body, StandardCharsets.UTF_8);
}
private static List<SceneEntry> sceneEntries(Engine engine, Query query) {
try {
return StudioScenes.of(engine).entries(query.text("view"));
@@ -654,6 +720,10 @@ 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. */
private record SceneViewInfo(String id, String label, String description, boolean editable) {
}
private record MessageBody(String message) {
}
@@ -0,0 +1,182 @@
/*
* 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.JsonPath;
import com.volmit.tooling.JsonText;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* One change the studio makes to a file shown as nodes, as the text changes it makes there. Each rewrites only what it
* changes, so the rest of the file keeps its author's layout.
*/
public sealed interface GraphEdit {
/**
* The splices that make the change in {@code source}.
*
* @throws IllegalArgumentException naming why, when the file has nothing there to change
*/
List<JsonText.Splice> splices(JsonText source);
/** Sets member {@code key} of the object at {@code object} to {@code literal}, writing the object when it is missing. */
record Set(JsonPath object, String key, String literal) implements GraphEdit {
public Set {
Objects.requireNonNull(object, "object");
Objects.requireNonNull(key, "key");
if (!JsonText.isValue(literal)) {
throw new IllegalArgumentException(literal + " is not a JSON value");
}
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
if (source.at(object).orElse(null) instanceof JsonText.Obj settings) {
return List.of(source.put(settings, key, literal));
}
if (object.isRoot() || !(object.last() instanceof String member)) {
throw new IllegalArgumentException("Nothing to set " + key + " on at " + object);
}
return new Set(object.parent(), member, "{" + JsonText.quote(key) + ": " + literal + "}").splices(source);
}
}
/** Removes member {@code key} of the object at {@code object}, leaving it at its default. */
record Unset(JsonPath object, String key) implements GraphEdit {
@Override
public List<JsonText.Splice> splices(JsonText source) {
if (!(source.at(object).orElse(null) instanceof JsonText.Obj settings) || settings.member(key).isEmpty()) {
return List.of();
}
return List.of(source.remove(settings, key));
}
}
/** Appends {@code literal} to the array at {@code list}, writing the array when it is missing. */
record Append(JsonPath list, String literal) implements GraphEdit {
public Append {
Objects.requireNonNull(list, "list");
if (!JsonText.isValue(literal)) {
throw new IllegalArgumentException(literal + " is not a JSON value");
}
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
return List.of(appendTo(source, list, literal));
}
}
/** Appends a copy of the last element of the array at {@code list}, so a new item starts out filled in. */
record AddItem(JsonPath list) implements GraphEdit {
@Override
public List<JsonText.Splice> splices(JsonText source) {
if (!(source.at(list).orElse(null) instanceof JsonText.Arr array)) {
throw new IllegalArgumentException("No list at " + list);
}
String copy = array.elements().isEmpty() ? "{}" : source.detachedTextOf(array.elements().getLast());
return List.of(source.append(array, copy));
}
}
/** Deletes the value at {@code path}, and the member holding the array it was in when it was the only element. */
record Delete(JsonPath path) implements GraphEdit {
public Delete {
if (path.isRoot()) {
throw new IllegalArgumentException("The file itself can't be deleted");
}
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
return List.of(removal(source, path));
}
}
/** Appends a copy of the element at {@code path}, with all it holds, to the array holding it. */
record Duplicate(JsonPath path) implements GraphEdit {
public Duplicate {
if (!path.isElement()) {
throw new IllegalArgumentException("Only an element of a list can be duplicated, not " + path);
}
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
JsonText.Value element = source.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path));
if (!(source.at(path.parent()).orElse(null) instanceof JsonText.Arr array)) {
throw new IllegalArgumentException("No list holds " + path);
}
return List.of(source.append(array, source.detachedTextOf(element)));
}
}
/** Moves the element at {@code path}, with all it holds, to the end of the array at {@code toList}. */
record Move(JsonPath path, JsonPath toList) implements GraphEdit {
public Move {
if (!path.isElement()) {
throw new IllegalArgumentException("Only an element of a list can move, not " + path);
}
if (toList.startsWith(path)) {
throw new IllegalArgumentException("A node can't move into itself or into what it holds");
}
if (toList.equals(path.parent())) {
throw new IllegalArgumentException("It is there already");
}
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
String moved = source.detachedTextOf(source.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path)));
List<JsonText.Splice> splices = new ArrayList<>();
splices.add(removal(source, path));
splices.add(appendTo(source, toList, moved));
return splices;
}
}
private static JsonText.Splice appendTo(JsonText source, JsonPath list, String literal) {
if (source.at(list).orElse(null) instanceof JsonText.Arr array) {
return source.append(array, literal);
}
if (list.isRoot() || !(list.last() instanceof String member) || !(source.at(list.parent()).orElse(null) instanceof JsonText.Obj owner)) {
throw new IllegalArgumentException("Nothing can be added at " + list);
}
return source.put(owner, member, "[" + literal + "]");
}
private static JsonText.Splice removal(JsonText source, JsonPath path) {
JsonPath holderPath = path.parent();
JsonText.Value holder = source.at(holderPath).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path));
if (path.last() instanceof String key && holder instanceof JsonText.Obj object) {
return source.remove(object, key);
}
if (!(path.last() instanceof Integer index) || !(holder instanceof JsonText.Arr array) || index >= array.elements().size()) {
throw new IllegalArgumentException("Nothing at " + path);
}
boolean onlyElement = array.elements().size() == 1;
if (onlyElement && !holderPath.isRoot() && holderPath.last() instanceof String key
&& source.at(holderPath.parent()).orElse(null) instanceof JsonText.Obj owner) {
return source.remove(owner, key);
}
return source.removeElement(array, index);
}
}
@@ -0,0 +1,23 @@
/*
* 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;
/** A studio view a module registered, as the studio lists it. */
public record ModuleViewInfo(String id, String label, String description) {
}
@@ -48,9 +48,9 @@ final class ModuleViews<V extends StudioView> {
return new ModuleViews<>(ofKind, kind, kindName, engine.getGeneration().world());
}
List<ViewInfo> infos() {
List<ModuleViewInfo> infos() {
return registrations.stream()
.map(registration -> new ViewInfo(registration.view().id().toString(), registration.view().label(), registration.view().description()))
.map(registration -> new ModuleViewInfo(registration.view().id().toString(), registration.view().label(), registration.view().description()))
.toList();
}
@@ -74,8 +74,4 @@ final class ModuleViews<V extends StudioView> {
PackWorld world() {
return world;
}
/** A studio view as the studio lists it. */
public record ViewInfo(String id, String label, String description) {
}
}
@@ -0,0 +1,126 @@
/*
* 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.host.schema.ObjectType;
import com.volmit.host.schema.PackSchema;
import com.volmit.host.schema.SchemaOption;
import com.volmit.host.schema.ValueKind;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.Deque;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
/**
* The settings types of the pack's schema a node graph shows, and every type they hold, as the studio reads them: each
* setting with its kind, description, limits and default, so the studio builds and checks its forms from them.
*/
final class SchemaTypes {
private SchemaTypes() {
}
/** {@code roots} and the types inside them, by name; a name the schema does not know is left out. */
static Map<String, TypeWire> reachableFrom(PackSchema schema, Collection<String> roots) {
Map<String, TypeWire> described = new LinkedHashMap<>();
Deque<String> pending = new ArrayDeque<>(roots);
while (!pending.isEmpty()) {
String name = pending.pop();
if (described.containsKey(name)) {
continue;
}
ObjectType type;
try {
type = schema.type(name);
} catch (NoSuchElementException unknown) {
continue;
}
described.put(name, new TypeWire(type.description(), type.options().stream().map(option -> optionOf(option, pending)).toList()));
}
return described;
}
private static OptionWire optionOf(SchemaOption option, Deque<String> pending) {
return new OptionWire(option.name(), option.description(), option.required(),
option.minimum().isPresent() ? option.minimum().getAsDouble() : null,
option.maximum().isPresent() ? option.maximum().getAsDouble() : null,
option.minItems().isPresent() ? option.minItems().getAsInt() : null,
option.defaultValue().orElse(null),
kindOf(option.kind(), pending));
}
@SuppressWarnings("removal")
private static Map<String, Object> kindOf(ValueKind kind, Deque<String> pending) {
Map<String, Object> wire = new LinkedHashMap<>();
switch (kind) {
case ValueKind.BooleanKind ignored -> wire.put("kind", "boolean");
case ValueKind.IntegerKind ignored -> wire.put("kind", "integer");
case ValueKind.DecimalKind ignored -> wire.put("kind", "decimal");
case ValueKind.TextKind text -> {
wire.put("kind", "text");
wire.put("format", text.format().name());
}
case ValueKind.ReferenceKind reference -> {
wire.put("kind", "reference");
wire.put("reference", reference.reference().name());
wire.put("format", reference.format().name());
}
case ValueKind.ResourceReferenceKind resource -> {
wire.put("kind", "resource");
wire.put("resource", resource.kind().toString());
}
case ValueKind.EnumKind enumKind -> {
wire.put("kind", "enum");
wire.put("constants", enumKind.constants().stream().map(constant -> Map.of("name", constant.name(), "description", constant.description())).toList());
}
case ValueKind.ListKind list -> {
wire.put("kind", "list");
wire.put("element", kindOf(list.element(), pending));
wire.put("unique", list.unique());
}
case ValueKind.MapKind map -> {
wire.put("kind", "map");
wire.put("value", kindOf(map.value(), pending));
}
case ValueKind.ObjectKind object -> {
pending.add(object.type());
wire.put("kind", "object");
wire.put("type", object.type());
}
case ValueKind.HostKind host -> {
wire.put("kind", "host");
wire.put("type", host.type());
}
case ValueKind.AnyKind ignored -> wire.put("kind", "any");
}
return wire;
}
/** A settings type: what it is for, and the settings a file of it may write. */
record TypeWire(String description, List<OptionWire> options) {
}
/** One setting; a limit or default the schema does not give is null. */
record OptionWire(String name, String description, boolean required, Double minimum, Double maximum, Integer minItems,
Object defaultValue, Map<String, Object> kind) {
}
}
@@ -0,0 +1,241 @@
/*
* 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 art.arcane.iris.engine.framework.Engine;
import com.volmit.host.schema.PackSchema;
import com.volmit.tooling.EditableSceneView;
import com.volmit.tooling.GraphNode;
import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
import com.volmit.tooling.NodeGraph;
import com.volmit.tooling.SceneFile;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* The editable scene views of an engine's pack: an entry's file as nodes, and the edits the studio makes to it. The
* studio reads and writes the file here, modules never do; a studio world reloads the pack when the file changes.
*/
public final class StudioEditors {
private static final String FILE_EXTENSION = ".json";
// The pack watcher ignores .tmp files.
private static final String WRITING_SUFFIX = ".tmp";
// Only a studio world reloads its pack when a file changes; elsewhere an edit would show nothing until a restart.
private static final String LOCKED_OUTSIDE_STUDIO = "Open the pack in a studio world to edit it";
private final ModuleViews<EditableSceneView> views;
private final Path packFolder;
private final PackSchema schema;
private final boolean studioWorld;
private StudioEditors(ModuleViews<EditableSceneView> views, Path packFolder, PackSchema schema, boolean studioWorld) {
this.views = views;
this.packFolder = packFolder;
this.schema = schema;
this.studioWorld = studioWorld;
}
public static StudioEditors of(Engine engine) {
return new StudioEditors(ModuleViews.of(engine, EditableSceneView.class, "editable scene view"),
engine.getData().getDataFolder().toPath().toAbsolutePath().normalize(), engine.getData().getModules().pack().schema(),
engine.isStudio());
}
/** Whether {@code viewId} is a scene view whose entries can be edited as nodes. */
public boolean edits(String viewId) {
return views.infos().stream().anyMatch(info -> info.id().equals(viewId));
}
/**
* The entry's file as it is now.
*
* @throws NoSuchElementException when there is no such view, or the entry has no file of its own
*/
public EditorState read(String viewId, String key) throws IOException {
Path file = fileOf(viewId, key);
return stateOf(viewId, key, file, Files.readString(file, StandardCharsets.UTF_8));
}
/**
* Makes {@code edit} and saves the file.
*
* @param revision the {@link EditorState#revision()} the edit was made on
* @throws StaleEditException when the file changed since {@code revision}
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException naming why, when the edit does not fit the file
*/
public EditorState edit(String viewId, String key, String revision, GraphEdit edit) throws IOException {
requireStudioWorld();
Path file = fileOf(viewId, key);
String text = currentText(file, revision);
JsonText source = JsonText.parse(text);
String edited = source.apply(edit.splices(source));
JsonText.parse(edited);
return save(viewId, key, file, edited);
}
/**
* Replaces the whole file, as undoing and redoing do.
*
* @throws StaleEditException when the file changed since {@code revision}
* @throws EditsLockedException when the world is not a studio world
* @throws IllegalArgumentException when {@code text} is not JSON
*/
public EditorState write(String viewId, String key, String revision, String text) throws IOException {
requireStudioWorld();
Path file = fileOf(viewId, key);
currentText(file, revision);
JsonText.parse(text);
return save(viewId, key, file, text);
}
private void requireStudioWorld() {
if (!studioWorld) {
throw new EditsLockedException(LOCKED_OUTSIDE_STUDIO);
}
}
private String lockedReason() {
return studioWorld ? null : LOCKED_OUTSIDE_STUDIO;
}
private String currentText(Path file, String revision) throws IOException {
String text = Files.readString(file, StandardCharsets.UTF_8);
if (!revisionOf(text).equals(revision)) {
throw new StaleEditException();
}
return text;
}
// Written beside the file and moved over it, so the pack watcher never reads it half written.
private EditorState save(String viewId, String key, Path file, String text) throws IOException {
Path written = file.resolveSibling(file.getFileName() + WRITING_SUFFIX);
Files.writeString(written, text, StandardCharsets.UTF_8);
Files.move(written, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
return stateOf(viewId, key, file, text);
}
private Path fileOf(String viewId, String key) {
SceneFile sceneFile = views.ask(viewId, "find the file of " + key, view -> view.fileOf(views.world(), key))
.orElseThrow(() -> new NoSuchElementException("Entry " + key + " has no file to edit"));
if (!sceneFile.id().namespace().equals(views.world().resources().packId().namespace())) {
throw new NoSuchElementException("Entry " + key + " is written in another pack, " + sceneFile.id().namespace());
}
Path file = packFolder.resolve(sceneFile.kind().folder()).resolve(sceneFile.id().path() + FILE_EXTENSION).normalize();
if (!file.startsWith(packFolder) || !Files.isRegularFile(file)) {
throw new NoSuchElementException("Entry " + key + " has no file at " + packFolder.relativize(file));
}
return file;
}
// A file that is no longer JSON, or that the view can't read as nodes, is still shown, with why.
private EditorState stateOf(String viewId, String key, Path file, String text) {
String fileName = packFolder.relativize(file).toString().replace('\\', '/');
JsonText source;
try {
source = JsonText.parse(text);
} catch (IllegalArgumentException notJson) {
return new EditorState(fileName, revisionOf(text), text, null, notJson.getMessage(), lockedReason(), Map.of());
}
NodeGraph graph;
try {
graph = views.ask(viewId, "read " + key + " as nodes", view -> view.graph(views.world(), key, source));
} catch (IllegalStateException refused) {
Throwable reason = refused.getCause() == null ? refused : refused.getCause();
return new EditorState(fileName, revisionOf(text), text, null, String.valueOf(reason.getMessage()), lockedReason(), Map.of());
}
Set<String> typeNames = new LinkedHashSet<>();
List<NodeWire> roots = graph.roots().stream().map(root -> NodeWire.of(root, typeNames)).toList();
return new EditorState(fileName, revisionOf(text), text, roots, null, lockedReason(), SchemaTypes.reachableFrom(schema, typeNames));
}
static String revisionOf(String text) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException missing) {
throw new IllegalStateException("The JVM has no SHA-256", missing);
}
}
/**
* An entry's file as the studio shows it.
*
* @param file where it is below the pack folder
* @param revision tells this text from any other, so an edit made on an older one is refused
* @param roots the file as nodes; null when it can't be read as nodes, and {@code problem} says why
* @param locked why the file can't be edited here; null when it can
* @param types the settings types the nodes show, by name
*/
public record EditorState(String file, String revision, String text, List<NodeWire> roots, String problem, String locked,
Map<String, SchemaTypes.TypeWire> types) {
}
/** A {@link GraphNode} as the studio reads it: paths as arrays of steps, and settings types by their schema name. */
public record NodeWire(String kind, String title, List<Object> path, int partId, List<String> roles, List<SettingsWire> settings,
List<LinkWire> children, List<Object> childList, boolean movable, boolean duplicable, List<AdditionWire> additions) {
static NodeWire of(GraphNode node, Set<String> typeNames) {
List<SettingsWire> settings = node.settings().stream().map(section -> {
typeNames.add(section.type().getName());
return new SettingsWire(section.title(), section.path().steps(), section.type().getName(), List.copyOf(section.shownAsNodes()));
}).toList();
List<LinkWire> children = node.children().stream().map(link -> new LinkWire(link.wire(), of(link.node(), typeNames))).toList();
List<AdditionWire> additions = node.additions().stream()
.map(addition -> new AdditionWire(addition.label(), addition.list().steps(), addition.literal()))
.toList();
return new NodeWire(node.kind(), node.title(), node.path().steps(), node.partId(), node.roles(), settings, children,
node.childList().map(JsonPath::steps).orElse(null), node.movable(), node.path().isElement(), additions);
}
}
public record SettingsWire(String title, List<Object> path, String type, List<String> shownAsNodes) {
}
public record LinkWire(String wire, NodeWire node) {
}
public record AdditionWire(String label, List<Object> list, String literal) {
}
/** The file changed since the text an edit was made on, such as in a text editor. */
public static final class StaleEditException extends RuntimeException {
StaleEditException() {
super("The file changed elsewhere; it was read again");
}
}
/** Edits are refused where the world would not show them, naming why. */
public static final class EditsLockedException extends RuntimeException {
EditsLockedException(String reason) {
super(reason);
}
}
}
@@ -40,7 +40,7 @@ public final class StudioPatterns {
return new StudioPatterns(ModuleViews.of(engine, PatternView.class, "pattern view"));
}
public List<ModuleViews.ViewInfo> views() {
public List<ModuleViewInfo> views() {
return views.infos();
}
@@ -39,7 +39,7 @@ public final class StudioScenes {
return new StudioScenes(ModuleViews.of(engine, SceneView.class, "scene view"));
}
public List<ModuleViews.ViewInfo> views() {
public List<ModuleViewInfo> views() {
return views.infos();
}
@@ -0,0 +1,117 @@
package art.arcane.iris.core.studio.scene;
import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class GraphEditTest {
private static final String TREE = """
{
"parts": [
{
"stem": {"length": 20},
"children": [
{
"blob": {"radius": 3}
},
{
"stem": {"length": 4},
"children": [
{"blob": {"radius": 1}}
]
}
]
}
]
}
""";
private static JsonText edited(GraphEdit edit) {
JsonText source = JsonText.parse(TREE);
return JsonText.parse(source.apply(edit.splices(source)));
}
private static String textAt(JsonText source, Object... steps) {
return source.textOf(source.at(JsonPath.of(steps)).orElseThrow());
}
@Test
public void aNewPartGrowsFromItsParentInAListWrittenForIt() {
JsonText result = edited(new GraphEdit.Append(JsonPath.of("parts", 0, "children", 0, "children"), "{\"stem\": {\"length\": 6}}"));
assertEquals("6", textAt(result, "parts", 0, "children", 0, "children", 0, "stem", "length"));
}
@Test
public void deletingTheOnlyChildDropsItsList() {
JsonText result = edited(new GraphEdit.Delete(JsonPath.of("parts", 0, "children", 1, "children", 0)));
assertTrue(result.at(JsonPath.of("parts", 0, "children", 1, "children")).isEmpty());
assertEquals("4", textAt(result, "parts", 0, "children", 1, "stem", "length"));
}
@Test
public void aMovedPartTakesWhatGrowsFromItAlong() {
JsonText result = edited(new GraphEdit.Move(JsonPath.of("parts", 0, "children", 1), JsonPath.of("parts", 0, "children", 0, "children")));
assertEquals(1, ((JsonText.Arr) result.at(JsonPath.of("parts", 0, "children")).orElseThrow()).elements().size());
assertEquals("1", textAt(result, "parts", 0, "children", 0, "children", 0, "children", 0, "blob", "radius"));
}
@Test
public void aMovedPartIsIndentedForItsNewPlace() {
JsonText source = JsonText.parse(TREE);
String result = source.apply(new GraphEdit.Move(JsonPath.of("parts", 0, "children", 1), JsonPath.of("parts")).splices(source));
assertTrue(result, result.contains("""
},
{
"stem": {"length": 4},
"children": [
{"blob": {"radius": 1}}
]
}
]
}"""));
}
@Test
public void aDuplicateJoinsTheSameListWithWhatGrowsFromIt() {
JsonText result = edited(new GraphEdit.Duplicate(JsonPath.of("parts", 0, "children", 1)));
assertEquals(3, ((JsonText.Arr) result.at(JsonPath.of("parts", 0, "children")).orElseThrow()).elements().size());
assertEquals("1", textAt(result, "parts", 0, "children", 2, "children", 0, "blob", "radius"));
}
@Test
public void settingWritesTheMemberAndAnObjectThatIsMissing() {
JsonText lean = edited(new GraphEdit.Set(JsonPath.of("parts", 0, "stem"), "lean", "7"));
JsonText offset = edited(new GraphEdit.Set(JsonPath.of("parts", 0, "offset"), "y", "2"));
assertEquals("7", textAt(lean, "parts", 0, "stem", "lean"));
assertEquals("2", textAt(offset, "parts", 0, "offset", "y"));
}
@Test
public void unsettingWhatIsNotWrittenChangesNothing() {
JsonText source = JsonText.parse(TREE);
assertTrue(new GraphEdit.Unset(JsonPath.of("parts", 0, "stem"), "lean").splices(source).isEmpty());
assertTrue(edited(new GraphEdit.Unset(JsonPath.of("parts", 0, "stem"), "length")).at(JsonPath.of("parts", 0, "stem", "length")).isEmpty());
}
@Test
public void aPartCanNotMoveIntoItselfOrWhereItIs() {
JsonPath part = JsonPath.of("parts", 0, "children", 1);
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(part, part.member("children")));
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(part, JsonPath.of("parts", 0, "children")));
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(JsonPath.of("parts", 0, "branches", "part"), JsonPath.of("parts")));
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Set(JsonPath.ROOT, "variants", "eight"));
}
}