diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java index dc448a6e..b987d892 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/DatapackSelection.java @@ -107,6 +107,31 @@ public void writeFile(List>> writ } } + /** + * Takes {@code id} off the datapacks {@code world}'s {@code level.dat} disables, and tells whether it was there. The + * game then enables it as a pack it has not seen when it loads the world, placing it as it places any new pack; the + * enabled packs, the selection Companion records, stay as they are. Blocking. + */ + static boolean enableDisabled(Path world, String id) throws IOException { + if (!disables(world, id)) return false; + LevelDat.update(world, root -> { + if (!(root.tag().entries().get("Data") instanceof NbtData.CompoundTag data)) { + throw new IOException("The level.dat of " + world.getFileName() + " holds no world data"); + } + NbtData.CompoundTag packs = dataPacks(root.tag()); + List disabled = new ArrayList<>(strings(packs, "Disabled")); + disabled.remove(id); + NbtData.CompoundTag written = LevelDat.with(packs, "Disabled", list(disabled)); + return new LevelDat.Root(root.name(), LevelDat.with(root.tag(), "Data", LevelDat.with(data, "DataPacks", written))); + }); + return true; + } + + /** Whether {@code world}'s {@code level.dat} lists {@code id} as disabled, which the player did. Blocking. */ + static boolean disables(Path world, String id) throws IOException { + return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Disabled").contains(id); + } + /** The datapacks {@code world}'s {@code level.dat} enables, lowest first. Blocking. */ static List saved(Path world) throws IOException { return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Enabled"); diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java index 20079cbe..d6361f6f 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEdits.java @@ -601,31 +601,64 @@ private CompletableFuture apply(String path, List alsoWatched, Pa "The TotalDebug pack could not be enabled in options.txt: " + exception.getMessage())); } } + if (!assets && managed(pack) && !game.isOpen(world)) { + // A world enables a datapack it has not seen when it loads, but not one its level.dat disables, which the + // player did; a save into the managed pack enables it, as the reload of a live save does. + try { + if (DatapackSelection.enableDisabled(world, PACK_ID)) { + this.landed.incrementAndGet(); + this.packs.written(ChangeRecord.PackSide.DATA); + } + } catch (IOException | RuntimeException exception) { + return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), + "The TotalDebug datapack could not be enabled in the level.dat of " + world.getFileName() + ": " + exception.getMessage())); + } + } if (!assets && game.isOpen(world)) { - // Written all the same: the game only reads a datapack, when it loads the world or its data again. - return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "The world " + world.getFileName() - + (game.connected() ? " is open, and the game has not said yet that it plays it" : " is open in a game that is not connected to Companion") - + "; it uses the change when the world is loaded again")); + // Written all the same: the game only reads a datapack, when it loads the world or its data again. Its + // level.dat is the open world's to write, so a pack it disables stays disabled. + String open = "The world " + world.getFileName() + (game.connected() + ? " is open, and the game has not said yet that it plays it" : " is open in a game that is not connected to Companion"); + return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), open + (managed(pack) ? whenLoaded(world) + : "; it uses the change when the world is loaded again"))); } return CompletableFuture.completedFuture(new Saved(later, pack, List.of(), "")); } - if (!assets && apply == ResourcePaths.Apply.WORLD_LOAD) { + GameLocation.Connection connection = ((Access.Live) access).connection(); + // The world reads a world-load file when it loads again, from the managed pack only if it is enabled: such a save + // reloads only to enable it, as the reload after any other save does. + boolean worldLoad = !assets && apply == ResourcePaths.Apply.WORLD_LOAD; + if (worldLoad && (!managed(pack) || serverEnables(PACK_ID))) { return CompletableFuture.completedFuture(new Saved(Effect.REJOIN, pack, List.of(), "")); } + Effect failed = assets ? Effect.GAME_STARTS : worldLoad ? Effect.REJOIN : Effect.WORLD_OPENS; // Files written beside it join the same reload, which they are part of. - GameLocation.Connection connection = ((Access.Live) access).connection(); String managedPack = managed(pack) ? PACK_ID : ""; for (String beside : alsoWatched) reload(connection, world, beside, managedPack); return reload(connection, world, path, managedPack).handle((result, failure) -> { - if (failure != null) { - return new Saved(assets ? Effect.GAME_STARTS : Effect.WORLD_OPENS, pack, - List.of(), message(failure)); - } - return new Saved(result.error().isEmpty() ? Effect.NOW : assets ? Effect.GAME_STARTS - : Effect.WORLD_OPENS, pack, problemsOf(result, path, alsoWatched), result.error()); + if (failure != null) return new Saved(failed, pack, List.of(), message(failure)); + return new Saved(!result.error().isEmpty() ? failed : worldLoad ? Effect.REJOIN : Effect.NOW, pack, + problemsOf(result, path, alsoWatched), result.error()); }); } + /** Whether an open world uses a change to the managed datapack when it loads again, as its level.dat says. Blocking. */ + private static String whenLoaded(Path world) { + try { + return DatapackSelection.disables(world, PACK_ID) + ? ", and its level.dat disables the TotalDebug datapack; the next save after the world closes enables it" + : "; it uses the change when the world is loaded again"; + } catch (IOException | RuntimeException unreadable) { + return ", and whether its level.dat enables the TotalDebug datapack could not be read: " + unreadable.getMessage(); + } + } + + /** Whether the server of the world the game plays named {@code id} among its enabled datapacks. */ + private boolean serverEnables(String id) { + PackStackPayload datapacks = this.packs.datapacks(); + return datapacks != null && datapacks.enabled().stream().anyMatch(enabled -> enabled.id().equals(id)); + } + /** Asks the game to reload what {@code path} needs: the client's resources, or the data of {@code world}. */ private CompletableFuture reload(GameLocation.Connection connection, Path world, String path, String managedPack) { return world == null ? this.pipeline.reloads().resources(connection, kind(path), path, managedPack) diff --git a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java index f2a1738a..b4ad6c8d 100644 --- a/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java +++ b/companion/src/main/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/PackResourceEditor.java @@ -37,6 +37,7 @@ import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionException; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.Supplier; @@ -487,6 +488,8 @@ private boolean save(Consumer after) { Map alongside = alongside(); String expected = this.baseline; String[] written = new String[1]; + // The saved copy as a read of it shows it: the pack saved into can keep an animation of its own for the pixels. + AtomicReference savedCopy = new AtomicReference<>(edited); // Encoding a large texture takes a while, so it runs with the rest of the save, and so does its hash. CompletableFuture.supplyAsync(() -> { try { @@ -502,7 +505,15 @@ private boolean save(Consumer after) { } catch (IOException exception) { throw new CompletionException(exception); } - }, Workers.files()).thenCompose(bytes -> this.edits.save(this.path, into, bytes, alongside, expected)) + }, Workers.files()).thenCompose(bytes -> this.edits.save(this.path, into, bytes, alongside, expected) + .thenApplyAsync(saved -> { + try { + savedCopy.set(decode(bytes, saved.pack())); + } catch (IOException | RuntimeException unreadable) { + // The bytes were encoded from what is shown; the copy stays as edited. + } + return saved; + }, Workers.files())) .whenComplete((saved, failure) -> SwingUtilities.invokeLater(() -> { // The reads go on afterwards, whatever happens here, unless another save takes the hold over. boolean savingAgain = false; @@ -532,10 +543,10 @@ private boolean save(Consumer after) { this.packHash = written[0]; boolean keepEdits = !same(shown(), edited); showPack(saved.pack()); - this.packContent = edited; + this.packContent = savedCopy.get(); this.managed = true; - if (keepEdits) markSaved(edited); - else load(edited); + if (keepEdits) markSaved(this.packContent); + else load(this.packContent); showSaved(saved); changed(); // Another tab's save that came while this one ran was not read then. diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java index 18e65e2f..647ffcb1 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/pack/ResourceEditsTest.java @@ -2,6 +2,7 @@ import com.github.minecraft_ta.totalDebugCompanion.change.ChangePipeline; import com.github.minecraft_ta.totalDebugCompanion.catalog.ConfigChanges; +import com.github.minecraft_ta.totalDebugCompanion.catalog.LevelDat; import com.github.minecraft_ta.totalDebugCompanion.catalog.LevelDatFixture; import com.github.minecraft_ta.totalDebugCompanion.change.Effect; import com.github.minecraft_ta.totalDebugCompanion.game.GameLocations; @@ -9,6 +10,7 @@ import com.github.minecraft_ta.totalDebugCompanion.storage.ResourceOriginals; import com.github.minecraft_ta.totaldebug.protocol.message.ClientPacksPayload; import com.github.minecraft_ta.totaldebug.protocol.message.PackStackPayload; +import com.github.minecraft_ta.totaldebug.protocol.nbt.NbtData; import com.github.minecraft_ta.totaldebug.protocol.message.PlayingPayload; import com.github.minecraft_ta.totaldebug.protocol.message.ReloadPayload; import com.github.minecraft_ta.totaldebug.protocol.message.ReloadResultPayload; @@ -38,6 +40,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -233,6 +236,78 @@ void dataGoesToTheWorldPlayedLastWhileNoneIsOpen() throws Exception { assertTrue(Files.readString(saved.pack().resolve("pack.mcmeta")).contains("\"pack_format\":48")); } + @Test + void aSaveIntoAClosedWorldThatDisabledTheManagedDatapackEnablesItThere() throws Exception { + Path world = this.directory.resolve("saves/World"); + Map data = LevelDatFixture.world("World"); + data.put("DataPacks", Map.of("Enabled", List.of("vanilla"), "Disabled", List.of(ResourceEdits.PACK_ID, "file/Off"))); + LevelDatFixture.write(world, data); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + + ResourceEdits.Saved saved = edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertEquals(Effect.WORLD_OPENS, saved.effect()); + assertEquals("", saved.reloadFailure()); + assertEquals(List.of("vanilla"), DatapackSelection.saved(world), + "the game enables it as a pack it has not seen, where it places any new pack; the recorded selection stays"); + NbtData.CompoundTag packs = (NbtData.CompoundTag) ((NbtData.CompoundTag) LevelDat.read(LevelDat.file(world)).tag() + .entries().get("Data")).entries().get("DataPacks"); + assertEquals(List.of(new NbtData.StringTag("file/Off")), ((NbtData.ListTag) packs.entries().get("Disabled")).items(), + "the player's other choices stay"); + } + + @Test + void aSaveIntoAClosedWorldThatDoesNotNameTheManagedDatapackLeavesItsLevelDat() throws Exception { + Path world = this.directory.resolve("saves/World"); + LevelDatFixture.write(world, LevelDatFixture.world("World")); + byte[] before = Files.readAllBytes(world.resolve("level.dat")); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + + edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertArrayEquals(before, Files.readAllBytes(world.resolve("level.dat")), "the game enables a new pack when it loads the world"); + } + + @Test + void aWorldLoadSaveAsksTheReloadThatEnablesTheManagedDatapackOnlyWhereTheServerDoesNotUseIt() throws Exception { + Path world = this.directory.resolve("saves/World"); + LevelDatFixture.write(world, LevelDatFixture.world("World")); + ResourceEdits edits = edits(ChangeRecord.inMemory()); + List sent = new CopyOnWriteArrayList<>(); + edits.location().connected(message -> { + if (SentMessage.of(message).message() instanceof ReloadMessage reload) sent.add(reload.payload()); + return true; + }); + PlayingPayload playing = new PlayingPayload.Singleplayer(world.toString()); + edits.location().playing(playing); + edits.packs().named(new ClientPacksPayload(STACK, 48)); + String biome = "data/testmod/worldgen/biome/glade.json"; + + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""), + new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""))), ""); + assertEquals(Effect.REJOIN, edits.save(biome, bytes("{}")).get(5, TimeUnit.SECONDS).effect()); + assertTrue(sent.isEmpty(), "the world reads the file when it loads again"); + + + edits.packs().datapacks(playing.identity(), new PackStackPayload(48, List.of(new PackStackPayload.Pack("vanilla", "Default", ""))), ""); + CompletableFuture saved = edits.save(biome, bytes("{\"a\":1}")); + awaitSent(sent, 1); + assertEquals(Set.of(ReloadPayload.Kind.DATA), sent.getFirst().kinds()); + assertEquals(ResourceEdits.PACK_ID, sent.getFirst().managedDataPack(), "the reload enables the managed datapack"); + edits.pipeline().reloads().relayFailed(sent.getFirst().requestId(), "The server does not have TotalDebug"); + assertEquals(Effect.REJOIN, saved.get(5, TimeUnit.SECONDS).effect()); + assertEquals("The server does not have TotalDebug", saved.get().reloadFailure()); + + CompletableFuture parsed = edits.save(biome, bytes("{\"a\":2}")); + awaitSent(sent, 2); + edits.pipeline().reloads().answered(new ReloadResultPayload(sent.get(1).requestId(), 10, + List.of(new ReloadResultPayload.Problem(biome, "Unknown biome field a")), "")); + assertEquals(Effect.REJOIN, parsed.get(5, TimeUnit.SECONDS).effect()); + assertEquals(List.of("Unknown biome field a"), parsed.get().problems(), "the reload's problems with the file are the save's"); + } + @Test void aDataReloadNamesTheWorldItsDataWasWrittenFor() throws Exception { Path world = this.directory.resolve("saves/World"); @@ -297,7 +372,34 @@ void aDatapackOfAWorldTheUnconnectedGameHasOpenIsWrittenForItsNextLoad() throws assertEquals(Effect.WORLD_OPENS, saved.effect()); assertEquals("The world World is open in a game that is not connected to Companion; it uses the change when the world is loaded again", saved.reloadFailure()); + + Files.write(world.resolve("level.dat"), new byte[]{1, 2, 3}); + String unread = edits.save("data/testmod/recipe/gear.json", bytes("{\"a\":1}")).get(5, TimeUnit.SECONDS).reloadFailure(); + assertTrue(unread.startsWith("The world World is open in a game that is not connected to Companion, and whether its " + + "level.dat enables the TotalDebug datapack could not be read: "), unread); + } + } + + @Test + void aDatapackOfAWorldTheUnconnectedGameHasOpenWithTheManagedPackDisabledSaysWhatEnablesIt() throws Exception { + Path world = this.directory.resolve("saves/World"); + Map data = LevelDatFixture.world("World"); + data.put("DataPacks", Map.of("Enabled", List.of("vanilla"), "Disabled", List.of(ResourceEdits.PACK_ID))); + LevelDatFixture.write(world, data); + byte[] levelDat = Files.readAllBytes(world.resolve("level.dat")); + Path pack = Files.createDirectories(world.resolve("datapacks/TotalDebug")); + Files.writeString(pack.resolve("pack.mcmeta"), "{\"pack\":{\"pack_format\":48,\"description\":\"\"}}"); + ResourceEdits edits = ResourceEditsFixture.edits(GameLocations.of(this.directory, true), ChangeRecord.inMemory(), + new ResourceOriginals(this.directory.resolve("total-debug/originals")), Runnable::run, InstanceState.inMemory()); + + try (FileChannel channel = FileChannel.open(world.resolve("session.lock"), StandardOpenOption.CREATE, StandardOpenOption.WRITE); + FileLock ignored = channel.lock()) { + ResourceEdits.Saved saved = edits.save("data/testmod/recipe/gear.json", bytes("{}")).get(5, TimeUnit.SECONDS); + + assertEquals("The world World is open in a game that is not connected to Companion, and its level.dat disables the " + + "TotalDebug datapack; the next save after the world closes enables it", saved.reloadFailure()); } + assertArrayEquals(levelDat, Files.readAllBytes(world.resolve("level.dat")), "the open world's level.dat is its own to write"); } @Test diff --git a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java index 40dd4efb..8d540ed8 100644 --- a/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java +++ b/companion/src/test/java/com/github/minecraft_ta/totalDebugCompanion/ui/components/editors/TextureEditorTest.java @@ -179,6 +179,36 @@ void thePacksCopyPlaysItsOwnAnimation() throws Exception { } } + @Test + void aSaveIntoAPackWithItsOwnAnimationPlaysThatAnimation() throws Exception { + ResourceEdits edits = ResourceEditsFixture.edits(GameLocations.of(this.directory, false), ChangeRecord.inMemory(), + new ResourceOriginals(this.directory.resolve("total-debug/originals")), Runnable::run, + InstanceState.inMemory()); + edits.packs().named(new ClientPacksPayload(new PackStackPayload(34, List.of(new PackStackPayload.Pack(ResourceEdits.PACK_ID, "TotalDebug", ""))), 48)); + // The pack has the texture's animation but not the texture: the save keeps the pack's animation. + Path copy = edits.pack(TEXTURE).resolve(TEXTURE); + Files.createDirectories(copy.getParent()); + Files.writeString(copy.resolveSibling("gear.png.mcmeta"), "{\"animation\":{\"frametime\":2}}"); + + TextureEditor[] editor = new TextureEditor[1]; + SwingUtilities.invokeAndWait(() -> editor[0] = new TextureEditor(TEXTURE, "testmod.jar", null, + new LoadedResource.Image(new BufferedImage(4, 8, BufferedImage.TYPE_INT_ARGB), 100), edits, ignored -> { })); + SwingUtilities.invokeAndWait(() -> UiTestScope.showPages(editor[0])); + try { + awaitOnSwing(() -> editor[0].targetBox().getItemCount() > 0); + SwingUtilities.invokeAndWait(() -> { + selectTool(editor[0], "Pencil"); + click(editor[0], new Point(1, 2), 0); + editor[0].save(); + }); + awaitOnSwing(() -> Files.isRegularFile(copy) && !editor[0].modified()); + SwingUtilities.invokeAndWait(() -> assertEquals(4, editor[0].view().shownRegion().height, + "the saved copy plays the pack's animation, two frames of 4 x 4, as the game does")); + } finally { + SwingUtilities.invokeAndWait(editor[0]::dispose); + } + } + /** Clicks the toolbar button with the accessible name {@code name}. */ private static void selectTool(TextureEditor editor, String name) { for (Component component : allComponents(editor.view())) {