diff --git a/api/CONTRACTS.md b/api/CONTRACTS.md index 7b83ad413..dd83d6881 100644 --- a/api/CONTRACTS.md +++ b/api/CONTRACTS.md @@ -46,7 +46,7 @@ types that carry them and lists what the Iris adapter still owes. | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Sparse geometry | `GeneratedObject` | -| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | +| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `BakeRun` (`Stage`), `BlockParts`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `SceneCreation`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` | | Commands of a module | `com.volmit.tooling`: `ToolingRegistry.registerCommand`, immutable `Command` (`named`, `alias`, `describe`, `child`, `argument`, `runs`, `openToEveryone`), typed `Argument` (`word`, `text`, `integer`, `decimal`, `flag`, `choice`, `resource`, `registered`, `orElse`, `suggesting`), `CommandAction`, `CommandContext` (`get`, `sender`, `pack`, `world`, `platform`), plain-text `Sender`, `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`), host `CommandRegistration` in `FeatureCatalog.commands()` | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Typed generation and persistent storage | `mantle` package | diff --git a/api/DESIGN.md b/api/DESIGN.md index 761218c22..eb9bed68b 100644 --- a/api/DESIGN.md +++ b/api/DESIGN.md @@ -1373,6 +1373,10 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet reads as nodes (`NodeGraph`). The studio makes every write, so one implementation keeps the author's layout, checks the result is still JSON, refuses edits outside a studio world and moves the file in atomically for the pack watcher. `JsonText` is in the API because a view reads positions from it; splicing text is not. +- **Creating and deleting are the host's too.** A view says only how its entries are made (`SceneCreation`: the kind + whose folder holds the files, the JSON a new one starts as, and the prefix other files name an entry by). The host + checks the key is a folder-safe name, writes the file, lists the files that still name an entry before it goes, and + moves it to the trash, so a view never touches the pack's files. - **Paths are typed.** A `JsonPath` step is a `Key` or an `Index`, so a view cannot write a step the file cannot hold. - **The wire is the host's.** The studio protocol may encode an absent part or block as it likes (Iris sends `-1`); the API types say absent with `Optional`/`OptionalInt`. diff --git a/api/README.md b/api/README.md index 0f0c95df4..cee336e72 100644 --- a/api/README.md +++ b/api/README.md @@ -534,7 +534,9 @@ final class RuinScenes implements SceneView { settings (`NodeSettings`, shown as the pack's schema describes their type), the nodes it holds and the `Edits` the studio may make (a child list to move nodes into, whether it moves, the `Addition`s it offers). Places in the file are `JsonPath`s of `Key` and `Index` steps. The studio writes the file itself, rewriting only what changes; the - view never writes. + view never writes. A view whose entries the studio may create and delete returns a `SceneCreation` from + `creation()`: the resource kind of its files, the starter JSON of a new entry and the text other files name an + entry by; the studio does the writing, listing of uses and trashing. - Absent values are empty, never blank or `-1`: an entry without a group, a node that draws no part of the scene (`GraphNode.part()`), a column a pattern places nothing at (`BlockPattern.pickAt`). diff --git a/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java b/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java index 83321a237..c6ac55faf 100644 --- a/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java +++ b/api/api/src/main/java/com/volmit/tooling/EditableSceneView.java @@ -20,4 +20,9 @@ public interface EditableSceneView extends SceneView { * @throws IllegalArgumentException when {@code text} does not hold what this view edits */ NodeGraph graph(PackWorld world, String key, JsonText text); + + /** How the studio creates and removes entries of this view; empty when it may not, which is the default. */ + default Optional creation() { + return Optional.empty(); + } } diff --git a/api/api/src/main/java/com/volmit/tooling/SceneCreation.java b/api/api/src/main/java/com/volmit/tooling/SceneCreation.java new file mode 100644 index 000000000..b3b04a202 --- /dev/null +++ b/api/api/src/main/java/com/volmit/tooling/SceneCreation.java @@ -0,0 +1,18 @@ +package com.volmit.tooling; + +import com.volmit.resource.ResourceKind; + +import java.util.Objects; + +/** + * How the studio creates and removes the entries of an editable scene view: each entry is a file of {@code kind}, a new + * one starts as the JSON text {@code starter}, and other files of the pack name an entry {@code key} as + * {@code referencePrefix + key}, which is how the studio finds what still uses an entry before it is removed. + */ +public record SceneCreation(ResourceKind kind, String starter, String referencePrefix) { + public SceneCreation { + Objects.requireNonNull(kind, "kind"); + Objects.requireNonNull(starter, "starter"); + Objects.requireNonNull(referencePrefix, "referencePrefix"); + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java index 51397a549..2d7273090 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java +++ b/core/src/main/java/art/arcane/iris/core/studio/bridge/StudioBridge.java @@ -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 editing(EditorTask 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 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 files) { + } + + private record TrashedBody(String to) { } /** A {@link SceneEntry} as the studio reads it, with a blank group for none. */ diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/SceneFiles.java b/core/src/main/java/art/arcane/iris/core/studio/scene/SceneFiles.java new file mode 100644 index 000000000..ce3508b7e --- /dev/null +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/SceneFiles.java @@ -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 . + */ + +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 usesOf(String key) throws IOException { + String reference = "\"" + creation.referencePrefix() + key + "\""; + Path own = fileOf(key); + List 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; + } +} diff --git a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java index 8a8e16627..0c5887db1 100644 --- a/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java +++ b/core/src/main/java/art/arcane/iris/core/studio/scene/StudioEditors.java @@ -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 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); diff --git a/core/src/test/java/art/arcane/iris/core/studio/scene/SceneFilesTest.java b/core/src/test/java/art/arcane/iris/core/studio/scene/SceneFilesTest.java new file mode 100644 index 000000000..4fcc28e23 --- /dev/null +++ b/core/src/test/java/art/arcane/iris/core/studio/scene/SceneFilesTest.java @@ -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")); + } +} diff --git a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java index e43f6bb49..8a826810a 100644 --- a/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java +++ b/module/src/main/java/art/arcane/iris/modules/objects/ProceduralObjectScenes.java @@ -31,6 +31,7 @@ import com.volmit.tooling.BlockParts; import com.volmit.tooling.EditableSceneView; import com.volmit.tooling.JsonText; import com.volmit.tooling.NodeGraph; +import com.volmit.tooling.SceneCreation; import com.volmit.tooling.SceneEntry; import com.volmit.tooling.SceneFile; import com.volmit.world.PackWorld; @@ -46,6 +47,24 @@ import java.util.Optional; public final class ProceduralObjectScenes implements EditableSceneView { private static final ResourceId ID = ResourceId.parse("iris:objects/procedural"); private static final char FOLDER_SEPARATOR = '/'; + private static final String STARTER = """ + { + "materials": [ + {"role": "wood", "block": "minecraft:oak_log"}, + {"role": "leaves", "block": "minecraft:oak_leaves"} + ], + "parts": [ + { + "role": "wood", + "stem": {"length": [6, 9], "radius": 0.5}, + "children": [ + {"role": "leaves", "mode": "FILL", "blob": {"radius": 3}} + ] + } + ] + } + """; + private static final SceneCreation CREATION = new SceneCreation(ProceduralObjectCatalog.DEFINITIONS, STARTER, ProceduralObjectCatalog.KEY_PREFIX); @Override public ResourceId id() { @@ -119,6 +138,11 @@ public final class ProceduralObjectScenes implements EditableSceneView { return ProceduralObjectGraph.of(key.substring(key.lastIndexOf(FOLDER_SEPARATOR) + 1), text, read); } + @Override + public Optional creation() { + return Optional.of(CREATION); + } + private static BakeRun runOf(BakeProfile profile) { List stages = Arrays.stream(BakeProfile.Stage.values()) .map(stage -> new BakeRun.Stage(stage.label(), profile.nanos(stage))) diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index dad1242a7..d8b6430c5 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -160,6 +160,23 @@ export class BridgeClient { return this.json(`scene-write?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST', body: JSON.stringify({ revision, text }) }) } + /** Writes a new entry from its view's starter; it is listed once the pack has reloaded. Refused when the key can't name a new one. */ + async sceneCreate(viewId: string, key: string): Promise { + await this.json(`scene-create?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' }) + } + + /** The pack files that still name the entry, such as the biomes that place it. */ + async sceneUses(viewId: string, key: string): Promise { + const uses = await this.json<{ files: string[] }>(`scene-uses?${new URLSearchParams({ view: viewId, key })}`) + return uses.files + } + + /** Moves the entry's file to the trash; says where it went. */ + async sceneDelete(viewId: string, key: string): Promise { + const trashed = await this.json<{ to: string }>(`scene-delete?${new URLSearchParams({ view: viewId, key })}`, { method: 'POST' }) + return trashed.to + } + /** What a setting naming an entry of a platform registry (reference) or a resource of the pack (resource) may be typed as, sorted. */ suggestions(of: { reference: string } | { resource: string }): Promise { return this.json(`suggestions?${new URLSearchParams(of)}`) diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index 17f1bd7f6..827d2df60 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -33,9 +33,10 @@ export interface SceneEntry { variants: number } -/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */ +/** A scene view as the server lists it; `editable` when its entries can be edited as nodes, `creatable` when they can also be created and deleted, `baked` when their bake can be timed, `parts` when a block can be traced to the part that placed it. */ export interface SceneViewInfo extends ModuleViewInfo { editable: boolean + creatable: boolean baked: boolean parts: boolean } diff --git a/studio/src/renderer/src/editor/entryKeys.test.ts b/studio/src/renderer/src/editor/entryKeys.test.ts new file mode 100644 index 000000000..7e57836b8 --- /dev/null +++ b/studio/src/renderer/src/editor/entryKeys.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from 'vitest' +import { folderPrefixOf, refusalOfNewKey } from './entryKeys' + +describe('refusalOfNewKey', () => { + it('accepts a free, plain key', () => { + expect(refusalOfNewKey('trees/oak-2', ['trees/oak'])).toBeNull() + }) + + it('refuses a key that is taken', () => { + expect(refusalOfNewKey('trees/oak', ['trees/oak'])).toBe('trees/oak already exists') + }) + + it('refuses a blank name', () => { + expect(refusalOfNewKey(' ', [])).toBe('Give it a name') + }) + + it('refuses keys that could leave the folder or are not plain', () => { + for (const key of ['Trees/Oak', 'trees//oak', '/oak', 'oak/', '../oak', 'trees/../oak', 'oak.json', 'trees\\oak']) { + expect(refusalOfNewKey(key, []), key).toMatch(/^Use lower case/) + } + }) +}) + +describe('folderPrefixOf', () => { + it('keeps the folders of a key with their closing slash', () => { + expect(folderPrefixOf('trees/oak/tall')).toBe('trees/oak/') + }) + + it('is empty for a key in no folder', () => { + expect(folderPrefixOf('oak')).toBe('') + }) +}) diff --git a/studio/src/renderer/src/editor/entryKeys.ts b/studio/src/renderer/src/editor/entryKeys.ts new file mode 100644 index 000000000..e16123e5f --- /dev/null +++ b/studio/src/renderer/src/editor/entryKeys.ts @@ -0,0 +1,18 @@ +const FOLDER_SEPARATOR = '/' +const KEY = /^[a-z0-9_-]+(\/[a-z0-9_-]+)*$/ + +/** Why `key` can't name a new entry beside the `existing` ones, or null when it can; the server checks the same. */ +export function refusalOfNewKey(key: string, existing: readonly string[]): string | null { + if (key.trim() === '') { + return 'Give it a name' + } + if (!KEY.test(key)) { + return 'Use lower case letters, digits, - and _, with / between folders' + } + return existing.includes(key) ? `${key} already exists` : null +} + +/** The folder of `key` as a start for naming a new entry in it, such as `trees/`; empty for an entry in no folder. */ +export function folderPrefixOf(key: string): string { + return key.slice(0, key.lastIndexOf(FOLDER_SEPARATOR) + 1) +} diff --git a/studio/src/renderer/src/studio/EntryBrowser.tsx b/studio/src/renderer/src/studio/EntryBrowser.tsx index f2663fc0e..ce15e0ef7 100644 --- a/studio/src/renderer/src/studio/EntryBrowser.tsx +++ b/studio/src/renderer/src/studio/EntryBrowser.tsx @@ -1,9 +1,14 @@ +import { Plus } from 'lucide-react' import { useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger } from '@/components/ui/context-menu' import { Input } from '@/components/ui/input' import { ScrollArea } from '@/components/ui/scroll-area' import { cn } from '@/lib/utils' +import { folderPrefixOf } from '../editor/entryKeys' const NUMBER = new Intl.NumberFormat('en-US') +const DELETE_KEY = 'Delete' /** An entry of a module view: its key, the name it is listed by, and the heading it is listed under (empty for none). */ export interface BrowsableEntry { @@ -12,23 +17,77 @@ export interface BrowsableEntry { group: string } +/** What the browser can do with the files of its entries, for a view whose entries are files of the pack. */ +export interface EntryFileActions { + /** Asks for a new entry, offering `folderPrefix`, such as `trees/`, to name it in. */ + onCreate(folderPrefix: string): void + /** Deletes the entry at `key`, once what still uses it was shown. */ + onDelete(key: string): void +} + interface EntryBrowserProps { title: string entries: BrowsableEntry[] current: string | null onSelect(key: string): void + fileActions?: EntryFileActions className?: string } +type MenuTarget = { entry: string } | { folder: string } | null + /** A view's entries under their headings, with a search over keys, names and headings (v3e ObjectBrowser). */ -export function EntryBrowser({ title, entries, current, onSelect, className }: EntryBrowserProps): React.JSX.Element { +export function EntryBrowser({ title, entries, current, onSelect, fileActions, className }: EntryBrowserProps): React.JSX.Element { const [search, setSearch] = useState('') + const [menuTarget, setMenuTarget] = useState(null) const wanted = search.trim().toLowerCase() const groups = useMemo(() => groupedEntries(entries, wanted), [entries, wanted]) + const list = ( +
{ + const target = menuTargetOf(event.target) + setMenuTarget(target) + if (target !== null && 'entry' in target) { + onSelect(target.entry) + } + }} + > + {groups.map(([group, members]) => ( +
+ {group !== '' && ( +

+ {group} +

+ )} + {members.map((entry) => ( + + ))} +
+ ))} + {groups.length === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} +
+ ) return ( -
+
-

{title}

+
+

{title}

+ {fileActions !== undefined && ( + + )} +

{NUMBER.format(entries.length)} in the pack

-
- {groups.map(([group, members]) => ( -
- {group !== '' &&

{group}

} - {members.map((entry) => ( - - ))} -
- ))} - {groups.length === 0 &&

{entries.length === 0 ? 'Nothing to show' : 'Nothing matches'}

} -
+ {fileActions === undefined ? ( + list + ) : ( + !open && setMenuTarget(null)}> + {list} + + + )}
) } +function EntryMenu({ target, actions }: { target: MenuTarget; actions: EntryFileActions }): React.JSX.Element { + if (target !== null && 'entry' in target) { + return ( + + actions.onCreate(folderPrefixOf(target.entry))}>New entry beside it… + actions.onDelete(target.entry)}> + Delete… + + + ) + } + const folder = target === null ? '' : target.folder + return ( + + actions.onCreate(folder === '' ? '' : `${folder}/`)}>{folder === '' ? 'New entry…' : `New entry in ${folder}…`} + + ) +} + +function menuTargetOf(eventTarget: EventTarget): MenuTarget { + if (!(eventTarget instanceof Element)) { + return null + } + const entry = eventTarget.closest('[data-entry-key]')?.dataset.entryKey + if (entry !== undefined) { + return { entry } + } + const folder = eventTarget.closest('[data-entry-folder]')?.dataset.entryFolder + return folder === undefined ? null : { folder } +} + function groupedEntries(entries: Entry[], wanted: string): [string, Entry[]][] { const groups = new Map() for (const entry of entries) { diff --git a/studio/src/renderer/src/studio/EntryFileDialogs.tsx b/studio/src/renderer/src/studio/EntryFileDialogs.tsx new file mode 100644 index 000000000..67dbc477b --- /dev/null +++ b/studio/src/renderer/src/studio/EntryFileDialogs.tsx @@ -0,0 +1,150 @@ +import { useMemo, useState } from 'react' +import { Button } from '@/components/ui/button' +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog' +import { Input } from '@/components/ui/input' +import type { BridgeClient } from '../bridge/BridgeClient' +import { refusalOfNewKey } from '../editor/entryKeys' +import type { EntryFileActions } from './EntryBrowser' + +const MOST_USES_LISTED = 8 + +type Ask = { kind: 'create'; folderPrefix: string } | { kind: 'delete'; key: string; uses: string[] } + +interface EntryFiles { + actions: EntryFileActions + dialogs: React.JSX.Element | null +} + +/** + * Creating and deleting a view's entries: asking for a new key, and listing what still uses an entry before it goes to + * the trash. The new entry is listed once the pack has reloaded, so `onCreated` names it to be chosen then. + */ +export function useEntryFiles( + client: BridgeClient, + viewId: string, + keys: string[], + onCreated: (key: string) => void, + tell: (message: string) => void +): EntryFiles { + const [ask, setAsk] = useState(null) + const close = (): void => setAsk(null) + const actions = useMemo( + () => ({ + onCreate: (folderPrefix) => setAsk({ kind: 'create', folderPrefix }), + onDelete: (key) => { + client + .sceneUses(viewId, key) + .then((uses) => setAsk({ kind: 'delete', key, uses })) + .catch((failure: Error) => tell(failure.message)) + } + }), + [client, viewId, tell] + ) + const create = (key: string): void => { + close() + client + .sceneCreate(viewId, key) + .then(() => { + onCreated(key) + tell(`Created ${key}`) + }) + .catch((failure: Error) => tell(failure.message)) + } + const remove = (key: string): void => { + close() + client + .sceneDelete(viewId, key) + .then((to) => tell(`Moved ${key} to ${to}`)) + .catch((failure: Error) => tell(failure.message)) + } + const dialogs = + ask === null ? null : ask.kind === 'create' ? ( + + ) : ( + remove(ask.key)} onClose={close} /> + ) + return { actions, dialogs } +} + +interface NewEntryDialogProps { + initial: string + existing: string[] + onCreate(key: string): void + onClose(): void +} + +function NewEntryDialog({ initial, existing, onCreate, onClose }: NewEntryDialogProps): React.JSX.Element { + const [typed, setTyped] = useState(initial) + const key = typed.trim() + const refusal = refusalOfNewKey(key, existing) + return ( + !open && onClose()}> + +
{ + event.preventDefault() + if (refusal === null) { + onCreate(key) + } + }} + > + + New entry + Name, with its folders, like trees/oak + + setTyped(event.target.value)} /> +

