Let a tool world refuse to close and hear that it is closing, and tell middle clicks apart

ToolWorldListener gets closeRefusal() and closing(by) so a tool world that holds the
studio slot can keep its owner's work safe. MenuClick tells a middle click from a
left or right one.
This commit is contained in:
piexel committed 2026-11-08 16:52:09 +01:00
1 parent 3691611c6c
commit 18c6b189d1
8 files changed
+43 -412

No files matched your search

+1 -1
View File
@@ -48,7 +48,7 @@ types that carry them and lists what the Iris adapter still owes.
| Sparse geometry | `GeneratedObject` | | Sparse geometry | `GeneratedObject` |
| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `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`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `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` (with `player()`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` | | 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` (with `player()`), `ToolPack` (`edit` with `PackEdit`, `outputFolder`, `objects` with `ObjectCodec`, `worlds`, `services`), host `CommandRegistration` in `FeatureCatalog.commands()` |
| Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `actionBar`, `sound`, `sidebar`, `particles`, `give`, `held`, `openMenu`), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause`, `command`, `chunkLoaded`, `closed`), `com.volmit.geometry.ChunkPos`; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) | | Worlds a tool opens | `com.volmit.tooling.world`, exposed to pack modules by host `ExposedPackages`: `ToolWorlds` (`open`, `find`) with `ToolWorldSpec`, `ChunkPainter` and `ChunkCanvas`, `ToolWorld` (`players`, `owns`, `run`, `call`, `block`, `blockEntity`, `setBlock`, `repaint`, `close`), `ToolPlayer` (`teleport`, `creative`, `actionBar`, `sound`, `sidebar`, `particles`, `give`, `held`, `openMenu`), `ToolItem`, `ToolMenu` with `MenuButton` and `MenuClick`, `Particle`, `ToolWorldListener` (`entered`, `left`, `moved`, `sneakToggled`, `used` with `ToolUse`, `blockChanging` with `BlockChange.Cause`, `command`, `chunkLoaded`, `closeRefusal`, `closing`, `closed`), `com.volmit.geometry.ChunkPos`; a tool world takes the pack's studio slot, so the host asks `closeRefusal` before it closes the world for another studio, the studio close command or a server stop, and waits for `closing` when another studio replaces it; every Y is the world's own; implemented by each platform adapter (Bukkit; modded adapters answer with a failed `open`) |
| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` | | Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` |
| Typed generation and persistent storage | `mantle` package | | Typed generation and persistent storage | `mantle` package |
+4
View File
@@ -611,6 +611,10 @@ worlds.open(new ToolWorldSpec("scratch", painter, new ToolWorldListener() { }))
`Cause`). Each method returns `true` to allow or `false` to cancel where it decides, and `blockChanging` freezes the `Cause`). Each method returns `true` to allow or `false` to cancel where it decides, and `blockChanging` freezes the
world unless the tool overrides it. Calls come on the thread that owns the player or the position, and must return world unless the tool overrides it. Calls come on the thread that owns the player or the position, and must return
quickly. quickly.
- A tool world takes the pack's studio slot: opening another studio, the studio close command and a server stop go
through the world. `closeRefusal()` lets the tool veto such a close with a message (an unsaved edit, a running
save), and `closing(by)` lets it finish its work before another studio replaces it; the host closes the world when
that future completes.
- On a platform that splits a world across threads (Folia), `ToolWorld.owns(at)` says whether the calling thread may - On a platform that splits a world across threads (Folia), `ToolWorld.owns(at)` says whether the calling thread may
touch the block, `run`/`call` get a task there, and `block`, `blockEntity` and `setBlock` fail with touch the block, `run`/`call` get a task there, and `block`, `blockEntity` and `setBlock` fail with
`IllegalStateException` elsewhere. `ToolPlayer` readers are valid on the player's own thread (`ToolPlayer.run`); its `IllegalStateException` elsewhere. `ToolPlayer` readers are valid on the player's own thread (`ToolPlayer.run`); its
@@ -3,12 +3,18 @@ package com.volmit.tooling.world;
import java.util.Objects; import java.util.Objects;
/** /**
* A click on a {@link MenuButton}. A left click has {@code right} false; holding shift is {@code shift}. * A click on a {@link MenuButton}. A left click has {@code right} false; holding shift is {@code shift}; the middle
* mouse button is {@code middle}, with {@code right} and {@code shift} false.
* *
* @param player the player who clicked * @param player the player who clicked
*/ */
public record MenuClick(ToolPlayer player, boolean right, boolean shift) { public record MenuClick(ToolPlayer player, boolean right, boolean shift, boolean middle) {
public MenuClick { public MenuClick {
Objects.requireNonNull(player, "player"); Objects.requireNonNull(player, "player");
} }
/** A left or right click, with or without shift. */
public MenuClick(ToolPlayer player, boolean right, boolean shift) {
this(player, right, shift, false);
}
} }
@@ -2,6 +2,7 @@ package com.volmit.tooling.world;
import com.volmit.geometry.BlockPosition; import com.volmit.geometry.BlockPosition;
import java.util.Optional; import java.util.Optional;
import java.util.concurrent.CompletableFuture;
/** /**
* What a tool hears about its world. Every method has a default that does nothing, so a tool implements only the ones * What a tool hears about its world. Every method has a default that does nothing, so a tool implements only the ones
@@ -52,6 +53,26 @@ public interface ToolWorldListener {
default void chunkLoaded(int chunkX, int chunkZ) { default void chunkLoaded(int chunkX, int chunkZ) {
} }
/**
* Whether the host may close the world now, asked before the host closes it for any reason other than the tool's own
* {@link ToolWorld#close()}: another studio opening, the studio close command, the server stopping. A tool world takes
* the pack's studio slot, so those paths go through the world. Return a message for the user to veto the close, such
* as "autosave is still running"; empty lets it happen. Asked on any thread, and must return quickly.
*/
default Optional<String> closeRefusal() {
return Optional.empty();
}
/**
* Another studio wants this world's slot. Get the world ready to close, such as finishing a save, and complete the
* future when it is ready; the host then closes the world. Complete it exceptionally to refuse, with a message for the
* user. {@code by} is the player who asked, empty when the console did. Called on any thread; the future may complete
* on any thread.
*/
default CompletableFuture<Void> closing(Optional<ToolPlayer> by) {
return CompletableFuture.completedFuture(null);
}
/** The world was unloaded and is gone; nothing can be done with it any more. */ /** The world was unloaded and is gone; nothing can be done with it any more. */
default void closed() { default void closed() {
} }
@@ -37,6 +37,15 @@ class ToolWorldRecordsTest {
assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", painter, null)); assertThrows(NullPointerException.class, () -> new ToolWorldSpec("name", painter, null));
} }
@Test
void aListenerThatSaysNothingAboutClosingLetsTheWorldCloseAtOnce() {
var listener = new ToolWorldListener() { };
assertEquals(java.util.Optional.empty(), listener.closeRefusal());
assertEquals(true, listener.closing(java.util.Optional.empty()).isDone());
assertEquals(false, listener.closing(java.util.Optional.empty()).isCompletedExceptionally());
}
@Test @Test
void aToolItemKeepsItsOwnCopyOfTheLore() { void aToolItemKeepsItsOwnCopyOfTheLore() {
var lore = new ArrayList<>(List.of("one")); var lore = new ArrayList<>(List.of("one"));
@@ -1,409 +0,0 @@
package art.arcane.iris.core.runtime.jigsaw;
import art.arcane.iris.core.loader.IrisData;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
public final class JigsawStudioActivation {
private static final Map<String, ActiveRequest> ACTIVE = new ConcurrentHashMap<>();
private static final AtomicReference<UUID> OPENING_OWNER = new AtomicReference<>();
private static final AtomicReference<StagedState> STAGED = new AtomicReference<>();
private JigsawStudioActivation() {
}
public static Request activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source
) {
JigsawStudioLayout layout = JigsawStudioLayout.create(
mode,
cellDimensions,
JigsawStudioVariantCatalog.empty());
return activate(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
layout,
null
);
}
public static Request activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
JigsawStudioLayout initialLayout
) {
return activate(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
initialLayout,
null
);
}
public static synchronized Request activate(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
if (STAGED.get() != null) {
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
}
if (ownerId != null && !ownerId.equals(OPENING_OWNER.get())) {
throw new IllegalStateException("Jigsaw Studio activation does not own the active opening lease");
}
UUID activeOwnerId = activeOwnerId();
if (ownerId != null && activeOwnerId != null && !ownerId.equals(activeOwnerId)) {
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
}
ActiveRequest activeRequest = createActiveRequest(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
initialLayout,
ownerId);
ACTIVE.put(normalize(packKey), activeRequest);
return activeRequest.request();
}
public static synchronized StagedActivation stage(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
JigsawStudioLayout initialLayout,
UUID ownerId,
UUID preservedRequestId
) {
UUID openingOwner = OPENING_OWNER.get();
UUID activeOwner = activeOwnerId();
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio staged owner ID");
if (!requestedOwner.equals(openingOwner)) {
throw new IllegalStateException("Jigsaw Studio staging does not own the active opening lease");
}
if (activeOwner != null && !requestedOwner.equals(activeOwner)) {
throw new IllegalStateException("Jigsaw Studio is owned by another player session");
}
if (STAGED.get() != null) {
throw new IllegalStateException("A Jigsaw Studio replacement is already staged");
}
ActiveRequest preserved = preservedRequestId == null ? null : active(preservedRequestId);
if (preservedRequestId != null && preserved == null) {
throw new IllegalStateException("The Jigsaw Studio being replaced is no longer active");
}
if (activeOwner != null && preserved == null) {
throw new IllegalStateException("The active Jigsaw Studio must be preserved during replacement");
}
if (preserved != null && preserved.request().ownerId() != null
&& !requestedOwner.equals(preserved.request().ownerId())) {
throw new IllegalStateException("The Jigsaw Studio being replaced belongs to another player session");
}
ActiveRequest candidate = createActiveRequest(
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
initialLayout,
requestedOwner);
StagedActivation staged = new StagedActivation(
UUID.randomUUID(), candidate.request(), candidate.session());
STAGED.set(new StagedState(staged, candidate, preserved, false));
return staged;
}
public static synchronized boolean beginStagedGeneration(StagedActivation expected) {
StagedState state = stagedState(expected);
if (state == null || state.generationVisible()) {
return false;
}
STAGED.set(new StagedState(state.staged(), state.candidate(), state.preserved(), true));
return true;
}
public static synchronized boolean commit(StagedActivation expected) {
StagedState state = stagedState(expected);
if (state == null || !state.generationVisible()) {
return false;
}
if (state.preserved() != null) {
ACTIVE.remove(normalize(state.preserved().request().packKey()), state.preserved());
}
ACTIVE.put(normalize(state.candidate().request().packKey()), state.candidate());
STAGED.set(null);
return true;
}
public static synchronized boolean rollback(StagedActivation expected) {
StagedState state = stagedState(expected);
if (state == null) {
return false;
}
STAGED.set(null);
return true;
}
public static Request getGeneratorRequest(String packKey) {
StagedState state = STAGED.get();
if (state != null && state.generationVisible()
&& normalize(state.candidate().request().packKey()).equals(normalize(packKey))) {
return state.candidate().request();
}
return getRequest(packKey);
}
public static JigsawStudioSession getGeneratorSession(String packKey) {
StagedState state = STAGED.get();
if (state != null && state.generationVisible()
&& normalize(state.candidate().request().packKey()).equals(normalize(packKey))) {
return state.candidate().session();
}
return getSession(packKey);
}
public static boolean tryBeginOpen(UUID ownerId) {
UUID requestedOwner = Objects.requireNonNull(ownerId, "Jigsaw Studio opening owner ID");
UUID activeOwnerId = activeOwnerId();
if (activeOwnerId != null && !requestedOwner.equals(activeOwnerId)) {
return false;
}
return OPENING_OWNER.compareAndSet(null, requestedOwner);
}
public static void finishOpen(UUID ownerId) {
if (ownerId != null) {
OPENING_OWNER.compareAndSet(ownerId, null);
}
}
public static UUID openingOwnerId() {
return OPENING_OWNER.get();
}
public static UUID activeOwnerId() {
for (ActiveRequest activeRequest : ACTIVE.values()) {
UUID ownerId = activeRequest.request().ownerId();
if (ownerId != null) {
return ownerId;
}
}
return null;
}
public static void deactivate(String packKey) {
if (packKey != null) {
ACTIVE.remove(normalize(packKey));
StagedState state = STAGED.get();
if (state != null && (normalize(state.candidate().request().packKey()).equals(normalize(packKey))
|| state.preserved() != null && normalize(state.preserved().request().packKey())
.equals(normalize(packKey)))) {
STAGED.compareAndSet(state, null);
}
}
}
public static boolean deactivate(String packKey, UUID requestId) {
if (packKey == null || requestId == null) {
return false;
}
StagedState staged = STAGED.get();
if (staged != null && staged.preserved() != null
&& requestId.equals(staged.preserved().request().requestId())
&& normalize(packKey).equals(normalize(staged.preserved().request().packKey()))) {
return false;
}
AtomicBoolean removed = new AtomicBoolean(false);
ACTIVE.computeIfPresent(normalize(packKey), (key, activeRequest) -> {
if (!requestId.equals(activeRequest.request().requestId())) {
return activeRequest;
}
removed.set(true);
return null;
});
return removed.get();
}
public static boolean isActive(String packKey) {
return getRequest(packKey) != null;
}
public static Request getRequest(String packKey) {
ActiveRequest activeRequest = active(packKey);
return activeRequest == null ? null : activeRequest.request();
}
public static JigsawStudioSession getSession(String packKey) {
ActiveRequest activeRequest = active(packKey);
return activeRequest == null ? null : activeRequest.session();
}
public static JigsawStudioLayout getLayout(String packKey) {
JigsawStudioSession session = getSession(packKey);
return session == null ? null : session.layout();
}
public static Request getRequest(UUID requestId) {
ActiveRequest activeRequest = active(requestId);
return activeRequest == null ? null : activeRequest.request();
}
public static JigsawStudioSession getSession(UUID requestId) {
ActiveRequest activeRequest = active(requestId);
return activeRequest == null ? null : activeRequest.session();
}
private static ActiveRequest active(String packKey) {
if (packKey == null) {
return null;
}
return ACTIVE.get(normalize(packKey));
}
private static ActiveRequest active(UUID requestId) {
if (requestId == null) {
return null;
}
for (ActiveRequest activeRequest : ACTIVE.values()) {
if (requestId.equals(activeRequest.request().requestId())) {
return activeRequest;
}
}
return null;
}
private static ActiveRequest createActiveRequest(
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
JigsawStudioLayout initialLayout,
UUID ownerId
) {
Request request = new Request(
UUID.randomUUID(),
packKey,
structureKey,
mode,
compatibilityTarget,
cellDimensions,
source,
ownerId);
JigsawStudioLayout layout = Objects.requireNonNull(initialLayout, "Initial Jigsaw Studio layout");
if (layout.mode() != mode) {
throw new IllegalArgumentException("Initial Jigsaw Studio layout mode does not match the request");
}
if (!layout.cellDimensions().equals(cellDimensions)) {
throw new IllegalArgumentException("Initial Jigsaw Studio layout cell dimensions do not match the request");
}
JigsawStudioSession session = new JigsawStudioSession(
request.requestId(),
request.packKey(),
request.structureKey(),
layout);
return new ActiveRequest(request, session);
}
private static StagedState stagedState(StagedActivation expected) {
StagedActivation staged = Objects.requireNonNull(expected, "Staged Jigsaw Studio activation");
StagedState state = STAGED.get();
return state != null && state.staged().stageId().equals(staged.stageId()) ? state : null;
}
private static String normalize(String key) {
return key.trim().toLowerCase(Locale.ROOT);
}
private record ActiveRequest(Request request, JigsawStudioSession session) {
}
private record StagedState(
StagedActivation staged,
ActiveRequest candidate,
ActiveRequest preserved,
boolean generationVisible
) {
}
public record StagedActivation(
UUID stageId,
Request request,
JigsawStudioSession session
) {
public StagedActivation {
Objects.requireNonNull(stageId, "Jigsaw Studio stage ID");
Objects.requireNonNull(request, "Jigsaw Studio staged request");
Objects.requireNonNull(session, "Jigsaw Studio staged session");
if (!request.requestId().equals(session.sessionId())) {
throw new IllegalArgumentException("Staged Jigsaw Studio request and session IDs do not match");
}
}
}
public record Request(
UUID requestId,
String packKey,
String structureKey,
JigsawStudioMode mode,
JigsawStudioCompatibilityTarget compatibilityTarget,
JigsawStudioCellDimensions cellDimensions,
IrisData source,
UUID ownerId
) {
public Request {
requestId = Objects.requireNonNull(requestId, "Jigsaw Studio request ID");
packKey = requireKey(packKey, "pack");
structureKey = requireKey(structureKey, "structure");
mode = Objects.requireNonNull(mode, "Jigsaw Studio mode");
compatibilityTarget = Objects.requireNonNull(
compatibilityTarget,
"Jigsaw Studio compatibility target"
);
cellDimensions = Objects.requireNonNull(cellDimensions, "Jigsaw Studio cell dimensions");
source = Objects.requireNonNull(source, "Jigsaw Studio source data");
}
private static String requireKey(String value, String name) {
Objects.requireNonNull(value, "Jigsaw Studio " + name + " key");
String normalized = value.trim();
if (normalized.isEmpty()) {
throw new IllegalArgumentException("Jigsaw Studio " + name + " key cannot be blank");
}
return normalized;
}
}
}