Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,31 @@ public void writeFile(List<Write<ChangeRecord.PackSelection, List<String>>> 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<String> 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<String> saved(Path world) throws IOException {
return strings(dataPacks(LevelDat.read(LevelDat.file(world)).tag()), "Enabled");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -601,31 +601,64 @@ private CompletableFuture<Saved> apply(String path, List<String> alsoWatched, Pa
"The TotalDebug pack could not be enabled in options.txt: " + exception.getMessage()));
}
}
if (!assets && managed(pack) && !game.isOpen(world)) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Report when an open world's disabled pack cannot be enabled

When the target world is open in an unconnected game, this condition skips enableDisabled, and the following branch says the change will be used when the world is loaded again. If level.dat already disables file/TotalDebug, however, reopening the world still leaves the pack disabled, and there is no later operation that enables it. Return the actual unmet requirement—connect the game or close the world and retry—instead of reporting delayed success.

AGENTS.md reference: AGENTS.md:L11-L11

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a5ceb8d: when the open world's level.dat disables the managed pack, the save says so and that the next save after the world closes enables it, instead of promising the next load. level.dat stays untouched while the world is open.

// 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<ReloadResultPayload> reload(GameLocation.Connection connection, Path world, String path, String managedPack) {
return world == null ? this.pipeline.reloads().resources(connection, kind(path), path, managedPack)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -487,6 +488,8 @@ private boolean save(Consumer<Path> after) {
Map<String, byte[]> 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<V> 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 {
Expand All @@ -502,7 +505,15 @@ private boolean save(Consumer<Path> 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;
Expand Down Expand Up @@ -532,10 +543,10 @@ private boolean save(Consumer<Path> 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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

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;
import com.github.minecraft_ta.totalDebugCompanion.storage.ChangeRecord;
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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<String, Object> 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<ReloadPayload> 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<ResourceEdits.Saved> 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<ResourceEdits.Saved> 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");
Expand Down Expand Up @@ -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<String, Object> 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
Expand Down
Loading