{typed === initial ? '' : (refusal ?? '')}

+ + + + +
+
+
+ ) +} + +interface DeleteEntryDialogProps { + entryKey: string + uses: string[] + onDelete(): void + onClose(): void +} + +// Used elsewhere, Cancel has the focus; nothing using it, moving it to the trash does. +function DeleteEntryDialog({ entryKey, uses, onDelete, onClose }: DeleteEntryDialogProps): React.JSX.Element { + const unused = uses.length === 0 + return ( + !open && onClose()}> + + + Delete {entryKey}? + {unused ? 'Nothing in the pack uses it.' : 'Still used by these files, which will warn that it is missing:'} + + {!unused && ( +
    + {uses.slice(0, MOST_USES_LISTED).map((file) => ( +
  • + {file} +
  • + ))} + {uses.length > MOST_USES_LISTED &&
  • and {uses.length - MOST_USES_LISTED} more
  • } +
+ )} + + + + +
+
+ ) +} diff --git a/studio/src/renderer/src/studio/NodePane.tsx b/studio/src/renderer/src/studio/NodePane.tsx index 309805457..b46bce8e7 100644 --- a/studio/src/renderer/src/studio/NodePane.tsx +++ b/studio/src/renderer/src/studio/NodePane.tsx @@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button' import type { GraphNode } from '../bridge/types' import type { NodeEditor } from '../editor/useNodeEditor' import { NodeCanvas } from './NodeCanvas' -import { isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts' +import { isInEntryBrowser, isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts' import { useBindings } from './useBindings' interface NodePaneProps { @@ -91,6 +91,9 @@ function useEditorKeys( // Captured, so the editor's keys come before the window's own: F fits the nodes instead of following the player. const down = (event: KeyboardEvent): void => { const action = isTypingInto(event.target) ? null : nodeEditorActionFor(event, bindings) + if (action === 'deleteNode' && isInEntryBrowser(event.target)) { + return + } if (action === 'dismiss') { onSelect(null) } else if (action === 'showAllNodes' && showAllRef.current !== null) { diff --git a/studio/src/renderer/src/studio/SceneStudio.tsx b/studio/src/renderer/src/studio/SceneStudio.tsx index f56f0ffca..bca1da774 100644 --- a/studio/src/renderer/src/studio/SceneStudio.tsx +++ b/studio/src/renderer/src/studio/SceneStudio.tsx @@ -18,6 +18,7 @@ import { INTS_PER_BLOCK, type BlockScene } from '../scene/sceneDecoding' import { buildSceneMesh, type SceneMesh } from '../scene/sceneMesh' import { BakeMeter, useBakeTiming } from './BakeMeter' import { EntryBrowser } from './EntryBrowser' +import { useEntryFiles } from './EntryFileDialogs' import { NodeInspector } from './NodeInspector' import { NodePane } from './NodePane' import { SceneViewport, type PickedSurface } from './SceneViewport' @@ -48,6 +49,8 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce const [chosen, setChosen] = useState<{ key: string; variant: number } | null>(null) const entry = entries.find((candidate) => candidate.key === chosen?.key) ?? entries[0] ?? null const variant = entry !== null && chosen?.key === entry.key ? Math.min(chosen.variant, entry.variants - 1) : 0 + const entryKeys = useMemo(() => entries.map((candidate) => candidate.key), [entries]) + const files = useEntryFiles(client, view.id, entryKeys, (key) => setChosen({ key, variant: 0 }), tell) const [farLeavesOnly, setFarLeavesOnly] = useState(false) const chooseVariant = (next: number): void => { if (entry !== null) { @@ -122,7 +125,15 @@ export function SceneStudio({ client, view, packRevision, onSummary, tell }: Sce )}