Splice studio edits in core instead of the API

JsonSplicer holds the text edits JsonText used to carry; GraphEdit works on
it with typed path steps. The bridge maps the API's Optionals to the wire the
studio already reads (-1 for no part or block, a blank group), so the studio
is unchanged.
This commit is contained in:
piexel committed 2026-11-06 06:09:16 +01:00
1 parent c0ac9d7f4e
commit f98d78a87b
9 files changed
+405 -83

No files matched your search

@@ -26,9 +26,6 @@ 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>
@@ -82,13 +79,13 @@ record GraphEditRequest(String revision, GraphEdit edit) {
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<>();
JsonPath path = JsonPath.ROOT;
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());
path = primitive.isNumber() ? path.element(primitive.getAsInt()) : path.member(primitive.getAsString());
}
return new JsonPath(path);
return path;
}
}
@@ -32,18 +32,19 @@ import java.util.List;
* <pre>
* u32 header length | header, UTF-8 JSON | padding to 4 bytes | i16 picks[columns²]
* </pre>
* The header holds the columns across, the blocks between columns, and the block keys the picks index; a pick of
* {@link BlockPattern#NO_BLOCK} is a column the pattern places nothing at.
* The header holds the columns across, the blocks between columns, the block keys the picks index, and the pick
* ({@code noBlock}) of a column the pattern places nothing at.
*/
final class PatternEncoding {
private static final int ALIGNMENT_BYTES = 4;
private static final short NO_BLOCK = -1;
private PatternEncoding() {
}
static byte[] encode(BlockPattern pattern, int blocksPerColumn, Gson gson) {
List<String> blocks = pattern.blocks().stream().map(BlockState::key).toList();
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, blocks, BlockPattern.NO_BLOCK))
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, blocks, NO_BLOCK))
.getBytes(StandardCharsets.UTF_8);
int columns = pattern.columns();
ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + columns * columns * Short.BYTES)
@@ -52,7 +53,7 @@ final class PatternEncoding {
buffer.position(aligned(buffer.position()));
for (int row = 0; row < columns; row++) {
for (int column = 0; column < columns; column++) {
buffer.putShort((short) pattern.pickAt(column, row));
buffer.putShort((short) pattern.pickAt(column, row).orElse(NO_BLOCK));
}
}
return buffer.array();
@@ -390,9 +390,9 @@ public final class StudioBridge implements AutoCloseable {
return new String(body, StandardCharsets.UTF_8);
}
private static List<SceneEntry> sceneEntries(Engine engine, Query query) {
private static List<SceneEntryWire> sceneEntries(Engine engine, Query query) {
try {
return StudioScenes.of(engine).entries(query.text("view"));
return StudioScenes.of(engine).entries(query.text("view")).stream().map(SceneEntryWire::of).toList();
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
}
@@ -409,9 +409,9 @@ public final class StudioBridge implements AutoCloseable {
return SceneEncoding.encode(scene.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No scene " + key)), gson);
}
private static List<PatternEntry> patternEntries(Engine engine, Query query) {
private static List<PatternEntryWire> patternEntries(Engine engine, Query query) {
try {
return StudioPatterns.of(engine).entries(query.text("view"));
return StudioPatterns.of(engine).entries(query.text("view")).stream().map(PatternEntryWire::of).toList();
} catch (NoSuchElementException unknown) {
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
}
@@ -742,6 +742,20 @@ public final class StudioBridge implements AutoCloseable {
private record SceneViewInfo(String id, String label, String description, boolean editable) {
}
/** A {@link SceneEntry} as the studio reads it, with a blank group for none. */
private record SceneEntryWire(String key, String name, String group, int variants) {
static SceneEntryWire of(SceneEntry entry) {
return new SceneEntryWire(entry.key(), entry.name(), entry.group().orElse(""), entry.variants());
}
}
/** A {@link PatternEntry} as the studio reads it, with a blank group for none. */
private record PatternEntryWire(String key, String name, String group, int depths, List<String> facts) {
static PatternEntryWire of(PatternEntry entry) {
return new PatternEntryWire(entry.key(), entry.name(), entry.group().orElse(""), entry.depths(), entry.facts());
}
}
private record MessageBody(String message) {
}
@@ -18,6 +18,7 @@
package art.arcane.iris.core.studio.scene;
import art.arcane.iris.core.studio.scene.JsonSplicer.Splice;
import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
@@ -31,11 +32,11 @@ import java.util.Objects;
*/
public sealed interface GraphEdit {
/**
* The splices that make the change in {@code source}.
* The splices that make the change in {@code file}.
*
* @throws IllegalArgumentException naming why, when the file has nothing there to change
*/
List<JsonText.Splice> splices(JsonText source);
List<Splice> splices(JsonSplicer file);
/** 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 {
@@ -48,25 +49,25 @@ public sealed interface GraphEdit {
}
@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));
public List<Splice> splices(JsonSplicer file) {
if (file.at(object).orElse(null) instanceof JsonText.Obj settings) {
return List.of(file.put(settings, key, literal));
}
if (object.isRoot() || !(object.last() instanceof String member)) {
if (object.isRoot() || !(object.last() instanceof JsonPath.Key(String member))) {
throw new IllegalArgumentException("Nothing to set " + key + " on at " + object);
}
return new Set(object.parent(), member, "{" + JsonText.quote(key) + ": " + literal + "}").splices(source);
return new Set(object.parent(), member, "{" + JsonSplicer.quote(key) + ": " + literal + "}").splices(file);
}
}
/** 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()) {
public List<Splice> splices(JsonSplicer file) {
if (!(file.at(object).orElse(null) instanceof JsonText.Obj settings) || settings.member(key).isEmpty()) {
return List.of();
}
return List.of(source.remove(settings, key));
return List.of(file.remove(settings, key));
}
}
@@ -80,20 +81,20 @@ public sealed interface GraphEdit {
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
return List.of(appendTo(source, list, literal));
public List<Splice> splices(JsonSplicer file) {
return List.of(appendTo(file, 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)) {
public List<Splice> splices(JsonSplicer file) {
if (!(file.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));
String copy = array.elements().isEmpty() ? "{}" : file.detachedTextOf(array.elements().getLast());
return List.of(file.append(array, copy));
}
}
@@ -106,8 +107,8 @@ public sealed interface GraphEdit {
}
@Override
public List<JsonText.Splice> splices(JsonText source) {
return List.of(removal(source, path));
public List<Splice> splices(JsonSplicer file) {
return List.of(removal(file, path));
}
}
@@ -120,12 +121,12 @@ public sealed interface GraphEdit {
}
@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)) {
public List<Splice> splices(JsonSplicer file) {
JsonText.Value element = file.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path));
if (!(file.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)));
return List.of(file.append(array, file.detachedTextOf(element)));
}
}
@@ -144,39 +145,40 @@ public sealed interface GraphEdit {
}
@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));
public List<Splice> splices(JsonSplicer file) {
String moved = file.detachedTextOf(file.at(path).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path)));
List<Splice> splices = new ArrayList<>();
splices.add(removal(file, path));
splices.add(appendTo(file, 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);
private static Splice appendTo(JsonSplicer file, JsonPath list, String literal) {
if (file.at(list).orElse(null) instanceof JsonText.Arr array) {
return file.append(array, literal);
}
if (list.isRoot() || !(list.last() instanceof String member) || !(source.at(list.parent()).orElse(null) instanceof JsonText.Obj owner)) {
if (list.isRoot() || !(list.last() instanceof JsonPath.Key(String member))
|| !(file.at(list.parent()).orElse(null) instanceof JsonText.Obj owner)) {
throw new IllegalArgumentException("Nothing can be added at " + list);
}
return source.put(owner, member, "[" + literal + "]");
return file.put(owner, member, "[" + literal + "]");
}
private static JsonText.Splice removal(JsonText source, JsonPath path) {
private static Splice removal(JsonSplicer file, 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);
JsonText.Value holder = file.at(holderPath).orElseThrow(() -> new IllegalArgumentException("Nothing at " + path));
if (path.last() instanceof JsonPath.Key(String key) && holder instanceof JsonText.Obj object) {
return file.remove(object, key);
}
if (!(path.last() instanceof Integer index) || !(holder instanceof JsonText.Arr array) || index >= array.elements().size()) {
if (!(path.last() instanceof JsonPath.Index(int 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);
if (onlyElement && !holderPath.isRoot() && holderPath.last() instanceof JsonPath.Key(String key)
&& file.at(holderPath.parent()).orElse(null) instanceof JsonText.Obj owner) {
return file.remove(owner, key);
}
return source.removeElement(array, index);
return file.removeElement(array, index);
}
}
@@ -0,0 +1,183 @@
/*
* 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.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* Edits of a {@link JsonText} as splices of its text, so an edit rewrites only the value it changes and the rest of
* the file keeps the layout its author gave it.
*/
public final class JsonSplicer {
private final JsonText source;
public JsonSplicer(JsonText source) {
this.source = Objects.requireNonNull(source, "source");
}
/** {@code plain} as a JSON string literal. */
public static String quote(String plain) {
StringBuilder quoted = new StringBuilder("\"");
for (char character : plain.toCharArray()) {
switch (character) {
case '"' -> quoted.append("\\\"");
case '\\' -> quoted.append("\\\\");
case '\n' -> quoted.append("\\n");
case '\r' -> quoted.append("\\r");
case '\t' -> quoted.append("\\t");
default -> {
if (character < 0x20) {
quoted.append(String.format("\\u%04x", (int) character));
} else {
quoted.append(character);
}
}
}
}
return quoted.append('"').toString();
}
/** The value at {@code path}; empty when the file has none there. */
public Optional<JsonText.Value> at(JsonPath path) {
return source.at(path);
}
/** The text of {@code value}, its later lines indented as if it started a line with no indent. */
public String detachedTextOf(JsonText.Value value) {
return reindented(source.textOf(value), indentOfLine(value.start()), "");
}
public Splice replace(JsonText.Value value, String literal) {
return new Splice(value.start(), value.end(), literal);
}
/** Sets the member, written after the last one in the object's own style when it is new. */
public Splice put(JsonText.Obj object, String key, String literal) {
Optional<JsonText.Member> existing = object.member(key);
if (existing.isPresent()) {
return replace(existing.get().value(), literal);
}
if (object.members().isEmpty()) {
return replace(object, "{" + quote(key) + ": " + reindented(literal, "", indentOfLine(object.start())) + "}");
}
JsonText.Member last = object.members().getLast();
String indent = indentOfLine(last.keyStart());
String entry = quote(key) + ": " + reindented(literal, "", indent);
String separator = isMultiline(object) ? ",\n" + indent : ", ";
return new Splice(last.value().end(), last.value().end(), separator + entry);
}
/** @throws IllegalArgumentException when the object has no member {@code key} */
public Splice remove(JsonText.Obj object, String key) {
List<JsonText.Member> members = object.members();
int index = members.indexOf(object.member(key).orElseThrow(() -> new IllegalArgumentException("No " + key + " to remove")));
if (members.size() == 1) {
return replace(object, "{}");
}
if (index > 0) {
return new Splice(members.get(index - 1).value().end(), members.get(index).value().end(), "");
}
return new Splice(members.getFirst().keyStart(), members.get(1).keyStart(), "");
}
/** Adds an element after the last one, a multi-line one indented to match the array. */
public Splice append(JsonText.Arr array, String literal) {
if (array.elements().isEmpty()) {
return replace(array, "[" + reindented(literal, "", indentOfLine(array.start())) + "]");
}
JsonText.Value last = array.elements().getLast();
String indent = indentOfLine(last.start());
String separator = isMultiline(array) ? ",\n" + indent : ", ";
return new Splice(last.end(), last.end(), separator + reindented(literal, "", indent));
}
public Splice removeElement(JsonText.Arr array, int index) {
List<JsonText.Value> elements = array.elements();
Objects.checkIndex(index, elements.size());
if (elements.size() == 1) {
return replace(array, "[]");
}
if (index > 0) {
return new Splice(elements.get(index - 1).end(), elements.get(index).end(), "");
}
return new Splice(elements.getFirst().start(), elements.get(1).start(), "");
}
/**
* The text with {@code splices} made, each placed by where it was in the source text.
*
* @throws IllegalArgumentException when two splices overlap
*/
public String apply(List<Splice> splices) {
List<Splice> fromLast = new ArrayList<>(splices);
fromLast.sort(Comparator.comparingInt(Splice::start).reversed());
StringBuilder edited = new StringBuilder(source.text());
int earliestStart = Integer.MAX_VALUE;
for (Splice splice : fromLast) {
if (splice.end() > earliestStart) {
throw new IllegalArgumentException("Overlapping edits");
}
edited.replace(splice.start(), splice.end(), splice.replacement());
earliestStart = splice.start();
}
return edited.toString();
}
private boolean isMultiline(JsonText.Value value) {
return source.textOf(value).indexOf('\n') >= 0;
}
// The blanks before the first character on the line holding position.
private String indentOfLine(int position) {
String text = source.text();
int lineStart = text.lastIndexOf('\n', position - 1) + 1;
int indentEnd = lineStart;
while (indentEnd < position && (text.charAt(indentEnd) == ' ' || text.charAt(indentEnd) == '\t')) {
indentEnd++;
}
return text.substring(lineStart, indentEnd);
}
private static String reindented(String literal, String fromIndent, String toIndent) {
String[] lines = literal.split("\n", -1);
StringBuilder result = new StringBuilder(lines[0]);
for (int index = 1; index < lines.length; index++) {
String line = lines[index].startsWith(fromIndent) ? lines[index].substring(fromIndent.length()) : lines[index].stripLeading();
result.append('\n').append(toIndent).append(line);
}
return result.toString();
}
/** Replaces the text from {@code start} up to {@code end} with {@code replacement}. */
public record Splice(int start, int end, String replacement) {
public Splice {
Objects.requireNonNull(replacement, "replacement");
if (start < 0 || end < start) {
throw new IllegalArgumentException("A splice runs forwards from 0, not " + start + " to " + end);
}
}
}
}
@@ -97,8 +97,8 @@ public final class StudioEditors {
requireStudioWorld();
Path file = fileOf(viewId, key);
String text = currentText(file, revision);
JsonText source = JsonText.parse(text);
String edited = source.apply(edit.splices(source));
JsonSplicer splicer = new JsonSplicer(JsonText.parse(text));
String edited = splicer.apply(edit.splices(splicer));
JsonText.parse(edited);
return save(viewId, key, file, edited);
}
@@ -199,20 +199,33 @@ public final class StudioEditors {
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. */
/**
* A {@link GraphNode} as the studio reads it: paths as arrays of member names and indices, a node that draws no
* part as part {@code -1}, 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) {
private static final int NO_PART = -1;
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()));
return new SettingsWire(section.title(), stepsOf(section.path()), 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()))
GraphNode.Edits edits = node.edits();
List<AdditionWire> additions = edits.additions().stream()
.map(addition -> new AdditionWire(addition.label(), stepsOf(addition.list()), 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);
return new NodeWire(node.kind(), node.title(), stepsOf(node.path()), node.part().orElse(NO_PART), node.roles(), settings,
children, edits.childList().map(NodeWire::stepsOf).orElse(null), edits.movable(), node.path().isElement(), additions);
}
static List<Object> stepsOf(JsonPath path) {
return path.steps().stream().<Object>map(step -> switch (step) {
case JsonPath.Key(String name) -> name;
case JsonPath.Index(int position) -> position;
}).toList();
}
}
@@ -4,6 +4,7 @@ import com.volmit.tooling.JsonPath;
import com.volmit.tooling.JsonText;
import org.junit.Test;
import static art.arcane.iris.core.studio.scene.TestPaths.path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
@@ -31,42 +32,42 @@ public class GraphEditTest {
""";
private static JsonText edited(GraphEdit edit) {
JsonText source = JsonText.parse(TREE);
return JsonText.parse(source.apply(edit.splices(source)));
JsonSplicer file = new JsonSplicer(JsonText.parse(TREE));
return JsonText.parse(file.apply(edit.splices(file)));
}
private static String textAt(JsonText source, Object... steps) {
return source.textOf(source.at(JsonPath.of(steps)).orElseThrow());
return source.textOf(source.at(path(steps)).orElseThrow());
}
@Test
public void aNewPartGrowsFromItsParentInAListWrittenForIt() {
JsonText result = edited(new GraphEdit.Append(JsonPath.of("parts", 0, "children", 0, "children"), "{\"stem\": {\"length\": 6}}"));
JsonText result = edited(new GraphEdit.Append(path("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)));
JsonText result = edited(new GraphEdit.Delete(path("parts", 0, "children", 1, "children", 0)));
assertTrue(result.at(JsonPath.of("parts", 0, "children", 1, "children")).isEmpty());
assertTrue(result.at(path("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")));
JsonText result = edited(new GraphEdit.Move(path("parts", 0, "children", 1), path("parts", 0, "children", 0, "children")));
assertEquals(1, ((JsonText.Arr) result.at(JsonPath.of("parts", 0, "children")).orElseThrow()).elements().size());
assertEquals(1, ((JsonText.Arr) result.at(path("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);
JsonSplicer file = new JsonSplicer(JsonText.parse(TREE));
String result = source.apply(new GraphEdit.Move(JsonPath.of("parts", 0, "children", 1), JsonPath.of("parts")).splices(source));
String result = file.apply(new GraphEdit.Move(path("parts", 0, "children", 1), path("parts")).splices(file));
assertTrue(result, result.contains("""
},
@@ -82,16 +83,16 @@ public class GraphEditTest {
@Test
public void aDuplicateJoinsTheSameListWithWhatGrowsFromIt() {
JsonText result = edited(new GraphEdit.Duplicate(JsonPath.of("parts", 0, "children", 1)));
JsonText result = edited(new GraphEdit.Duplicate(path("parts", 0, "children", 1)));
assertEquals(3, ((JsonText.Arr) result.at(JsonPath.of("parts", 0, "children")).orElseThrow()).elements().size());
assertEquals(3, ((JsonText.Arr) result.at(path("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"));
JsonText lean = edited(new GraphEdit.Set(path("parts", 0, "stem"), "lean", "7"));
JsonText offset = edited(new GraphEdit.Set(path("parts", 0, "offset"), "y", "2"));
assertEquals("7", textAt(lean, "parts", 0, "stem", "lean"));
assertEquals("2", textAt(offset, "parts", 0, "offset", "y"));
@@ -99,19 +100,19 @@ public class GraphEditTest {
@Test
public void unsettingWhatIsNotWrittenChangesNothing() {
JsonText source = JsonText.parse(TREE);
JsonSplicer file = new JsonSplicer(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());
assertTrue(new GraphEdit.Unset(path("parts", 0, "stem"), "lean").splices(file).isEmpty());
assertTrue(edited(new GraphEdit.Unset(path("parts", 0, "stem"), "length")).at(path("parts", 0, "stem", "length")).isEmpty());
}
@Test
public void aPartCanNotMoveIntoItselfOrWhereItIs() {
JsonPath part = JsonPath.of("parts", 0, "children", 1);
JsonPath part = path("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.Move(part, path("parts", 0, "children")));
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Move(path("parts", 0, "branches", "part"), path("parts")));
assertThrows(IllegalArgumentException.class, () -> new GraphEdit.Set(JsonPath.ROOT, "variants", "eight"));
}
}
@@ -0,0 +1,94 @@
package art.arcane.iris.core.studio.scene;
import com.volmit.tooling.JsonText;
import org.junit.Test;
import java.util.List;
import static art.arcane.iris.core.studio.scene.TestPaths.path;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
public class JsonSplicerTest {
private static final String TREE = """
{
"variants": 8,
"parts": [
{
"stem": {"length": [16.0, 26.0], "radius": 0.5},
"children": [
{
"blob": {
"radius": 3
}
}
]
}
]
}
""";
private final JsonSplicer file = new JsonSplicer(JsonText.parse(TREE));
@Test
public void replacingAValueKeepsTheRestOfTheText() {
JsonText.Value length = file.at(path("parts", 0, "stem", "length")).orElseThrow();
String edited = file.apply(List.of(file.replace(length, "[12, 20]")));
assertEquals(TREE.replace("[16.0, 26.0]", "[12, 20]"), edited);
}
@Test
public void aNewMemberFollowsAnInlineObjectsStyle() {
JsonText.Obj stem = (JsonText.Obj) file.at(path("parts", 0, "stem")).orElseThrow();
String edited = file.apply(List.of(file.put(stem, "lean", "7")));
assertTrue(edited.contains("\"stem\": {\"length\": [16.0, 26.0], \"radius\": 0.5, \"lean\": 7},"));
}
@Test
public void aNewMemberFollowsAMultilineObjectsStyle() {
JsonText.Obj blob = (JsonText.Obj) file.at(path("parts", 0, "children", 0, "blob")).orElseThrow();
String edited = file.apply(List.of(file.put(blob, "depth", "0")));
assertTrue(edited.contains("\"radius\": 3,\n \"depth\": 0\n"));
}
@Test
public void removingMembersLeavesValidJson() {
JsonText.Obj stem = (JsonText.Obj) file.at(path("parts", 0, "stem")).orElseThrow();
String withoutFirst = file.apply(List.of(file.remove(stem, "length")));
String withoutLast = file.apply(List.of(file.remove(stem, "radius")));
assertTrue(withoutFirst.contains("\"stem\": {\"radius\": 0.5},"));
assertTrue(withoutLast.contains("\"stem\": {\"length\": [16.0, 26.0]},"));
assertTrue(JsonText.isValue(withoutFirst));
assertTrue(JsonText.isValue(withoutLast));
}
@Test
public void aMovedSubtreeIsIndentedForItsNewPlace() {
JsonText.Arr children = (JsonText.Arr) file.at(path("parts", 0, "children")).orElseThrow();
JsonText.Arr parts = (JsonText.Arr) file.at(path("parts")).orElseThrow();
JsonText.Obj parent = (JsonText.Obj) file.at(path("parts", 0)).orElseThrow();
String edited = file.apply(List.of(file.remove(parent, "children"), file.append(parts, file.detachedTextOf(children.elements().getFirst()))));
JsonText moved = JsonText.parse(edited);
assertEquals("3", moved.textOf(moved.at(path("parts", 1, "blob", "radius")).orElseThrow()));
assertTrue(edited.contains("\n {\n \"blob\": {\n \"radius\": 3\n }\n }\n ]"));
}
@Test
public void quotesTextAndRefusesOverlappingEdits() {
JsonText.Value variants = file.at(path("variants")).orElseThrow();
assertEquals("\"a\\\"b\"", JsonSplicer.quote("a\"b"));
assertThrows(IllegalArgumentException.class, () -> file.apply(List.of(file.replace(variants, "1"), file.replace(variants, "2"))));
}
}
@@ -0,0 +1,17 @@
package art.arcane.iris.core.studio.scene;
import com.volmit.tooling.JsonPath;
/** Paths written as tests read them: a {@link String} for a member, an {@link Integer} for an element. */
final class TestPaths {
private TestPaths() {
}
static JsonPath path(Object... steps) {
JsonPath path = JsonPath.ROOT;
for (Object step : steps) {
path = step instanceof Integer position ? path.element(position) : path.member((String) step);
}
return path;
}
}