From 03754d38254ee708ac84499bedf35390b14eceb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Wed, 14 Oct 2026 18:01:39 +0800 Subject: [PATCH 01/16] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20DataPack?= =?UTF-8?q?.Pack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 4 +- .../ui/instances/DataPackListPageSkin.java | 10 +- .../hmcl/addon/datapack/DataPack.java | 164 ++++++++---------- 3 files changed, 78 insertions(+), 100 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index b533b4326bf..817bfe0f7bd 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -104,7 +104,7 @@ void removeSelected(ObservableList sele .map(DataPackListPageSkin.DataPackInfoObject::getPackInfo) .forEach(pack -> { try { - dataPack.deletePack(pack); + pack.delete(); } catch (IOException e) { // Fail to remove mods if the game is running or the datapack is absent. LOG.warning("Failed to delete datapack \"" + pack.getId() + "\"", e); @@ -148,7 +148,7 @@ void openDataPackFolder() { return dataPack -> { String id = dataPack.getPackInfo().getId(); - String description = dataPack.getPackInfo().getDescription().toString(); + String description = dataPack.getPackInfo().getInfo().description().toString(); return stringPredicate.test(id) || stringPredicate.test(description); }; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index ae339417032..3cafdbb405a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -273,7 +273,7 @@ String getTitle() { } String getSubtitle() { - return packInfo.getDescription().toString(); + return packInfo.getInfo().description().toString(); } DataPack.Pack getPackInfo() { @@ -288,20 +288,20 @@ private Image loadIcon() { Image image = null; Path imagePath; if (this.getPackInfo().isDirectory()) { - imagePath = getPackInfo().getPath().resolve("pack.png"); + imagePath = getPackInfo().getFile().resolve("pack.png"); try { image = FXUtils.loadImage(imagePath, 64, 64, true, true); } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + getPackInfo().getPath(), e); + LOG.warning("fail to load image, datapack path: " + getPackInfo().getFile(), e); } } else { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(getPackInfo().getPath())) { + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(getPackInfo().getFile())) { imagePath = fs.getPath("/pack.png"); if (Files.exists(imagePath)) { image = FXUtils.loadImage(imagePath, 64, 64, true, true); } } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + getPackInfo().getPath(), e); + LOG.warning("fail to load image, datapack path: " + getPackInfo().getFile(), e); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index ec88a03808f..e16ad041bf2 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -17,7 +17,6 @@ */ package org.jackhuang.hmcl.addon.datapack; -import com.google.gson.JsonParseException; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; @@ -31,6 +30,7 @@ import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.io.Unzipper; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; +import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.file.*; @@ -42,7 +42,6 @@ public class DataPack { private static final String DISABLED_EXT = "disabled"; - private static final String ZIP_EXT = "zip"; private final Path path; private final ObservableList packs = FXCollections.observableArrayList(); @@ -157,16 +156,6 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber loadFromDir(); } - public void deletePack(Pack packToDelete) throws IOException { - Path pathToDelete = packToDelete.path; - if (Files.isDirectory(pathToDelete)) - FileUtils.deleteDirectory(pathToDelete); - else if (Files.isRegularFile(pathToDelete)) - Files.delete(pathToDelete); - - Platform.runLater(() -> packs.removeIf(p -> p.getId().equals(packToDelete.getId()))); - } - public void loadFromDir() { try { loadFromDir(path); @@ -180,94 +169,53 @@ private void loadFromDir(Path dir) throws IOException { try (Stream stream = Files.list(dir)) { discoveredPacks = stream .parallel() - .map(this::loadSinglePackFromPath) - .flatMap(Optional::stream) - .sorted(Comparator.comparing(Pack::getId, String.CASE_INSENSITIVE_ORDER)) - .collect(Collectors.toList()); + .map(packPath -> { + try { + return new Pack(packPath, this); + } catch (IOException e) { + LOG.warning("Failed to load pack " + packPath, e); + } + return null; + }) + .filter(Objects::nonNull) + .sorted() + .toList(); } Platform.runLater(() -> this.packs.setAll(discoveredPacks)); } - private Optional loadSinglePackFromPath(Path path) { - if (Files.isDirectory(path)) { - return loadSinglePackFromDirectory(path); - } else if (Files.isRegularFile(path)) { - return loadSinglePackFromZipFile(path); - } - return Optional.empty(); - } - - private Optional loadSinglePackFromDirectory(Path path) { - Path mcmeta = path.resolve("pack.mcmeta"); - Path mcmetaDisabled = path.resolve("pack.mcmeta.disabled"); - - if (!Files.exists(mcmeta) && !Files.exists(mcmetaDisabled)) { - return Optional.empty(); - } - - Path targetPath = Files.exists(mcmeta) ? mcmeta : mcmetaDisabled; - return parsePack(path, true, FileUtils.getNameWithoutExtension(path), targetPath); - } - - private Optional loadSinglePackFromZipFile(Path path) { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { - Path mcmeta = fs.getPath("pack.mcmeta"); - - if (!Files.exists(mcmeta)) { - return Optional.empty(); - } - - String packName = FileUtils.getName(path); - if (FileUtils.getExtension(path).equals(DISABLED_EXT)) { - packName = FileUtils.getNameWithoutExtension(packName); - } - packName = FileUtils.getNameWithoutExtension(packName); - - return parsePack(path, false, packName, mcmeta); - } catch (IOException e) { - LOG.warning("IO error reading " + path, e); - return Optional.empty(); - } - } - - private Optional parsePack(Path dataPackPath, boolean isDirectory, String name, Path mcmetaPath) { - try { - PackMcMeta mcMeta = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class); - return Optional.of(new Pack(dataPackPath, isDirectory, name, mcMeta.pack().description(), this)); - } catch (JsonParseException e) { - LOG.warning("Invalid pack.mcmeta format in " + dataPackPath, e); - } catch (IOException e) { - LOG.warning("IO error reading " + dataPackPath, e); - } - return Optional.empty(); - } - - public static class Pack { + public static class Pack extends LocalAddonFile implements Comparable { private Path path; private final boolean isDirectory; private Path statusFile; private final BooleanProperty activeProperty; private final String id; - private final LocalAddonFile.Description description; - private final DataPack parentDataPack; + private final PackMcMeta.PackInfo info; + private final DataPack manager; - public Pack(Path path, boolean isDirectory, String id, LocalAddonFile.Description description, DataPack parentDataPack) { + public Pack(Path path, DataPack manager) throws IOException { this.path = path; - this.isDirectory = isDirectory; - this.id = id; - this.description = description; - this.parentDataPack = parentDataPack; + this.manager = manager; + isDirectory = Files.isDirectory(path); - this.statusFile = initializeStatusFile(path, isDirectory); - this.activeProperty = initializeActiveProperty(); - } + String idd = FileUtils.getNameWithoutExtension(path); + if (!isDirectory && FileUtils.getExtension(path).equals(DISABLED_EXT)) + idd = FileUtils.getNameWithoutExtension(idd); + id = idd; - private Path initializeStatusFile(Path path, boolean isDirectory) { + Path mcmetaPath; if (isDirectory) { - Path mcmeta = path.resolve("pack.mcmeta"); - return Files.exists(mcmeta) ? mcmeta : path.resolve("pack.mcmeta.disabled"); - } - return path; + Path mcmeta1 = path.resolve("pack.mcmeta"); + mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); + } else + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { + mcmetaPath = fs.getPath("pack.mcmeta"); + } + + info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + statusFile = isDirectory ? mcmetaPath : path; + + this.activeProperty = initializeActiveProperty(); } private BooleanProperty initializeActiveProperty() { @@ -310,12 +258,8 @@ public String getId() { return id; } - public LocalAddonFile.Description getDescription() { - return description; - } - - public DataPack getParentDataPack() { - return parentDataPack; + public PackMcMeta.PackInfo getInfo() { + return info; } public BooleanProperty activeProperty() { @@ -330,13 +274,47 @@ public void setActive(boolean active) { this.activeProperty.set(active); } - public Path getPath() { + @Override + public Path getFile() { return path; } public boolean isDirectory() { return isDirectory; } + + @Override + public String getFileName() { + return id; + } + + @Override + public void markDisabled() { + } + + @Override + public void setOld(boolean old) { + } + + @Override + public boolean keepOldFiles() { + return false; + } + + @Override + public void delete() throws IOException { + if (isDirectory) + FileUtils.deleteDirectory(path); + else + Files.delete(path); + + Platform.runLater(() -> manager.packs.removeIf(p -> p.getId().equals(id))); + } + + @Override + public int compareTo(@NotNull DataPack.Pack o) { + return String.CASE_INSENSITIVE_ORDER.compare(id, o.id); + } } } From 18cac93f4323e3320166b479741f682298ac1522 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Wed, 14 Oct 2026 18:43:30 +0800 Subject: [PATCH 02/16] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20DataPack?= =?UTF-8?q?.Pack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/addon/datapack/DataPack.java | 47 ++++++------------- 1 file changed, 15 insertions(+), 32 deletions(-) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index e16ad041bf2..722ec3e5e6e 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -215,43 +215,26 @@ public Pack(Path path, DataPack manager) throws IOException { info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); statusFile = isDirectory ? mcmetaPath : path; - this.activeProperty = initializeActiveProperty(); - } - - private BooleanProperty initializeActiveProperty() { BooleanProperty property = new SimpleBooleanProperty(this, "active", !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)); property.addListener((obs, wasActive, isNowActive) -> { - if (wasActive != isNowActive) { - handleFileRename(isNowActive); - } - }); - return property; - } + if (isNowActive == wasActive) + return; - private void handleFileRename(boolean isNowActive) { - Path newStatusFile = calculateNewStatusFilePath(isNowActive); - if (statusFile.equals(newStatusFile)) { - return; - } - try { - Files.move(this.statusFile, newStatusFile); - this.statusFile = newStatusFile; - if (!this.isDirectory) { - this.path = newStatusFile; + Path newStatusFile = isNowActive + ? statusFile.getParent().resolve(FileUtils.getNameWithoutExtension(statusFile)) + : statusFile.getParent().resolve(FileUtils.getName(statusFile) + "." + DISABLED_EXT); + + try { + Files.move(statusFile, newStatusFile); + } catch (IOException e) { + LOG.warning("Unable to rename file from " + this.statusFile + " to " + newStatusFile, e); } - } catch (IOException e) { - LOG.warning("Unable to rename file from " + this.statusFile + " to " + newStatusFile, e); - } - } - private Path calculateNewStatusFilePath(boolean isActive) { - boolean isFileDisabled = DISABLED_EXT.equals(FileUtils.getExtension(this.statusFile)); - if (isActive && isFileDisabled) { - return this.statusFile.getParent().resolve(FileUtils.getNameWithoutExtension(this.statusFile)); - } else if (!isActive && !isFileDisabled) { - return this.statusFile.getParent().resolve(FileUtils.getName(this.statusFile) + "." + DISABLED_EXT); - } - return this.statusFile; + statusFile = newStatusFile; + if (!isDirectory) + this.path = newStatusFile; + }); + this.activeProperty = property; } public String getId() { From e4aa23f3cac8eb3e840d34e813675a09bb55762a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Wed, 14 Oct 2026 19:06:42 +0800 Subject: [PATCH 03/16] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=9B=9E?= =?UTF-8?q?=E5=BD=92=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/addon/datapack/DataPack.java | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index 722ec3e5e6e..49ee2cb1f4b 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -17,6 +17,7 @@ */ package org.jackhuang.hmcl.addon.datapack; +import com.google.gson.JsonParseException; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; @@ -172,7 +173,7 @@ private void loadFromDir(Path dir) throws IOException { .map(packPath -> { try { return new Pack(packPath, this); - } catch (IOException e) { + } catch (IOException | JsonParseException e) { LOG.warning("Failed to load pack " + packPath, e); } return null; @@ -203,21 +204,21 @@ public Pack(Path path, DataPack manager) throws IOException { idd = FileUtils.getNameWithoutExtension(idd); id = idd; - Path mcmetaPath; if (isDirectory) { Path mcmeta1 = path.resolve("pack.mcmeta"); - mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); - } else + Path mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); + info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + statusFile = mcmetaPath; + } else { try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { - mcmetaPath = fs.getPath("pack.mcmeta"); + info = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("pack.mcmeta")), PackMcMeta.class).pack(); } - - info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); - statusFile = isDirectory ? mcmetaPath : path; + statusFile = path; + } BooleanProperty property = new SimpleBooleanProperty(this, "active", !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)); property.addListener((obs, wasActive, isNowActive) -> { - if (isNowActive == wasActive) + if (isNowActive == !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)) return; Path newStatusFile = isNowActive @@ -226,13 +227,12 @@ public Pack(Path path, DataPack manager) throws IOException { try { Files.move(statusFile, newStatusFile); + statusFile = newStatusFile; + if (!isDirectory) + this.path = newStatusFile; } catch (IOException e) { LOG.warning("Unable to rename file from " + this.statusFile + " to " + newStatusFile, e); } - - statusFile = newStatusFile; - if (!isDirectory) - this.path = newStatusFile; }); this.activeProperty = property; } From d4e8f48d512ce66cc6b00b40609fe891b4a94f14 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Thu, 15 Oct 2026 11:54:12 +0800 Subject: [PATCH 04/16] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20DataPack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 71 ++++++----- .../hmcl/ui/instances/WorldBackupsPage.java | 4 +- .../hmcl/ui/instances/WorldListPage.java | 23 +++- .../hmcl/ui/instances/WorldManagePage.java | 4 + .../hmcl/addon/datapack/DataPack.java | 113 +++++++++--------- .../java/org/jackhuang/hmcl/game/World.java | 33 ++--- 6 files changed, 133 insertions(+), 115 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 817bfe0f7bd..6ceac579dcc 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -30,7 +30,6 @@ import org.jackhuang.hmcl.ui.ListPageBase; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.io.FileUtils; -import org.jackhuang.hmcl.util.javafx.MappedObservableList; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -38,6 +37,7 @@ import java.util.List; import java.util.Locale; import java.util.Objects; +import java.util.concurrent.locks.ReentrantLock; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -48,31 +48,28 @@ public final class DataPackListPage extends ListPageBase Objects.equals("zip", FileUtils.getExtension(it)), - this::installMultiDataPack, this::refresh); - + this::installMultiDataPack); refresh(); } private void installMultiDataPack(List dataPackPath) { - dataPackPath.forEach(this::installSingleDataPack); - if (readOnly.get()) { + dataPackPath.forEach(pack -> { + try { + dataPack.installPack(pack, world.getGameVersion()); + } catch (IOException e) { + LOG.warning("Unable to parse datapack file " + pack, e); + } + }); + if (readOnly.get()) Controllers.showToast(i18n("datapack.reload.toast")); - } - } - - private void installSingleDataPack(Path dataPack) { - try { - this.dataPack.installPack(dataPack, world.getGameVersion()); - } catch (IOException | IllegalArgumentException e) { - LOG.warning("Unable to parse datapack file " + dataPack, e); - } + refresh(); } @Override @@ -82,9 +79,23 @@ protected Skin createDefaultSkin() { public void refresh() { setLoading(true); - Task.runAsync(dataPack::loadFromDir) - .withRunAsync(Schedulers.javafx(), () -> setLoading(false)) - .start(); + Task.supplyAsync(Schedulers.io(), () -> { + lock.lock(); + try { + dataPack.refresh(); + return dataPack.getLocalFiles().stream().map(DataPackListPageSkin.DataPackInfoObject::new).toList(); + } finally { + lock.unlock(); + } + }).whenComplete(Schedulers.javafx(), (result, exception) -> { + if (exception == null) { + getItems().setAll(result); + } else { + LOG.warning("Error refreshing data pack list page", exception); + getItems().clear(); + } + setLoading(false); + }).start(); } public void add() { @@ -95,21 +106,17 @@ public void add() { if (res != null) { installMultiDataPack(res); } - - dataPack.loadFromDir(); } void removeSelected(ObservableList selectedItems) { - selectedItems.stream() - .map(DataPackListPageSkin.DataPackInfoObject::getPackInfo) - .forEach(pack -> { - try { - pack.delete(); - } catch (IOException e) { - // Fail to remove mods if the game is running or the datapack is absent. - LOG.warning("Failed to delete datapack \"" + pack.getId() + "\"", e); - } - }); + try { + if (dataPack.removePacks(selectedItems.stream().map(DataPackListPageSkin.DataPackInfoObject::getPackInfo).toList())) + refresh(); + } catch (IOException e) { + // Fail to remove mods if the game is running or the datapack is absent. + LOG.warning("Failed to delete datapacks", e); + refresh(); + } } void enableSelected(ObservableList selectedItems) { @@ -125,7 +132,7 @@ void disableSelected(ObservableList sel } void openDataPackFolder() { - FXUtils.openFolder(dataPack.getPath()); + FXUtils.openFolder(dataPack.getDirectory()); } @NotNull Predicate updateSearchPredicate(String queryString) { diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java index 7aad9021f94..4798f929fd2 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java @@ -101,7 +101,7 @@ public void refresh() { count = Integer.parseInt(matcher.group("count")); } - result.add(new BackupInfo(path, new World(path), time, count)); + result.add(new BackupInfo(path, new World(path, world.getGameInstance()), time, count)); } } catch (Throwable e) { LOG.warning("Failed to load backup file " + path, e); @@ -144,7 +144,7 @@ void createBackup() { count = Integer.parseInt(matcher.group("count")); } - return Pair.pair(path, new BackupInfo(path, new World(path), time, count)); + return Pair.pair(path, new BackupInfo(path, new World(path, world.getGameInstance()), time, count)); }).whenComplete(Schedulers.javafx(), (result, exception) -> { if (exception == null) { WorldBackupsPage.this.getItems().add(result.getValue()); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java index 2f4cafc12c1..5ee4aadfc70 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java @@ -51,12 +51,14 @@ import java.io.IOException; import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.time.Instant; import java.util.Arrays; import java.util.List; import java.util.Objects; +import java.util.stream.Stream; import static org.jackhuang.hmcl.ui.FXUtils.determineOptimalPopupPosition; import static org.jackhuang.hmcl.util.StringUtils.parseColorEscapes; @@ -128,7 +130,24 @@ public void refresh() { Task.supplyAsync(Schedulers.io(), () -> { // Ensure the game version number is parsed gameInstance.getVersion(); - return World.getWorlds(savesDir); + if (!Files.exists(savesDir)) + return List.of(); + + try (Stream stream = Files.list(savesDir)) { + return stream.filter(Files::isDirectory) + .flatMap(world -> { + try { + return Stream.of(new World(world.toAbsolutePath().normalize(), this.gameInstance)); + } catch (IOException e) { + LOG.warning("Failed to read world " + world, e); + return Stream.empty(); + } + }) + .toList(); + } catch (IOException e) { + LOG.warning("Failed to read saves", e); + return List.of(); + } }).whenComplete(Schedulers.javafx(), (result, exception) -> { if (refreshCount != currentRefresh) { // A newer refresh task is running, discard this result @@ -165,7 +184,7 @@ public void download() { private void installWorld(Path zipFile) { // Only accept one world file because user is required to confirm the new world name // Or too many input dialogs are popped. - Task.supplyAsync(() -> new World(zipFile)) + Task.supplyAsync(() -> new World(zipFile, gameInstance)) .whenComplete(Schedulers.javafx(), world -> { Controllers.prompt(i18n("world.name.enter"), (name, handler) -> { Task.runAsync(() -> world.install(savesDir, name)) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManagePage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManagePage.java index af2113475ee..2786862402b 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManagePage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldManagePage.java @@ -165,6 +165,10 @@ public World getWorld() { return world; } + public HMCLGameInstance getGameInstance() { + return gameInstance; + } + public Path getBackupsDir() { return backupsDir; } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index 49ee2cb1f4b..cb4aa7748a0 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -18,13 +18,12 @@ package org.jackhuang.hmcl.addon.datapack; import com.google.gson.JsonParseException; -import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; -import javafx.collections.FXCollections; -import javafx.collections.ObservableList; import org.jackhuang.hmcl.addon.LocalAddonFile; +import org.jackhuang.hmcl.addon.LocalAddonManager; import org.jackhuang.hmcl.addon.meta.PackMcMeta; +import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; @@ -41,28 +40,20 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; -public class DataPack { +public class DataPack extends LocalAddonManager { private static final String DISABLED_EXT = "disabled"; private final Path path; - private final ObservableList packs = FXCollections.observableArrayList(); - public DataPack(Path path) { - this.path = path; + public DataPack(World world) { + super(world.getGameInstance()); + this.path = world.getFile().resolve("datapacks"); } - public Path getPath() { - return path; - } - - public ObservableList getPacks() { - return packs; - } - - public static void installPack(Path sourceDataPackPath, Path targetDataPackDirectory, GameVersionNumber gameVersionNumber) throws IOException { + public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber) throws IOException { boolean containsMultiplePacks; - Set packs = new HashSet<>(); - try (FileSystem fs = CompressingUtils.readonly(sourceDataPackPath).build()) { + Set packs1 = new HashSet<>(); + try (FileSystem fs = CompressingUtils.readonly(sourcePackPath).build()) { Path dataPacks = fs.getPath("datapacks"); Path mcmeta = fs.getPath("pack.mcmeta"); @@ -76,20 +67,20 @@ public static void installPack(Path sourceDataPackPath, Path targetDataPackDirec if (containsMultiplePacks) { try (Stream s = Files.list(dataPacks)) { - packs = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); + packs1 = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); } } else { - packs.add(FileUtils.getNameWithoutExtension(sourceDataPackPath)); + packs1.add(FileUtils.getNameWithoutExtension(sourcePackPath)); } - try (DirectoryStream stream = Files.newDirectoryStream(targetDataPackDirectory)) { + try (DirectoryStream stream = Files.newDirectoryStream(path)) { for (Path dir : stream) { String packName = FileUtils.getName(dir); if (FileUtils.getExtension(dir).equals(DISABLED_EXT)) { packName = StringUtils.removeSuffix(packName, "." + DISABLED_EXT); } packName = FileUtils.getNameWithoutExtension(packName); - if (packs.contains(packName)) { + if (packs1.contains(packName)) { if (Files.isDirectory(dir)) { FileUtils.deleteDirectory(dir); } else if (Files.isRegularFile(dir)) { @@ -101,9 +92,9 @@ public static void installPack(Path sourceDataPackPath, Path targetDataPackDirec } if (!containsMultiplePacks) { - FileUtils.copyFile(sourceDataPackPath, targetDataPackDirectory.resolve(FileUtils.getName(sourceDataPackPath))); + FileUtils.copyFile(sourcePackPath, path.resolve(FileUtils.getName(sourcePackPath))); } else { - new Unzipper(sourceDataPackPath, targetDataPackDirectory) + new Unzipper(sourcePackPath, path) .setReplaceExistentFile(true) .setSubDirectory("/datapacks/") .unzip(); @@ -114,14 +105,14 @@ public static void installPack(Path sourceDataPackPath, Path targetDataPackDirec && gameVersionNumber.compareTo("26.1-snapshot-6") >= 0; if (useNewResourcePath) { - Files.createDirectories(targetDataPackDirectory.getParent().resolve("resourcepacks")); - targetResourceZipPath = targetDataPackDirectory.getParent().resolve("resourcepacks/resources.zip"); + Files.createDirectories(path.getParent().resolve("resourcepacks")); + targetResourceZipPath = path.getParent().resolve("resourcepacks/resources.zip"); } else { - targetResourceZipPath = targetDataPackDirectory.getParent().resolve("resources.zip"); + targetResourceZipPath = path.getParent().resolve("resources.zip"); } try (FileSystem outputResourcesZipFS = CompressingUtils.createWritableZipFileSystem(targetResourceZipPath); - FileSystem inputPackZipFS = CompressingUtils.createReadOnlyZipFileSystem(sourceDataPackPath)) { + FileSystem inputPackZipFS = CompressingUtils.createReadOnlyZipFileSystem(sourcePackPath)) { Path resourcesZip = inputPackZipFS.getPath("resources.zip"); if (Files.isRegularFile(resourcesZip)) { Path tempResourcesFile = Files.createTempFile("hmcl", ".zip"); @@ -150,39 +141,53 @@ public static void installPack(Path sourceDataPackPath, Path targetDataPackDirec Files.delete(packPng); } } + refresh(); } - public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber) throws IOException { - installPack(sourcePackPath, path, gameVersionNumber); - loadFromDir(); + public boolean removePacks(List datapacks) throws IOException { + lock.lock(); + try { + boolean modified = false; + for (Pack pack : datapacks) { + if (pack != null && pack.manager == this) { + pack.delete(); + localFiles.remove(pack); + modified = true; + } + } + return modified; + } finally { + lock.unlock(); + } } - public void loadFromDir() { + @Override + public Path getDirectory() { + return path; + } + + @Override + public void refresh() throws IOException { + lock.lock(); try { - loadFromDir(path); - } catch (Exception e) { - LOG.warning("Failed to read datapacks " + path, e); + localFiles.clear(); + try (Stream stream = Files.list(path)) { + stream.forEach(packPath -> { + try { + localFiles.add(new Pack(packPath, this)); + } catch (IOException | JsonParseException e) { + LOG.warning("Failed to load pack " + packPath, e); + } + }); + } + } finally { + lock.unlock(); } } - private void loadFromDir(Path dir) throws IOException { - List discoveredPacks; - try (Stream stream = Files.list(dir)) { - discoveredPacks = stream - .parallel() - .map(packPath -> { - try { - return new Pack(packPath, this); - } catch (IOException | JsonParseException e) { - LOG.warning("Failed to load pack " + packPath, e); - } - return null; - }) - .filter(Objects::nonNull) - .sorted() - .toList(); - } - Platform.runLater(() -> this.packs.setAll(discoveredPacks)); + @Override + public Comparator getComparator() { + return Pack::compareTo; } public static class Pack extends LocalAddonFile implements Comparable { @@ -290,8 +295,6 @@ public void delete() throws IOException { FileUtils.deleteDirectory(path); else Files.delete(path); - - Platform.runLater(() -> manager.packs.removeIf(p -> p.getId().equals(id))); } @Override diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java index 758ff0e34c5..da6f2cc7bb1 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java @@ -42,6 +42,7 @@ public final class World { private final Path file; + private final DefaultGameInstance gameInstance; private String fileName; private Image icon; @@ -56,8 +57,9 @@ public final class World { private CompoundTag playerData; // Use for both reading/modification and writing back to the file private Path playerDataPath; - public World(Path file) throws IOException { + public World(Path file, DefaultGameInstance gameInstance) throws IOException { this.file = file; + this.gameInstance = gameInstance; if (Files.isDirectory(file)) { fileName = FileUtils.getName(this.file); @@ -127,6 +129,10 @@ public Path getFile() { return file; } + public DefaultGameInstance getGameInstance() { + return gameInstance; + } + public String getFileName() { return fileName; } @@ -348,7 +354,7 @@ public void install(Path savesDir, String name) throws IOException { } } - new World(worldDir).rename(name); + new World(worldDir, gameInstance).rename(name); } else if (Files.isDirectory(file)) { FileUtils.copyDirectory(file, worldDir); } @@ -381,7 +387,7 @@ public void copy(String newName) throws IOException { Path newPath = file.resolveSibling(newName); FileUtils.copyDirectory(file, newPath, path -> !path.contains("session.lock")); - World newWorld = new World(newPath); + World newWorld = new World(newPath, gameInstance); newWorld.rename(newName); } @@ -444,25 +450,4 @@ private static boolean isLocked(Path sessionLockFile) { return false; } } - - public static List getWorlds(Path savesDir) { - if (Files.exists(savesDir)) { - try (Stream stream = Files.list(savesDir)) { - return stream - .filter(Files::isDirectory) - .flatMap(world -> { - try { - return Stream.of(new World(world.toAbsolutePath().normalize())); - } catch (IOException e) { - LOG.warning("Failed to read world " + world, e); - return Stream.empty(); - } - }) - .toList(); - } catch (IOException e) { - LOG.warning("Failed to read saves", e); - } - } - return List.of(); - } } From 42d7b37eb31f55c960c31b9125937a4e310f00c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Thu, 15 Oct 2026 12:00:06 +0800 Subject: [PATCH 05/16] =?UTF-8?q?chore:=20=E4=BF=AE=E5=A4=8D=E5=8F=98?= =?UTF-8?q?=E9=87=8F=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/jackhuang/hmcl/addon/datapack/DataPack.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index cb4aa7748a0..54d480fc196 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -52,7 +52,7 @@ public DataPack(World world) { public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber) throws IOException { boolean containsMultiplePacks; - Set packs1 = new HashSet<>(); + Set packs = new HashSet<>(); try (FileSystem fs = CompressingUtils.readonly(sourcePackPath).build()) { Path dataPacks = fs.getPath("datapacks"); Path mcmeta = fs.getPath("pack.mcmeta"); @@ -67,10 +67,10 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber if (containsMultiplePacks) { try (Stream s = Files.list(dataPacks)) { - packs1 = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); + packs = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); } } else { - packs1.add(FileUtils.getNameWithoutExtension(sourcePackPath)); + packs.add(FileUtils.getNameWithoutExtension(sourcePackPath)); } try (DirectoryStream stream = Files.newDirectoryStream(path)) { @@ -80,7 +80,7 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber packName = StringUtils.removeSuffix(packName, "." + DISABLED_EXT); } packName = FileUtils.getNameWithoutExtension(packName); - if (packs1.contains(packName)) { + if (packs.contains(packName)) { if (Files.isDirectory(dir)) { FileUtils.deleteDirectory(dir); } else if (Files.isRegularFile(dir)) { From 76ea02232bae5908ecbdc32b84bb8a50283744b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Thu, 15 Oct 2026 12:54:28 +0800 Subject: [PATCH 06/16] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20DataPack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 2 +- .../ui/instances/DataPackListPageSkin.java | 2 +- .../hmcl/addon/datapack/DataPack.java | 20 +++++++------------ 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 6ceac579dcc..1862a1de5c6 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -154,7 +154,7 @@ void openDataPackFolder() { } return dataPack -> { - String id = dataPack.getPackInfo().getId(); + String id = dataPack.getPackInfo().getFileName(); String description = dataPack.getPackInfo().getInfo().description().toString(); return stringPredicate.test(id) || stringPredicate.test(description); }; diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index 3cafdbb405a..29a73897041 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -269,7 +269,7 @@ static class DataPackInfoObject extends RecursiveTreeObject } String getTitle() { - return packInfo.getId(); + return packInfo.getFileName(); } String getSubtitle() { diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index 54d480fc196..0c275b6d4b0 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -41,8 +41,6 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; public class DataPack extends LocalAddonManager { - private static final String DISABLED_EXT = "disabled"; - private final Path path; public DataPack(World world) { @@ -76,8 +74,8 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber try (DirectoryStream stream = Files.newDirectoryStream(path)) { for (Path dir : stream) { String packName = FileUtils.getName(dir); - if (FileUtils.getExtension(dir).equals(DISABLED_EXT)) { - packName = StringUtils.removeSuffix(packName, "." + DISABLED_EXT); + if (FileUtils.getName(dir).endsWith(DISABLED_EXTENSION)) { + packName = StringUtils.removeSuffix(packName, DISABLED_EXTENSION); } packName = FileUtils.getNameWithoutExtension(packName); if (packs.contains(packName)) { @@ -205,7 +203,7 @@ public Pack(Path path, DataPack manager) throws IOException { isDirectory = Files.isDirectory(path); String idd = FileUtils.getNameWithoutExtension(path); - if (!isDirectory && FileUtils.getExtension(path).equals(DISABLED_EXT)) + if (!isDirectory && FileUtils.getName(path).endsWith(DISABLED_EXTENSION)) idd = FileUtils.getNameWithoutExtension(idd); id = idd; @@ -221,14 +219,14 @@ public Pack(Path path, DataPack manager) throws IOException { statusFile = path; } - BooleanProperty property = new SimpleBooleanProperty(this, "active", !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)); + BooleanProperty property = new SimpleBooleanProperty(this, "active", !FileUtils.getName(statusFile).endsWith(DISABLED_EXTENSION)); property.addListener((obs, wasActive, isNowActive) -> { - if (isNowActive == !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)) + if (isNowActive == !FileUtils.getName(statusFile).endsWith(DISABLED_EXTENSION)) return; Path newStatusFile = isNowActive - ? statusFile.getParent().resolve(FileUtils.getNameWithoutExtension(statusFile)) - : statusFile.getParent().resolve(FileUtils.getName(statusFile) + "." + DISABLED_EXT); + ? statusFile.resolveSibling(FileUtils.getNameWithoutExtension(statusFile)) + : statusFile.resolveSibling(FileUtils.getName(statusFile) + DISABLED_EXTENSION); try { Files.move(statusFile, newStatusFile); @@ -242,10 +240,6 @@ public Pack(Path path, DataPack manager) throws IOException { this.activeProperty = property; } - public String getId() { - return id; - } - public PackMcMeta.PackInfo getInfo() { return info; } From ef8b49d39f3011d51cfa8c122747953762aec4d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Thu, 15 Oct 2026 14:52:10 +0800 Subject: [PATCH 07/16] =?UTF-8?q?chore:=20=E7=AE=80=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 7 ++--- .../hmcl/addon/datapack/DataPack.java | 27 ++++++++----------- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 1862a1de5c6..74b5bb32520 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -21,7 +21,6 @@ import javafx.collections.ObservableList; import javafx.scene.control.Skin; import javafx.stage.FileChooser; -import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.addon.datapack.DataPack; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; @@ -45,14 +44,12 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; public final class DataPackListPage extends ListPageBase implements WorldManagePage.WorldRefreshable { - private final World world; private final DataPack dataPack; final BooleanProperty readOnly; private final ReentrantLock lock = new ReentrantLock(); public DataPackListPage(WorldManagePage worldManagePage) { - world = worldManagePage.getWorld(); - dataPack = new DataPack(world); + dataPack = new DataPack(worldManagePage.getWorld()); readOnly = worldManagePage.readOnlyProperty(); FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), this::installMultiDataPack); @@ -62,7 +59,7 @@ public DataPackListPage(WorldManagePage worldManagePage) { private void installMultiDataPack(List dataPackPath) { dataPackPath.forEach(pack -> { try { - dataPack.installPack(pack, world.getGameVersion()); + dataPack.installPack(pack); } catch (IOException e) { LOG.warning("Unable to parse datapack file " + pack, e); } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java index 0c275b6d4b0..406276da913 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java @@ -29,7 +29,6 @@ import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.io.Unzipper; -import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.NotNull; import java.io.IOException; @@ -41,14 +40,16 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; public class DataPack extends LocalAddonManager { + private final World world; private final Path path; public DataPack(World world) { super(world.getGameInstance()); + this.world = world; this.path = world.getFile().resolve("datapacks"); } - public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber) throws IOException { + public void installPack(Path sourcePackPath) throws IOException { boolean containsMultiplePacks; Set packs = new HashSet<>(); try (FileSystem fs = CompressingUtils.readonly(sourcePackPath).build()) { @@ -73,11 +74,7 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber try (DirectoryStream stream = Files.newDirectoryStream(path)) { for (Path dir : stream) { - String packName = FileUtils.getName(dir); - if (FileUtils.getName(dir).endsWith(DISABLED_EXTENSION)) { - packName = StringUtils.removeSuffix(packName, DISABLED_EXTENSION); - } - packName = FileUtils.getNameWithoutExtension(packName); + String packName = FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(FileUtils.getName(dir), DISABLED_EXTENSION)); if (packs.contains(packName)) { if (Files.isDirectory(dir)) { FileUtils.deleteDirectory(dir); @@ -99,14 +96,14 @@ public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber Path targetResourceZipPath; // When the version cannot be obtained, the old version logic is used by default. - boolean useNewResourcePath = gameVersionNumber != null - && gameVersionNumber.compareTo("26.1-snapshot-6") >= 0; + boolean useNewResourcePath = world.getGameVersion() != null + && world.getGameVersion().compareTo("26.1-snapshot-6") >= 0; if (useNewResourcePath) { - Files.createDirectories(path.getParent().resolve("resourcepacks")); - targetResourceZipPath = path.getParent().resolve("resourcepacks/resources.zip"); + Files.createDirectories(path.resolveSibling("resourcepacks")); + targetResourceZipPath = path.resolveSibling("resourcepacks/resources.zip"); } else { - targetResourceZipPath = path.getParent().resolve("resources.zip"); + targetResourceZipPath = path.resolveSibling("resources.zip"); } try (FileSystem outputResourcesZipFS = CompressingUtils.createWritableZipFileSystem(targetResourceZipPath); @@ -202,10 +199,8 @@ public Pack(Path path, DataPack manager) throws IOException { this.manager = manager; isDirectory = Files.isDirectory(path); - String idd = FileUtils.getNameWithoutExtension(path); - if (!isDirectory && FileUtils.getName(path).endsWith(DISABLED_EXTENSION)) - idd = FileUtils.getNameWithoutExtension(idd); - id = idd; + String name = FileUtils.getName(path); + id = isDirectory ? name : FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(name, DISABLED_EXTENSION)); if (isDirectory) { Path mcmeta1 = path.resolve("pack.mcmeta"); From 262bb71abdb547c7476f38957bc9173868985b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Sat, 17 Oct 2026 12:59:02 +0800 Subject: [PATCH 08/16] =?UTF-8?q?refactor:=20=E9=87=8D=E6=9E=84=20DataPack?= =?UTF-8?q?=20=E4=B8=BA=20DataPackManager=20=EF=BC=88=E9=A3=8E=E5=91=B3=20?= =?UTF-8?q?LocalAddonManager=EF=BC=8C=E4=BD=86=E4=B8=8D=E6=98=AF=EF=BC=89?= =?UTF-8?q?=EF=BC=8C=E7=A7=BB=E5=8A=A8=20DataPack.Pack=20=E4=B8=BA=20DataP?= =?UTF-8?q?ackFile=20=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 37 +-- .../ui/instances/DataPackListPageSkin.java | 43 ++- .../hmcl/ui/instances/WorldBackupsPage.java | 4 +- .../hmcl/ui/instances/WorldListPage.java | 4 +- .../hmcl/addon/datapack/DataPack.java | 289 ------------------ .../hmcl/addon/datapack/DataPackFile.java | 136 +++++++++ .../hmcl/addon/datapack/DataPackManager.java | 190 ++++++++++++ .../java/org/jackhuang/hmcl/game/World.java | 24 +- 8 files changed, 385 insertions(+), 342 deletions(-) delete mode 100644 HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java create mode 100644 HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java create mode 100644 HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 43a1709330b..3240813bb7a 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -21,7 +21,8 @@ import javafx.collections.ObservableList; import javafx.scene.control.Skin; import javafx.stage.FileChooser; -import org.jackhuang.hmcl.addon.datapack.DataPack; +import org.jackhuang.hmcl.addon.datapack.DataPackFile; +import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.ui.Controllers; @@ -46,12 +47,12 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; public final class DataPackListPage extends ListPageBase implements WorldManagePage.WorldRefreshable { - private final DataPack dataPack; + private final World world; final BooleanProperty readOnly; private final ReentrantLock lock = new ReentrantLock(); public DataPackListPage(WorldManagePage worldManagePage) { - dataPack = new DataPack(worldManagePage.getWorld()); + world = worldManagePage.getWorld(); readOnly = worldManagePage.readOnlyProperty(); FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), this::installMultiDataPack); @@ -61,7 +62,7 @@ public DataPackListPage(WorldManagePage worldManagePage) { private void installMultiDataPack(List dataPackPath) { dataPackPath.forEach(pack -> { try { - dataPack.installPack(pack); + world.getDataPackManager().installPack(pack); } catch (IOException e) { LOG.warning("Unable to parse datapack file " + pack, e); } @@ -81,8 +82,8 @@ public void refresh() { Task.supplyAsync(Schedulers.io(), () -> { lock.lock(); try { - dataPack.refresh(); - return dataPack.getLocalFiles().stream().map(DataPackListPageSkin.DataPackInfoObject::new).toList(); + world.getDataPackManager().refresh(); + return world.getDataPackManager().getLocalFiles().stream().map(DataPackListPageSkin.DataPackInfoObject::new).toList(); } finally { lock.unlock(); } @@ -110,12 +111,12 @@ public void add() { void removeSelected(ObservableList selectedItems) { List failed = new ArrayList<>(); for (DataPackListPageSkin.DataPackInfoObject item : selectedItems) { - DataPack.Pack pack = item.getPackInfo(); + DataPackFile dataPack = item.getFile(); try { - dataPack.removePacks(List.of(pack)); + world.getDataPackManager().removePack(dataPack); } catch (IOException e) { - failed.add(pack.getFile().toString()); - LOG.warning("Failed to delete datapack \"" + pack.getFileName() + "\"", e); + failed.add(dataPack.getFile().toString()); + LOG.warning("Failed to delete datapack \"" + dataPack.getFileName() + "\"", e); } } refresh(); @@ -127,13 +128,13 @@ void removeSelected(ObservableList sele void setSelectedEnabled(ObservableList selectedItems, boolean enabled) { List failed = new ArrayList<>(); selectedItems.stream() - .map(DataPackListPageSkin.DataPackInfoObject::getPackInfo) - .forEach(pack -> { + .map(DataPackListPageSkin.DataPackInfoObject::getFile) + .forEach(dataPack -> { try { - pack.setActive(enabled); + dataPack.setActive(enabled); } catch (IOException e) { - failed.add(pack.getFile().toString()); - LOG.warning("Failed to enable or disable datapack \"" + pack.getFileName() + "\"", e); + failed.add(dataPack.getFile().toString()); + LOG.warning("Failed to enable or disable datapack \"" + dataPack.getFileName() + "\"", e); } }); if (!failed.isEmpty()) @@ -142,7 +143,7 @@ void setSelectedEnabled(ObservableList } void openDataPackFolder() { - FXUtils.openFolder(dataPack.getDirectory()); + FXUtils.openFolder(world.getDataPackManager().getDirectory()); } @NotNull Predicate updateSearchPredicate(String queryString) { @@ -164,8 +165,8 @@ void openDataPackFolder() { } return dataPack -> { - String id = dataPack.getPackInfo().getFileName(); - String description = dataPack.getPackInfo().getInfo().description().toString(); + String id = dataPack.getFile().getFileName(); + String description = dataPack.getFile().getInfo().description().toString(); return stringPredicate.test(id) || stringPredicate.test(description); }; } diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index ee5607deaf4..ea918acd087 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -46,7 +46,7 @@ import javafx.scene.layout.Priority; import javafx.scene.layout.StackPane; import javafx.util.Duration; -import org.jackhuang.hmcl.addon.datapack.DataPack; +import org.jackhuang.hmcl.addon.datapack.DataPackFile; import org.jackhuang.hmcl.ui.Controllers; import org.jackhuang.hmcl.ui.FXUtils; import org.jackhuang.hmcl.ui.SVG; @@ -260,24 +260,23 @@ private void changeToolbar(HBox newToolbar) { } static class DataPackInfoObject extends RecursiveTreeObject { - private final DataPack.Pack packInfo; - private final ItemPropertyAsyncCache iconCache; + private final DataPackFile file; + private final ItemPropertyAsyncCache iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon); - DataPackInfoObject(DataPack.Pack packInfo) { - this.packInfo = packInfo; - this.iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon); + DataPackInfoObject(DataPackFile file) { + this.file = file; } String getTitle() { - return packInfo.getFileName(); + return file.getFileName(); } String getSubtitle() { - return packInfo.getInfo().description().toString(); + return file.getInfo().description().toString(); } - DataPack.Pack getPackInfo() { - return packInfo; + DataPackFile getFile() { + return file; } private Image getDefaultIcon() { @@ -287,21 +286,21 @@ private Image getDefaultIcon() { private Image loadIcon() { Image image = null; Path imagePath; - if (this.getPackInfo().isDirectory()) { - imagePath = getPackInfo().getFile().resolve("pack.png"); + if (file.isDirectory()) { + imagePath = file.getFile().resolve("pack.png"); try { image = FXUtils.loadImage(imagePath, 64, 64, true, true); } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + getPackInfo().getFile(), e); + LOG.warning("fail to load image, datapack path: " + file.getFile(), e); } } else { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(getPackInfo().getFile())) { + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(file.getFile())) { imagePath = fs.getPath("/pack.png"); if (Files.exists(imagePath)) { image = FXUtils.loadImage(imagePath, 64, 64, true, true); } } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + getPackInfo().getFile(), e); + LOG.warning("fail to load image, datapack path: " + file.getFile(), e); } } @@ -319,7 +318,7 @@ private final class DataPackInfoListCell extends MDListCell ImageContainer imageContainer = new ImageContainer(32); final TwoLineListItem content = new TwoLineListItem(); - private final InvalidationListener activeListener = obs -> checkBox.setSelected(getItem().getPackInfo().isActive()); + private final InvalidationListener activeListener = obs -> checkBox.setSelected(getItem().getFile().isActive()); private final WeakInvalidationListener weakActiveListener = new WeakInvalidationListener(activeListener); private @Nullable ReadOnlyBooleanProperty observedActiveProperty; @@ -352,17 +351,17 @@ protected void updateControl(@Nullable DataPackInfoObject dataItem, boolean empt content.setTitle(dataItem.getTitle()); content.setSubtitle(dataItem.getSubtitle()); - DataPack.Pack packInfo = dataItem.getPackInfo(); - (observedActiveProperty = packInfo.activeProperty()).addListener(weakActiveListener); - checkBox.setSelected(packInfo.isActive()); + DataPackFile dataPackInfo = dataItem.getFile(); + (observedActiveProperty = dataPackInfo.activeProperty()).addListener(weakActiveListener); + checkBox.setSelected(dataPackInfo.isActive()); checkBox.setOnAction(event -> { try { - packInfo.setActive(checkBox.isSelected()); + dataPackInfo.setActive(checkBox.isSelected()); } catch (IOException e) { - LOG.warning("Unable to change state of datapack " + packInfo.getFile(), e); + LOG.warning("Unable to change state of datapack " + dataPackInfo.getFile(), e); Controllers.showToast(i18n("datapack.toggle.failed")); } finally { - checkBox.setSelected(packInfo.isActive()); + checkBox.setSelected(dataPackInfo.isActive()); } }); dataItem.iconCache.attachValue(imageContainer.imageProperty(), new WeakReference<>(this.itemProperty())); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java index 4798f929fd2..7aad9021f94 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldBackupsPage.java @@ -101,7 +101,7 @@ public void refresh() { count = Integer.parseInt(matcher.group("count")); } - result.add(new BackupInfo(path, new World(path, world.getGameInstance()), time, count)); + result.add(new BackupInfo(path, new World(path), time, count)); } } catch (Throwable e) { LOG.warning("Failed to load backup file " + path, e); @@ -144,7 +144,7 @@ void createBackup() { count = Integer.parseInt(matcher.group("count")); } - return Pair.pair(path, new BackupInfo(path, new World(path, world.getGameInstance()), time, count)); + return Pair.pair(path, new BackupInfo(path, new World(path), time, count)); }).whenComplete(Schedulers.javafx(), (result, exception) -> { if (exception == null) { WorldBackupsPage.this.getItems().add(result.getValue()); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java index 5ee4aadfc70..84dcc59b831 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/WorldListPage.java @@ -137,7 +137,7 @@ public void refresh() { return stream.filter(Files::isDirectory) .flatMap(world -> { try { - return Stream.of(new World(world.toAbsolutePath().normalize(), this.gameInstance)); + return Stream.of(new World(world.toAbsolutePath().normalize())); } catch (IOException e) { LOG.warning("Failed to read world " + world, e); return Stream.empty(); @@ -184,7 +184,7 @@ public void download() { private void installWorld(Path zipFile) { // Only accept one world file because user is required to confirm the new world name // Or too many input dialogs are popped. - Task.supplyAsync(() -> new World(zipFile, gameInstance)) + Task.supplyAsync(() -> new World(zipFile)) .whenComplete(Schedulers.javafx(), world -> { Controllers.prompt(i18n("world.name.enter"), (name, handler) -> { Task.runAsync(() -> world.install(savesDir, name)) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java deleted file mode 100644 index 65aa377b0d1..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Hello Minecraft! Launcher - * Copyright (C) 2026 huangyuhui and contributors - * - * 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 org.jackhuang.hmcl.addon.datapack; - -import com.google.gson.JsonParseException; -import javafx.beans.property.ReadOnlyBooleanProperty; -import javafx.beans.property.ReadOnlyBooleanWrapper; -import org.jackhuang.hmcl.addon.LocalAddonFile; -import org.jackhuang.hmcl.addon.LocalAddonManager; -import org.jackhuang.hmcl.addon.meta.PackMcMeta; -import org.jackhuang.hmcl.game.World; -import org.jackhuang.hmcl.util.StringUtils; -import org.jackhuang.hmcl.util.gson.JsonUtils; -import org.jackhuang.hmcl.util.io.CompressingUtils; -import org.jackhuang.hmcl.util.io.FileUtils; -import org.jackhuang.hmcl.util.io.Unzipper; -import org.jetbrains.annotations.NotNull; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.jackhuang.hmcl.util.logging.Logger.LOG; - -public class DataPack extends LocalAddonManager { - private final World world; - private final Path path; - - public DataPack(World world) { - super(world.getGameInstance()); - this.world = world; - this.path = world.getFile().resolve("datapacks"); - } - - public void installPack(Path sourcePackPath) throws IOException { - boolean containsMultiplePacks; - Set packs = new HashSet<>(); - try (FileSystem fs = CompressingUtils.readonly(sourcePackPath).build()) { - Path dataPacks = fs.getPath("datapacks"); - Path mcmeta = fs.getPath("pack.mcmeta"); - - if (Files.exists(dataPacks)) { - containsMultiplePacks = true; - } else if (Files.exists(mcmeta)) { - containsMultiplePacks = false; - } else { - throw new IOException("Malformed datapack zip"); - } - - if (containsMultiplePacks) { - try (Stream s = Files.list(dataPacks)) { - packs = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); - } - } else { - packs.add(FileUtils.getNameWithoutExtension(sourcePackPath)); - } - - try (DirectoryStream stream = Files.newDirectoryStream(path)) { - for (Path dir : stream) { - String packName = FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(FileUtils.getName(dir), DISABLED_EXTENSION)); - if (packs.contains(packName)) { - if (Files.isDirectory(dir)) { - FileUtils.deleteDirectory(dir); - } else if (Files.isRegularFile(dir)) { - Files.delete(dir); - } - } - } - } - } - - if (!containsMultiplePacks) { - FileUtils.copyFile(sourcePackPath, path.resolve(FileUtils.getName(sourcePackPath))); - } else { - new Unzipper(sourcePackPath, path) - .setReplaceExistentFile(true) - .setSubDirectory("/datapacks/") - .unzip(); - - Path targetResourceZipPath; - // When the version cannot be obtained, the old version logic is used by default. - boolean useNewResourcePath = world.getGameVersion() != null - && world.getGameVersion().compareTo("26.1-snapshot-6") >= 0; - - if (useNewResourcePath) { - Files.createDirectories(path.resolveSibling("resourcepacks")); - targetResourceZipPath = path.resolveSibling("resourcepacks/resources.zip"); - } else { - targetResourceZipPath = path.resolveSibling("resources.zip"); - } - - try (FileSystem outputResourcesZipFS = CompressingUtils.createWritableZipFileSystem(targetResourceZipPath); - FileSystem inputPackZipFS = CompressingUtils.createReadOnlyZipFileSystem(sourcePackPath)) { - Path resourcesZip = inputPackZipFS.getPath("resources.zip"); - if (Files.isRegularFile(resourcesZip)) { - Path tempResourcesFile = Files.createTempFile("hmcl", ".zip"); - try { - Files.copy(resourcesZip, tempResourcesFile, StandardCopyOption.REPLACE_EXISTING); - try (FileSystem resources = CompressingUtils.createReadOnlyZipFileSystem(tempResourcesFile)) { - FileUtils.copyDirectory(resources.getPath("/"), outputResourcesZipFS.getPath("/")); - } - } finally { - Files.deleteIfExists(tempResourcesFile); - } - } - Path packMcMeta = outputResourcesZipFS.getPath("pack.mcmeta"); - String metaContent = """ - { - "pack": { - "pack_format": 4, - "description": "Modified by HMCL." - } - } - """; - Files.writeString(packMcMeta, metaContent, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - - Path packPng = outputResourcesZipFS.getPath("pack.png"); - if (Files.isRegularFile(packPng)) - Files.delete(packPng); - } - } - refresh(); - } - - public boolean removePacks(List datapacks) throws IOException { - lock.lock(); - try { - boolean modified = false; - for (Pack pack : datapacks) { - if (pack != null && pack.manager == this) { - pack.delete(); - localFiles.remove(pack); - modified = true; - } - } - return modified; - } finally { - lock.unlock(); - } - } - - @Override - public Path getDirectory() { - return path; - } - - @Override - public void refresh() throws IOException { - lock.lock(); - try { - localFiles.clear(); - try (Stream stream = Files.list(path)) { - stream.forEach(packPath -> { - try { - localFiles.add(new Pack(packPath, this)); - } catch (IOException | JsonParseException e) { - LOG.warning("Failed to load pack " + packPath, e); - } - }); - } - } finally { - lock.unlock(); - } - } - - @Override - public Comparator getComparator() { - return Pack::compareTo; - } - - public static class Pack extends LocalAddonFile { - private Path path; - private final boolean isDirectory; - private Path statusFile; - private final ReadOnlyBooleanWrapper activeProperty; - private final String id; - private final PackMcMeta.PackInfo info; - private final DataPack manager; - - public Pack(Path path, DataPack manager) throws IOException { - this.path = path; - this.manager = manager; - isDirectory = Files.isDirectory(path); - - String name = FileUtils.getName(path); - id = isDirectory ? name : FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(name, DISABLED_EXTENSION)); - - if (isDirectory) { - Path mcmeta1 = path.resolve("pack.mcmeta"); - Path mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); - info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); - statusFile = mcmetaPath; - } else { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { - info = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("pack.mcmeta")), PackMcMeta.class).pack(); - } - statusFile = path; - } - - this.activeProperty = new ReadOnlyBooleanWrapper(this, "active", !FileUtils.getName(statusFile).endsWith(DISABLED_EXTENSION)); - } - - public PackMcMeta.PackInfo getInfo() { - return info; - } - - public ReadOnlyBooleanProperty activeProperty() { - return activeProperty.getReadOnlyProperty(); - } - - public boolean isActive() { - return activeProperty.get(); - } - - public void setActive(boolean active) throws IOException { - if (active == isActive()) - return; - - Path newStatusFile = active - ? statusFile.resolveSibling(FileUtils.getNameWithoutExtension(statusFile)) - : statusFile.resolveSibling(FileUtils.getName(statusFile) + DISABLED_EXTENSION); - - Files.move(statusFile, newStatusFile); - statusFile = newStatusFile; - if (!isDirectory) - path = newStatusFile; - - activeProperty.set(active); - } - - @Override - public Path getFile() { - return path; - } - - public boolean isDirectory() { - return isDirectory; - } - - @Override - public String getFileName() { - return id; - } - - @Override - public void markDisabled() { - } - - @Override - public void setOld(boolean old) { - } - - @Override - public boolean keepOldFiles() { - return false; - } - - @Override - public void delete() throws IOException { - if (isDirectory) - FileUtils.deleteDirectory(path); - else - Files.delete(path); - } - - @Override - public int compareTo(@NotNull DataPack.Pack o) { - return String.CASE_INSENSITIVE_ORDER.compare(id, o.id); - } - } - -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java new file mode 100644 index 00000000000..b3cf58b4c36 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -0,0 +1,136 @@ +/* + * Hello Minecraft! Launcher + * Copyright (C) 2026 huangyuhui and contributors + * + * 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 org.jackhuang.hmcl.addon.datapack; + +import javafx.beans.property.ReadOnlyBooleanProperty; +import javafx.beans.property.ReadOnlyBooleanWrapper; +import org.jackhuang.hmcl.addon.LocalAddonFile; +import org.jackhuang.hmcl.addon.meta.PackMcMeta; +import org.jackhuang.hmcl.util.StringUtils; +import org.jackhuang.hmcl.util.gson.JsonUtils; +import org.jackhuang.hmcl.util.io.CompressingUtils; +import org.jackhuang.hmcl.util.io.FileUtils; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.nio.file.FileSystem; +import java.nio.file.Files; +import java.nio.file.Path; + +import static org.jackhuang.hmcl.addon.LocalAddonManager.DISABLED_EXTENSION; + +public class DataPackFile extends LocalAddonFile { + final DataPackManager manager; + private Path path; + private final boolean isDirectory; + private Path statusFile; + private final ReadOnlyBooleanWrapper activeProperty; + private final String id; + private final PackMcMeta.PackInfo info; + + public DataPackFile(DataPackManager manager, Path path) throws IOException { + this.manager = manager; + this.path = path; + isDirectory = Files.isDirectory(path); + + String name = FileUtils.getName(path); + id = isDirectory ? name : FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(name, DISABLED_EXTENSION)); + + if (isDirectory) { + Path mcmeta1 = path.resolve("pack.mcmeta"); + Path mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); + info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + statusFile = mcmetaPath; + } else { + try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { + info = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("pack.mcmeta")), PackMcMeta.class).pack(); + } + statusFile = path; + } + + this.activeProperty = new ReadOnlyBooleanWrapper(this, "active", !FileUtils.getName(statusFile).endsWith(DISABLED_EXTENSION)); + } + + public PackMcMeta.PackInfo getInfo() { + return info; + } + + public ReadOnlyBooleanProperty activeProperty() { + return activeProperty.getReadOnlyProperty(); + } + + public boolean isActive() { + return activeProperty.get(); + } + + public void setActive(boolean active) throws IOException { + if (active == isActive()) + return; + + Path newStatusFile = active + ? statusFile.resolveSibling(FileUtils.getNameWithoutExtension(statusFile)) + : statusFile.resolveSibling(FileUtils.getName(statusFile) + DISABLED_EXTENSION); + + Files.move(statusFile, newStatusFile); + statusFile = newStatusFile; + if (!isDirectory) + path = newStatusFile; + + activeProperty.set(active); + } + + @Override + public Path getFile() { + return path; + } + + public boolean isDirectory() { + return isDirectory; + } + + @Override + public String getFileName() { + return id; + } + + @Override + public void markDisabled() { + } + + @Override + public void setOld(boolean old) { + } + + @Override + public boolean keepOldFiles() { + return false; + } + + @Override + public void delete() throws IOException { + if (isDirectory) + FileUtils.deleteDirectory(path); + else + Files.delete(path); + } + + @Override + public int compareTo(@NotNull DataPackFile o) { + return String.CASE_INSENSITIVE_ORDER.compare(id, o.id); + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java new file mode 100644 index 00000000000..1183b1ac088 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java @@ -0,0 +1,190 @@ +/* + * Hello Minecraft! Launcher + * Copyright (C) 2026 huangyuhui and contributors + * + * 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 org.jackhuang.hmcl.addon.datapack; + +import com.google.gson.JsonParseException; +import org.jackhuang.hmcl.game.World; +import org.jackhuang.hmcl.util.StringUtils; +import org.jackhuang.hmcl.util.io.CompressingUtils; +import org.jackhuang.hmcl.util.io.FileUtils; +import org.jackhuang.hmcl.util.io.Unzipper; +import org.jetbrains.annotations.Unmodifiable; + +import java.io.IOException; +import java.nio.file.*; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.concurrent.locks.ReentrantLock; + +import static org.jackhuang.hmcl.addon.LocalAddonManager.DISABLED_EXTENSION; +import static org.jackhuang.hmcl.util.logging.Logger.LOG; + +public class DataPackManager { + private final World world; + private final Path directory; + protected final Set localFiles = new LinkedHashSet<>(); + private final ReentrantLock lock = new ReentrantLock(); + + public DataPackManager(World world) { + this.world = world; + directory = world.getFile().resolve("datapacks"); + } + + public void installPack(Path sourcePackPath) throws IOException { + lock.lock(); + try { + boolean containsMultiplePacks; + Set packs = new HashSet<>(); + try (FileSystem fs = CompressingUtils.readonly(sourcePackPath).build()) { + Path dataPacks = fs.getPath("datapacks"); + Path mcmeta = fs.getPath("pack.mcmeta"); + + if (Files.exists(dataPacks)) { + containsMultiplePacks = true; + } else if (Files.exists(mcmeta)) { + containsMultiplePacks = false; + } else { + throw new IOException("Malformed datapack zip"); + } + + if (containsMultiplePacks) { + try (Stream s = Files.list(dataPacks)) { + packs = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); + } + } else { + packs.add(FileUtils.getNameWithoutExtension(sourcePackPath)); + } + + try (DirectoryStream stream = Files.newDirectoryStream(directory)) { + for (Path dir : stream) { + String packName = FileUtils.getNameWithoutExtension(StringUtils.removeSuffix(FileUtils.getName(dir), DISABLED_EXTENSION)); + if (packs.contains(packName)) { + if (Files.isDirectory(dir)) { + FileUtils.deleteDirectory(dir); + } else if (Files.isRegularFile(dir)) { + Files.delete(dir); + } + } + } + } + } + + if (!containsMultiplePacks) { + FileUtils.copyFile(sourcePackPath, directory.resolve(FileUtils.getName(sourcePackPath))); + } else { + new Unzipper(sourcePackPath, directory) + .setReplaceExistentFile(true) + .setSubDirectory("/datapacks/") + .unzip(); + + Path targetResourceZipPath; + // When the version cannot be obtained, the old version logic is used by default. + boolean useNewResourcePath = world.getGameVersion() != null + && world.getGameVersion().compareTo("26.1-snapshot-6") >= 0; + + if (useNewResourcePath) { + Files.createDirectories(directory.resolveSibling("resourcepacks")); + targetResourceZipPath = directory.resolveSibling("resourcepacks/resources.zip"); + } else { + targetResourceZipPath = directory.resolveSibling("resources.zip"); + } + + try (FileSystem outputResourcesZipFS = CompressingUtils.createWritableZipFileSystem(targetResourceZipPath); + FileSystem inputPackZipFS = CompressingUtils.createReadOnlyZipFileSystem(sourcePackPath)) { + Path resourcesZip = inputPackZipFS.getPath("resources.zip"); + if (Files.isRegularFile(resourcesZip)) { + Path tempResourcesFile = Files.createTempFile("hmcl", ".zip"); + try { + Files.copy(resourcesZip, tempResourcesFile, StandardCopyOption.REPLACE_EXISTING); + try (FileSystem resources = CompressingUtils.createReadOnlyZipFileSystem(tempResourcesFile)) { + FileUtils.copyDirectory(resources.getPath("/"), outputResourcesZipFS.getPath("/")); + } + } finally { + Files.deleteIfExists(tempResourcesFile); + } + } + Path packMcMeta = outputResourcesZipFS.getPath("pack.mcmeta"); + String metaContent = """ + { + "pack": { + "pack_format": 4, + "description": "Modified by HMCL." + } + } + """; + Files.writeString(packMcMeta, metaContent, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); + + Path packPng = outputResourcesZipFS.getPath("pack.png"); + if (Files.isRegularFile(packPng)) + Files.delete(packPng); + } + } + refresh(); + } finally { + lock.unlock(); + } + } + + public void removePack(DataPackFile dataPack) throws IOException { + lock.lock(); + try { + if (dataPack != null && dataPack.manager == this) { + dataPack.delete(); + localFiles.remove(dataPack); + } + } finally { + lock.unlock(); + } + } + + public Path getDirectory() { + return directory; + } + + public @Unmodifiable List getLocalFiles() { + lock.lock(); + try { + return localFiles.stream().sorted(getComparator()).toList(); + } finally { + lock.unlock(); + } + } + + public void refresh() throws IOException { + lock.lock(); + try { + localFiles.clear(); + try (Stream stream = Files.list(directory)) { + stream.forEach(packPath -> { + try { + localFiles.add(new DataPackFile(this, packPath)); + } catch (IOException | JsonParseException e) { + LOG.warning("Failed to load pack " + packPath, e); + } + }); + } + } finally { + lock.unlock(); + } + } + + public Comparator getComparator() { + return DataPackFile::compareTo; + } +} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java index da6f2cc7bb1..54088afd601 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java @@ -20,6 +20,7 @@ import javafx.scene.image.Image; import org.glavo.nbt.io.NBTCodec; import org.glavo.nbt.tag.*; +import org.jackhuang.hmcl.addon.datapack.DataPackManager; import org.jackhuang.hmcl.util.io.*; import org.jackhuang.hmcl.util.versioning.GameVersionNumber; import org.jetbrains.annotations.Nullable; @@ -42,7 +43,6 @@ public final class World { private final Path file; - private final DefaultGameInstance gameInstance; private String fileName; private Image icon; @@ -57,9 +57,11 @@ public final class World { private CompoundTag playerData; // Use for both reading/modification and writing back to the file private Path playerDataPath; - public World(Path file, DefaultGameInstance gameInstance) throws IOException { + /// Lazily created data pack manager. + private @Nullable DataPackManager dataPackManager; + + public World(Path file) throws IOException { this.file = file; - this.gameInstance = gameInstance; if (Files.isDirectory(file)) { fileName = FileUtils.getName(this.file); @@ -129,10 +131,6 @@ public Path getFile() { return file; } - public DefaultGameInstance getGameInstance() { - return gameInstance; - } - public String getFileName() { return fileName; } @@ -354,7 +352,7 @@ public void install(Path savesDir, String name) throws IOException { } } - new World(worldDir, gameInstance).rename(name); + new World(worldDir).rename(name); } else if (Files.isDirectory(file)) { FileUtils.copyDirectory(file, worldDir); } @@ -387,7 +385,7 @@ public void copy(String newName) throws IOException { Path newPath = file.resolveSibling(newName); FileUtils.copyDirectory(file, newPath, path -> !path.contains("session.lock")); - World newWorld = new World(newPath, gameInstance); + World newWorld = new World(newPath); newWorld.rename(newName); } @@ -450,4 +448,12 @@ private static boolean isLocked(Path sessionLockFile) { return false; } } + + /// Returns the data pack manager for this world. + public DataPackManager getDataPackManager() { + if (dataPackManager == null) { + dataPackManager = new DataPackManager(this); + } + return dataPackManager; + } } From 9914131520e14a9856a3899e84c9f7c50d04fa48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Tue, 20 Oct 2026 22:25:48 +0800 Subject: [PATCH 09/16] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E9=9A=94?= =?UTF-8?q?=E7=A6=BB=E5=AE=89=E8=A3=85=E5=90=8E=E5=88=B7=E6=96=B0=E4=BA=A7?= =?UTF-8?q?=E7=94=9F=E7=9A=84=E8=A7=A3=E6=9E=90=E5=BC=82=E5=B8=B8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/addon/datapack/DataPackFile.java | 18 ++++++++++++------ .../hmcl/addon/datapack/DataPackManager.java | 4 +++- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java index b3cf58b4c36..048b65729ef 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -25,15 +25,15 @@ import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; -import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.NotNullByDefault; import java.io.IOException; -import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import static org.jackhuang.hmcl.addon.LocalAddonManager.DISABLED_EXTENSION; +@NotNullByDefault public class DataPackFile extends LocalAddonFile { final DataPackManager manager; private Path path; @@ -54,11 +54,17 @@ public DataPackFile(DataPackManager manager, Path path) throws IOException { if (isDirectory) { Path mcmeta1 = path.resolve("pack.mcmeta"); Path mcmetaPath = Files.exists(mcmeta1) ? mcmeta1 : path.resolve("pack.mcmeta.disabled"); - info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + try { + info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + } catch (Exception e) { + throw new IOException(e); + } statusFile = mcmetaPath; } else { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { - info = JsonUtils.fromNonNullJson(Files.readString(fs.getPath("pack.mcmeta")), PackMcMeta.class).pack(); + try (var tree = CompressingUtils.openZipTree(path)) { + info = JsonUtils.fromNonNullJson(tree.readTextEntry("/pack.mcmeta"), PackMcMeta.class).pack(); + } catch (Exception e) { + throw new IOException(e); } statusFile = path; } @@ -130,7 +136,7 @@ public void delete() throws IOException { } @Override - public int compareTo(@NotNull DataPackFile o) { + public int compareTo(DataPackFile o) { return String.CASE_INSENSITIVE_ORDER.compare(id, o.id); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java index 1183b1ac088..812bcb8a0a5 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java @@ -23,6 +23,7 @@ import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.io.Unzipper; +import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Unmodifiable; import java.io.IOException; @@ -35,6 +36,7 @@ import static org.jackhuang.hmcl.addon.LocalAddonManager.DISABLED_EXTENSION; import static org.jackhuang.hmcl.util.logging.Logger.LOG; +@NotNullByDefault public class DataPackManager { private final World world; private final Path directory; @@ -144,7 +146,7 @@ public void installPack(Path sourcePackPath) throws IOException { public void removePack(DataPackFile dataPack) throws IOException { lock.lock(); try { - if (dataPack != null && dataPack.manager == this) { + if (dataPack.manager == this) { dataPack.delete(); localFiles.remove(dataPack); } From 929c1cdc12de667715db6c374fbf542f35c2e8ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Mon, 26 Oct 2026 23:12:14 +0800 Subject: [PATCH 10/16] =?UTF-8?q?fix:=20=E4=BF=9D=E7=95=99=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E5=AE=89=E8=A3=85=E5=AF=B9=E9=9D=9E=E6=B3=95=E8=B7=AF?= =?UTF-8?q?=E5=BE=84=E5=BC=82=E5=B8=B8=E7=9A=84=E9=9A=94=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 50 ++++++++++++------- .../resources/assets/lang/I18N.properties | 1 + .../resources/assets/lang/I18N_ar.properties | 2 + .../resources/assets/lang/I18N_de.properties | 2 + .../resources/assets/lang/I18N_es.properties | 2 + .../resources/assets/lang/I18N_ja.properties | 2 + .../resources/assets/lang/I18N_lzh.properties | 2 + .../resources/assets/lang/I18N_ru.properties | 2 + .../resources/assets/lang/I18N_uk.properties | 2 + .../assets/lang/I18N_zh_Hans.properties | 1 + .../assets/lang/I18N_zh_Hant.properties | 1 + .../hmcl/addon/datapack/DataPackManager.java | 2 +- 12 files changed, 49 insertions(+), 20 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 3240813bb7a..31fa7174dcb 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -22,6 +22,7 @@ import javafx.scene.control.Skin; import javafx.stage.FileChooser; import org.jackhuang.hmcl.addon.datapack.DataPackFile; +import org.jackhuang.hmcl.addon.datapack.DataPackManager; import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; @@ -47,29 +48,40 @@ import static org.jackhuang.hmcl.util.logging.Logger.LOG; public final class DataPackListPage extends ListPageBase implements WorldManagePage.WorldRefreshable { - private final World world; + private final DataPackManager dataPackManager; final BooleanProperty readOnly; private final ReentrantLock lock = new ReentrantLock(); public DataPackListPage(WorldManagePage worldManagePage) { - world = worldManagePage.getWorld(); + dataPackManager = worldManagePage.getWorld().getDataPackManager(); readOnly = worldManagePage.readOnlyProperty(); - FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), - this::installMultiDataPack); + FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), this::addFiles); refresh(); } - private void installMultiDataPack(List dataPackPath) { - dataPackPath.forEach(pack -> { - try { - world.getDataPackManager().installPack(pack); - } catch (IOException e) { - LOG.warning("Unable to parse datapack file " + pack, e); + private void addFiles(List files) { + List failures = new ArrayList<>(); + Task.runAsync(() -> { + for (Path file : files) { + try { + dataPackManager.importDataPack(file); + } catch (Exception e) { + LOG.warning("Failed to add data pack", e); + failures.add(file); + } } - }); - if (readOnly.get()) - Controllers.showToast(i18n("datapack.reload.toast")); - refresh(); + }).thenRunAsync(Schedulers.javafx(), () -> { + if (!failures.isEmpty()) { + StringBuilder failure = new StringBuilder(i18n("datapack.add.failed")); + for (Path file: failures) { + failure.append("\n").append(file.toString()); + } + Controllers.dialog(failure.toString(), i18n("message.error"), MessageDialogPane.MessageType.ERROR); + } + if (readOnly.get()) + Controllers.showToast(i18n("datapack.reload.toast")); + refresh(); + }).start(); } @Override @@ -82,8 +94,8 @@ public void refresh() { Task.supplyAsync(Schedulers.io(), () -> { lock.lock(); try { - world.getDataPackManager().refresh(); - return world.getDataPackManager().getLocalFiles().stream().map(DataPackListPageSkin.DataPackInfoObject::new).toList(); + dataPackManager.refresh(); + return dataPackManager.getLocalFiles().stream().map(DataPackListPageSkin.DataPackInfoObject::new).toList(); } finally { lock.unlock(); } @@ -104,7 +116,7 @@ public void add() { chooser.getExtensionFilters().setAll(new FileChooser.ExtensionFilter(i18n("extension.datapack"), "*.zip")); List res = Controllers.showOpenMultipleDialog(chooser); if (res != null) { - installMultiDataPack(res); + addFiles(res); } } @@ -113,7 +125,7 @@ void removeSelected(ObservableList sele for (DataPackListPageSkin.DataPackInfoObject item : selectedItems) { DataPackFile dataPack = item.getFile(); try { - world.getDataPackManager().removePack(dataPack); + dataPackManager.removePack(dataPack); } catch (IOException e) { failed.add(dataPack.getFile().toString()); LOG.warning("Failed to delete datapack \"" + dataPack.getFileName() + "\"", e); @@ -143,7 +155,7 @@ void setSelectedEnabled(ObservableList } void openDataPackFolder() { - FXUtils.openFolder(world.getDataPackManager().getDirectory()); + FXUtils.openFolder(dataPackManager.getDirectory()); } @NotNull Predicate updateSearchPredicate(String queryString) { diff --git a/HMCL/src/main/resources/assets/lang/I18N.properties b/HMCL/src/main/resources/assets/lang/I18N.properties index a3acd76c648..06dccaef4af 100644 --- a/HMCL/src/main/resources/assets/lang/I18N.properties +++ b/HMCL/src/main/resources/assets/lang/I18N.properties @@ -1210,6 +1210,7 @@ nbt.title=View File - %s datapack=Data Packs datapack.add=Add datapack.add.title=Choose data pack archive you want to add +datapack.add.failed=Failed to add data packs: datapack.delete.failed=Failed to delete data pack(s). The data pack file(s) may be in use by another program. datapack.empty=No Data Packs datapack.reload.toast=Minecraft is running. Use the /reload command to reload data packs diff --git a/HMCL/src/main/resources/assets/lang/I18N_ar.properties b/HMCL/src/main/resources/assets/lang/I18N_ar.properties index c20716521cf..c555ecd8fec 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ar.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ar.properties @@ -176,6 +176,7 @@ addon.check_update.empty=جميع المودات محدّثة addon.check_update.failed_check=فشل التحقق من التحديثات. addon.check_update.failed_download=فشل تنزيل بعض الملفات. addon.check_update.file=الملف +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=المصدر addon.check_update.target_version=الإصدار المستهدف @@ -1209,6 +1210,7 @@ nbt.title=عرض الملف - %s datapack=حزم البيانات datapack.add=إضافة datapack.add.title=اختر أرشيف حزمة البيانات التي تريد إضافتها +# datapack.add.failed= # datapack.delete.failed= # datapack.empty= datapack.reload.toast=اللعبة تعمل حالياً، يُرجى استخدام الأمر /reload لإعادة تحميل حزمة البيانات diff --git a/HMCL/src/main/resources/assets/lang/I18N_de.properties b/HMCL/src/main/resources/assets/lang/I18N_de.properties index 9889576db02..fd2aec545c4 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_de.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_de.properties @@ -174,6 +174,7 @@ addon.check_update.empty=Alle Dateien sind auf dem neuesten Stand addon.check_update.failed_check=Fehler beim Suchen nach Aktualisierungen. addon.check_update.failed_download=Fehler beim Herunterladen einiger Dateien. addon.check_update.file=Datei +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=Quelle addon.check_update.target_version=Zielversion @@ -1208,6 +1209,7 @@ nbt.title=Datei ansehen - %s datapack=Datenpakete datapack.add=Hinzufügen datapack.add.title=Wählen Sie das Datenpaket-Archiv, das Sie hinzufügen möchten +# datapack.add.failed= # datapack.delete.failed= datapack.empty=Keine Datenpakete datapack.reload.toast=Minecraft läuft. Verwenden Sie den Befehl /reload, um Datenpakete neu zu laden diff --git a/HMCL/src/main/resources/assets/lang/I18N_es.properties b/HMCL/src/main/resources/assets/lang/I18N_es.properties index 778ee2d6862..65052e042af 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_es.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_es.properties @@ -174,6 +174,7 @@ addon.check_update.empty=Todos los mods están actualizados addon.check_update.failed_check=No se ha podido comprobar si hay actualizaciones. addon.check_update.failed_download=No se han podido descargar algunos de los archivos. addon.check_update.file=Archivo +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=Fuente addon.check_update.target_version=Versión de destino @@ -1201,6 +1202,7 @@ nbt.title=Ver archivo - %s datapack=Paquetes de datos # datapack.add= # datapack.add.title= +# datapack.add.failed= # datapack.delete.failed= # datapack.empty= # datapack.reload.toast= diff --git a/HMCL/src/main/resources/assets/lang/I18N_ja.properties b/HMCL/src/main/resources/assets/lang/I18N_ja.properties index 819101c5c07..69ced6c1a74 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ja.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ja.properties @@ -163,6 +163,7 @@ addon.check_update.current_version=Current addon.check_update.failed_check=更新のチェックに失敗しました addon.check_update.failed_download=一部のファイルのダウンロードに失敗しました addon.check_update.file=ファイル +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=Source addon.check_update.target_version=Target @@ -1009,6 +1010,7 @@ mods.update_modpack_mod.warning=modpack 内の mod を更新すると、修復 datapack=Datapacks # datapack.add= # datapack.add.title= +# datapack.add.failed= # datapack.delete.failed= # datapack.empty= # datapack.reload.toast= diff --git a/HMCL/src/main/resources/assets/lang/I18N_lzh.properties b/HMCL/src/main/resources/assets/lang/I18N_lzh.properties index e5ea348632a..f7c0f47e849 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_lzh.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_lzh.properties @@ -174,6 +174,7 @@ addon.check_update.empty=無改囊可迭更 addon.check_update.failed_check=檢囊迭更未成 addon.check_update.failed_download=有引案未成 addon.check_update.file=案 +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=源 addon.check_update.target_version=將至之版 @@ -1021,6 +1022,7 @@ nbt.title=覽案 - %s datapack=錄囊 datapack.add=增錄囊 datapack.add.title=擇須導入之錄囊緊囊 +# datapack.add.failed= # datapack.delete.failed= # datapack.empty= # datapack.reload.toast= diff --git a/HMCL/src/main/resources/assets/lang/I18N_ru.properties b/HMCL/src/main/resources/assets/lang/I18N_ru.properties index 9382b3f8f23..e759de56e75 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ru.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ru.properties @@ -170,6 +170,7 @@ addon.check_update.empty=Все файлы актуальны addon.check_update.failed_check=Не удалось проверить обновления. addon.check_update.failed_download=Не удалось скачать некоторые файлы. addon.check_update.file=Файл +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=Источник addon.check_update.target_version=Целевая версия @@ -1141,6 +1142,7 @@ nbt.title=Просмотр файла - %s datapack=Наборы данных datapack.add=Добавить datapack.add.title=Выберите архив набора данных, который хотите добавить +# datapack.add.failed= # datapack.delete.failed= datapack.empty=Нет наборов данных datapack.reload.toast=Minecraft запущен. Чтобы перезагрузить наборы данных, используйте команду /reload diff --git a/HMCL/src/main/resources/assets/lang/I18N_uk.properties b/HMCL/src/main/resources/assets/lang/I18N_uk.properties index 7b6ae08f4cf..5b4eb3fece0 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_uk.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_uk.properties @@ -176,6 +176,7 @@ addon.check_update.empty=Усі моди оновлені addon.check_update.failed_check=Не вдалося перевірити оновлення. addon.check_update.failed_download=Не вдалося завантажити деякі файли. addon.check_update.file=Файл +# addon.check_update.only_preview= # addon.check_update.preview= addon.check_update.source=Джерело addon.check_update.target_version=Цільова версія @@ -1164,6 +1165,7 @@ nbt.title=Перегляд файлу - %s datapack=Datapacks datapack.add=Додати datapack.add.title=Виберіть архів пакета даних, який ви хочете додати +# datapack.add.failed= # datapack.delete.failed= datapack.empty=Немає пакетів даних datapack.reload.toast=Minecraft запущено. Використовуйте команду /reload, щоб перезавантажити пакети даних diff --git a/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties b/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties index c47d6a89555..2c5e8713286 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties @@ -1026,6 +1026,7 @@ nbt.title=查看文件 - %s datapack=数据包 datapack.add=添加数据包 datapack.add.title=选择要添加的数据包压缩包 +datapack.add.failed=添加数据包失败: datapack.delete.failed=删除数据包失败,数据包文件可能已被其他程序占用。 datapack.empty=没有数据包 datapack.reload.toast=Minecraft 正在运行,请使用 /reload 命令重新加载数据包 diff --git a/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties b/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties index 703cf92a0f2..0566dfe484b 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties @@ -1020,6 +1020,7 @@ nbt.title=查看檔案 - %s datapack=資料包 datapack.add=新增資料包 datapack.add.title=選取要新增的資料包壓縮檔 +datapack.add.failed=新增資料包失敗: datapack.delete.failed=刪除資料包失敗,資料包檔案可能已被其他程式佔用。 datapack.empty=沒有資料包 datapack.reload.toast=Minecraft 正在執行,請使用 /reload 指令重新載入資料包 diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java index 812bcb8a0a5..09a5ec01924 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java @@ -48,7 +48,7 @@ public DataPackManager(World world) { directory = world.getFile().resolve("datapacks"); } - public void installPack(Path sourcePackPath) throws IOException { + public void importDataPack(Path sourcePackPath) throws IOException { lock.lock(); try { boolean containsMultiplePacks; From 10ebf566a9382887b6a21a70eea380bbba0c6d7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Mon, 26 Oct 2026 23:23:35 +0800 Subject: [PATCH 11/16] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E6=9C=AA?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E7=9A=84=20import?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 1 - .../hmcl/addon/datapack/DataPackFile.java | 19 ++----------------- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index bf9ffde902e..c36a8cf9a44 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -8,7 +8,6 @@ import javafx.stage.FileChooser; import org.jackhuang.hmcl.addon.datapack.DataPackFile; import org.jackhuang.hmcl.addon.datapack.DataPackManager; -import org.jackhuang.hmcl.game.World; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; import org.jackhuang.hmcl.ui.Controllers; diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java index 048b65729ef..a8a63fc8003 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -1,20 +1,5 @@ -/* - * Hello Minecraft! Launcher - * Copyright (C) 2026 huangyuhui and contributors - * - * 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 . - */ +// SPDX-FileCopyrightText: Copyright (C) 2020 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.addon.datapack; import javafx.beans.property.ReadOnlyBooleanProperty; From bc68bc4ff8b9d1117984d6611a39eefe7866fb05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Mon, 26 Oct 2026 23:29:02 +0800 Subject: [PATCH 12/16] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=89=88?= =?UTF-8?q?=E6=9D=83=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/addon/datapack/DataPackManager.java | 19 ++----------------- 1 file changed, 2 insertions(+), 17 deletions(-) diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java index 09a5ec01924..e6698731747 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java @@ -1,20 +1,5 @@ -/* - * Hello Minecraft! Launcher - * Copyright (C) 2026 huangyuhui and contributors - * - * 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 . - */ +// SPDX-FileCopyrightText: Copyright (C) 2020 The HMCL Authors +// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL package org.jackhuang.hmcl.addon.datapack; import com.google.gson.JsonParseException; From 9730d7d44ded76237a51797f43f6433559b42417 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Mon, 9 Nov 2026 17:00:55 +0800 Subject: [PATCH 13/16] =?UTF-8?q?chore:=20=E7=AE=80=E5=8C=96=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 24 ++++++++----------- .../ui/instances/DataPackListPageSkin.java | 15 ++++-------- .../hmcl/addon/datapack/DataPackFile.java | 4 ++++ 3 files changed, 18 insertions(+), 25 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 1750270165b..af2c0a802c8 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -6,7 +6,6 @@ import javafx.collections.ObservableList; import javafx.scene.control.Skin; import javafx.stage.FileChooser; -import org.jackhuang.hmcl.addon.datapack.DataPackFile; import org.jackhuang.hmcl.addon.datapack.DataPackManager; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; @@ -101,15 +100,14 @@ public void add() { void removeSelected(ObservableList selectedItems) { List failed = new ArrayList<>(); - for (DataPackListPageSkin.DataPackInfoObject item : selectedItems) { - DataPackFile dataPack = item.getFile(); + selectedItems.stream().map(DataPackListPageSkin.DataPackInfoObject::getFile).forEach(dataPack -> { try { dataPackManager.removePack(dataPack); } catch (IOException e) { failed.add(dataPack.getFile().toString()); LOG.warning("Failed to delete datapack \"" + dataPack.getFileName() + "\"", e); } - } + }); refresh(); if (!failed.isEmpty()) Controllers.dialog(i18n("datapack.delete.failed") + "\n" + String.join(",\n", failed), @@ -118,16 +116,14 @@ void removeSelected(ObservableList sele void setSelectedEnabled(ObservableList selectedItems, boolean enabled) { List failed = new ArrayList<>(); - selectedItems.stream() - .map(DataPackListPageSkin.DataPackInfoObject::getFile) - .forEach(dataPack -> { - try { - dataPack.setActive(enabled); - } catch (IOException e) { - failed.add(dataPack.getFile().toString()); - LOG.warning("Failed to enable or disable datapack \"" + dataPack.getFileName() + "\"", e); - } - }); + selectedItems.stream().map(DataPackListPageSkin.DataPackInfoObject::getFile).forEach(dataPack -> { + try { + dataPack.setActive(enabled); + } catch (IOException e) { + failed.add(dataPack.getFile().toString()); + LOG.warning("Failed to enable or disable datapack \"" + dataPack.getFileName() + "\"", e); + } + }); if (!failed.isEmpty()) Controllers.dialog(i18n("datapack.toggle.failed") + "\n" + String.join(",\n", failed), i18n("message.error"), MessageDialogPane.MessageType.ERROR); diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index f27c3d31d60..d4564c896c3 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -233,7 +233,8 @@ private void search() { } for (DataPackInfoObject item : getSkinnable().getItems()) { - if (predicate.test(item.getTitle()) || predicate.test(item.getSubtitle())) { + DataPackFile datapack = item.getFile(); + if (predicate.test(datapack.getFileName()) || predicate.test(datapack.getDescription().toString())) { listView.getItems().add(item); } } @@ -260,14 +261,6 @@ static class DataPackInfoObject { this.file = file; } - String getTitle() { - return file.getFileName(); - } - - String getSubtitle() { - return file.getInfo().description().toString(); - } - DataPackFile getFile() { return file; } @@ -345,8 +338,8 @@ protected void updateControl(@Nullable DataPackInfoObject dataItem, boolean empt if (observedActiveProperty != null) observedActiveProperty.removeListener(weakActiveListener); if (empty || dataItem == null) return; - content.setTitle(dataItem.getTitle()); - content.setSubtitle(dataItem.getSubtitle()); + content.setTitle(dataItem.file.getFileName()); + content.setSubtitle(dataItem.file.getDescription().toString()); DataPackFile dataPackInfo = dataItem.getFile(); (observedActiveProperty = dataPackInfo.activeProperty()).addListener(weakActiveListener); diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java index a8a63fc8003..12a84adf9a5 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -61,6 +61,10 @@ public PackMcMeta.PackInfo getInfo() { return info; } + public LocalAddonFile.Description getDescription() { + return info.description(); + } + public ReadOnlyBooleanProperty activeProperty() { return activeProperty.getReadOnlyProperty(); } From a3d38a0fa0e5df1fdf0046ac6d60216fb89339ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Mon, 9 Nov 2026 18:47:52 +0800 Subject: [PATCH 14/16] =?UTF-8?q?fix:=20=E4=BD=BF=E7=94=A8=20toStringSingl?= =?UTF-8?q?eLine?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index d4564c896c3..1ea783a9394 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -339,7 +339,7 @@ protected void updateControl(@Nullable DataPackInfoObject dataItem, boolean empt observedActiveProperty.removeListener(weakActiveListener); if (empty || dataItem == null) return; content.setTitle(dataItem.file.getFileName()); - content.setSubtitle(dataItem.file.getDescription().toString()); + content.setSubtitle(dataItem.file.getDescription().toStringSingleLine()); DataPackFile dataPackInfo = dataItem.getFile(); (observedActiveProperty = dataPackInfo.activeProperty()).addListener(weakActiveListener); From 8374effa8e8546722477af36dc0a38810ab51db0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Wed, 18 Nov 2026 21:56:23 +0800 Subject: [PATCH 15/16] =?UTF-8?q?fix:=20=E4=BD=BF=E7=94=A8=E4=B8=8A?= =?UTF-8?q?=E6=B8=B8=E5=9B=BE=E6=A0=87=E5=8A=A0=E8=BD=BD=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ui/instances/DataPackListPageSkin.java | 28 +- .../hmcl/addon/datapack/DataPack.java | 322 ------------------ .../hmcl/addon/datapack/DataPackFile.java | 23 ++ 3 files changed, 25 insertions(+), 348 deletions(-) delete mode 100644 HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java index 03f05c6a2cf..44ae5f8b3f2 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPageSkin.java @@ -267,32 +267,8 @@ private Image getDefaultIcon() { } private Image loadIcon() { - Image image = null; - Path imagePath; - if (file.isDirectory()) { - imagePath = file.getFile().resolve("pack.png"); - try { - image = ImageLoaders.DEFAULT.load(imagePath, 64, 64, true, true); - } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + file.getFile(), e); - } - } else { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(file.getFile())) { - imagePath = fs.getPath("/pack.png"); - if (Files.exists(imagePath)) { - image = ImageLoaders.DEFAULT.load(imagePath, 64, 64, true, true); - } - } catch (Exception e) { - LOG.warning("fail to load image, datapack path: " + file.getFile(), e); - } - } - - if (image != null && !image.isError() && image.getWidth() > 0 && image.getHeight() > 0 && - Math.abs(image.getWidth() - image.getHeight()) < 1) { - return image; - } else { - return getDefaultIcon(); - } + Image icon = file.loadIcon(ImageLoaders.DEFAULT); + return FXUtils.isValidIcon(icon) ? icon : getDefaultIcon(); } } diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java deleted file mode 100644 index dda6c44eb4c..00000000000 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPack.java +++ /dev/null @@ -1,322 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (C) 2026 The HMCL Authors -// SPDX-License-Identifier: GPL-3.0-or-later WITH AdditionRef-HMCL -package org.jackhuang.hmcl.addon.datapack; - -import com.google.gson.JsonParseException; -import javafx.application.Platform; -import javafx.beans.property.ReadOnlyBooleanProperty; -import javafx.beans.property.ReadOnlyBooleanWrapper; -import javafx.collections.FXCollections; -import javafx.collections.ObservableList; -import org.jackhuang.hmcl.addon.LocalAddonFile; -import org.jackhuang.hmcl.addon.meta.PackMcMeta; -import org.jackhuang.hmcl.image.ImageLoader; -import org.jackhuang.hmcl.util.StringUtils; -import org.jackhuang.hmcl.util.gson.JsonUtils; -import org.jackhuang.hmcl.util.io.CompressingUtils; -import org.jackhuang.hmcl.util.io.FileUtils; -import org.jackhuang.hmcl.util.io.Unzipper; -import org.jackhuang.hmcl.util.versioning.GameVersionNumber; -import org.jetbrains.annotations.Nullable; - -import java.io.IOException; -import java.nio.file.*; -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import static org.jackhuang.hmcl.util.logging.Logger.LOG; - -public class DataPack { - private static final String DISABLED_EXT = "disabled"; - private static final String ZIP_EXT = "zip"; - - private final Path path; - private final ObservableList packs = FXCollections.observableArrayList(); - - public DataPack(Path path) { - this.path = path; - } - - public Path getPath() { - return path; - } - - public ObservableList getPacks() { - return packs; - } - - public static void installPack(Path sourceDataPackPath, Path targetDataPackDirectory, GameVersionNumber gameVersionNumber) throws IOException { - boolean containsMultiplePacks; - Set packs = new HashSet<>(); - try (FileSystem fs = CompressingUtils.readonly(sourceDataPackPath).build()) { - Path dataPacks = fs.getPath("datapacks"); - Path mcmeta = fs.getPath("pack.mcmeta"); - - if (Files.exists(dataPacks)) { - containsMultiplePacks = true; - } else if (Files.exists(mcmeta)) { - containsMultiplePacks = false; - } else { - throw new IOException("Malformed datapack zip"); - } - - if (containsMultiplePacks) { - try (Stream s = Files.list(dataPacks)) { - packs = s.map(FileUtils::getNameWithoutExtension).collect(Collectors.toSet()); - } - } else { - packs.add(FileUtils.getNameWithoutExtension(sourceDataPackPath)); - } - - try (DirectoryStream stream = Files.newDirectoryStream(targetDataPackDirectory)) { - for (Path dir : stream) { - String packName = FileUtils.getName(dir); - if (FileUtils.getExtension(dir).equals(DISABLED_EXT)) { - packName = StringUtils.removeSuffix(packName, "." + DISABLED_EXT); - } - packName = FileUtils.getNameWithoutExtension(packName); - if (packs.contains(packName)) { - if (Files.isDirectory(dir)) { - FileUtils.deleteDirectory(dir); - } else if (Files.isRegularFile(dir)) { - Files.delete(dir); - } - } - } - } - } - - if (!containsMultiplePacks) { - FileUtils.copyFile(sourceDataPackPath, targetDataPackDirectory.resolve(FileUtils.getName(sourceDataPackPath))); - } else { - new Unzipper(sourceDataPackPath, targetDataPackDirectory) - .setReplaceExistentFile(true) - .setSubDirectory("/datapacks/") - .unzip(); - - Path targetResourceZipPath; - // When the version cannot be obtained, the old version logic is used by default. - boolean useNewResourcePath = gameVersionNumber != null - && gameVersionNumber.compareTo("26.1-snapshot-6") >= 0; - - if (useNewResourcePath) { - Files.createDirectories(targetDataPackDirectory.getParent().resolve("resourcepacks")); - targetResourceZipPath = targetDataPackDirectory.getParent().resolve("resourcepacks/resources.zip"); - } else { - targetResourceZipPath = targetDataPackDirectory.getParent().resolve("resources.zip"); - } - - try (FileSystem outputResourcesZipFS = CompressingUtils.createWritableZipFileSystem(targetResourceZipPath); - FileSystem inputPackZipFS = CompressingUtils.createReadOnlyZipFileSystem(sourceDataPackPath)) { - Path resourcesZip = inputPackZipFS.getPath("resources.zip"); - if (Files.isRegularFile(resourcesZip)) { - Path tempResourcesFile = Files.createTempFile("hmcl", ".zip"); - try { - Files.copy(resourcesZip, tempResourcesFile, StandardCopyOption.REPLACE_EXISTING); - try (FileSystem resources = CompressingUtils.createReadOnlyZipFileSystem(tempResourcesFile)) { - FileUtils.copyDirectory(resources.getPath("/"), outputResourcesZipFS.getPath("/")); - } - } finally { - Files.deleteIfExists(tempResourcesFile); - } - } - Path packMcMeta = outputResourcesZipFS.getPath("pack.mcmeta"); - String metaContent = """ - { - "pack": { - "pack_format": 4, - "description": "Modified by HMCL." - } - } - """; - Files.writeString(packMcMeta, metaContent, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING); - - Path packPng = outputResourcesZipFS.getPath("pack.png"); - if (Files.isRegularFile(packPng)) - Files.delete(packPng); - } - } - } - - public void installPack(Path sourcePackPath, GameVersionNumber gameVersionNumber) throws IOException { - installPack(sourcePackPath, path, gameVersionNumber); - loadFromDir(); - } - - public void deletePack(Pack packToDelete) throws IOException { - Path pathToDelete = packToDelete.path; - if (Files.isDirectory(pathToDelete)) - FileUtils.deleteDirectory(pathToDelete); - else if (Files.isRegularFile(pathToDelete)) - Files.delete(pathToDelete); - - Platform.runLater(() -> packs.removeIf(p -> p.getId().equals(packToDelete.getId()))); - } - - public void loadFromDir() { - try { - loadFromDir(path); - } catch (Exception e) { - LOG.warning("Failed to read datapacks " + path, e); - } - } - - private void loadFromDir(Path dir) throws IOException { - List discoveredPacks; - try (Stream stream = Files.list(dir)) { - discoveredPacks = stream - .parallel() - .map(this::loadSinglePackFromPath) - .flatMap(Optional::stream) - .sorted(Comparator.comparing(Pack::getId, String.CASE_INSENSITIVE_ORDER)) - .collect(Collectors.toList()); - } - Platform.runLater(() -> this.packs.setAll(discoveredPacks)); - } - - private Optional loadSinglePackFromPath(Path path) { - if (Files.isDirectory(path)) { - return loadSinglePackFromDirectory(path); - } else if (Files.isRegularFile(path)) { - return loadSinglePackFromZipFile(path); - } - return Optional.empty(); - } - - private Optional loadSinglePackFromDirectory(Path path) { - Path mcmeta = path.resolve("pack.mcmeta"); - Path mcmetaDisabled = path.resolve("pack.mcmeta.disabled"); - - if (!Files.exists(mcmeta) && !Files.exists(mcmetaDisabled)) { - return Optional.empty(); - } - - Path targetPath = Files.exists(mcmeta) ? mcmeta : mcmetaDisabled; - return parsePack(path, true, FileUtils.getNameWithoutExtension(path), targetPath); - } - - private Optional loadSinglePackFromZipFile(Path path) { - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path)) { - Path mcmeta = fs.getPath("pack.mcmeta"); - - if (!Files.exists(mcmeta)) { - return Optional.empty(); - } - - String packName = FileUtils.getName(path); - if (FileUtils.getExtension(path).equals(DISABLED_EXT)) { - packName = FileUtils.getNameWithoutExtension(packName); - } - packName = FileUtils.getNameWithoutExtension(packName); - - return parsePack(path, false, packName, mcmeta); - } catch (IOException e) { - LOG.warning("IO error reading " + path, e); - return Optional.empty(); - } - } - - private Optional parsePack(Path dataPackPath, boolean isDirectory, String name, Path mcmetaPath) { - try { - PackMcMeta mcMeta = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class); - return Optional.of(new Pack(dataPackPath, isDirectory, name, mcMeta.pack().description(), this)); - } catch (JsonParseException e) { - LOG.warning("Invalid pack.mcmeta format in " + dataPackPath, e); - } catch (IOException e) { - LOG.warning("IO error reading " + dataPackPath, e); - } - return Optional.empty(); - } - - public static class Pack { - private Path path; - private final boolean isDirectory; - private Path statusFile; - private final ReadOnlyBooleanWrapper activeProperty; - private final String id; - private final LocalAddonFile.Description description; - private final DataPack parentDataPack; - - public Pack(Path path, boolean isDirectory, String id, LocalAddonFile.Description description, DataPack parentDataPack) { - this.path = path; - this.isDirectory = isDirectory; - this.id = id; - this.description = description; - this.parentDataPack = parentDataPack; - - this.statusFile = initializeStatusFile(path, isDirectory); - this.activeProperty = new ReadOnlyBooleanWrapper(this, "active", !FileUtils.getExtension(this.statusFile).equals(DISABLED_EXT)); - } - - private Path initializeStatusFile(Path path, boolean isDirectory) { - if (isDirectory) { - Path mcmeta = path.resolve("pack.mcmeta"); - return Files.exists(mcmeta) ? mcmeta : path.resolve("pack.mcmeta.disabled"); - } - return path; - } - - public String getId() { - return id; - } - - public LocalAddonFile.Description getDescription() { - return description; - } - - public DataPack getParentDataPack() { - return parentDataPack; - } - - public ReadOnlyBooleanProperty activeProperty() { - return activeProperty.getReadOnlyProperty(); - } - - public boolean isActive() { - return activeProperty.get(); - } - - public void setActive(boolean active) throws IOException { - if (active == isActive()) - return; - - Path newStatusFile = active - ? statusFile.getParent().resolve(FileUtils.getNameWithoutExtension(statusFile)) - : statusFile.getParent().resolve(FileUtils.getName(statusFile) + "." + DISABLED_EXT); - - Files.move(statusFile, newStatusFile); - statusFile = newStatusFile; - if (!isDirectory) - path = newStatusFile; - - activeProperty.set(active); - } - - public Path getPath() { - return path; - } - - public boolean isDirectory() { - return isDirectory; - } - - public @Nullable I loadIcon(ImageLoader loader) { - try { - if (isDirectory) { - try (var inputStream = Files.newInputStream(path.resolve("pack.png"))) { - return loader.load(inputStream, "pack.png", 64, 64, true, true); - } - } - - try (FileSystem fs = CompressingUtils.createReadOnlyZipFileSystem(path); - var inputStream = Files.newInputStream(fs.getPath("/pack.png"))) { - return loader.load(inputStream, "pack.png", 64, 64, true, true); - } - } catch (Exception e) { - LOG.warning("Failed to load data pack icon", e); - return null; - } - } - } -} diff --git a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java index 12a84adf9a5..03cddec77f7 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -6,17 +6,21 @@ import javafx.beans.property.ReadOnlyBooleanWrapper; import org.jackhuang.hmcl.addon.LocalAddonFile; import org.jackhuang.hmcl.addon.meta.PackMcMeta; +import org.jackhuang.hmcl.image.ImageLoader; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.gson.JsonUtils; import org.jackhuang.hmcl.util.io.CompressingUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jetbrains.annotations.NotNullByDefault; +import org.jetbrains.annotations.Nullable; import java.io.IOException; +import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import static org.jackhuang.hmcl.addon.LocalAddonManager.DISABLED_EXTENSION; +import static org.jackhuang.hmcl.util.logging.Logger.LOG; @NotNullByDefault public class DataPackFile extends LocalAddonFile { @@ -98,6 +102,25 @@ public boolean isDirectory() { return isDirectory; } + /// Loads the data-pack icon, returning null when it is missing or cannot be read. + public @Nullable I loadIcon(ImageLoader loader) { + try { + if (isDirectory) { + try (var inputStream = Files.newInputStream(path.resolve("pack.png"))) { + return loader.load(inputStream, "pack.png", 64, 64, true, true); + } + } + + try (FileSystem fileSystem = CompressingUtils.createReadOnlyZipFileSystem(path); + var inputStream = Files.newInputStream(fileSystem.getPath("/pack.png"))) { + return loader.load(inputStream, "pack.png", 64, 64, true, true); + } + } catch (Exception e) { + LOG.warning("Failed to load data pack icon", e); + return null; + } + } + @Override public String getFileName() { return id; From 1758e70dc76fd6049701572e1991131696a2ed29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=B1=BC=E5=89=8D=E4=B8=89=E7=99=BE?= Date: Sun, 22 Nov 2026 13:36:35 +0800 Subject: [PATCH 16/16] =?UTF-8?q?chore:=20=E4=BF=AE=E6=AD=A3=20merge=20?= =?UTF-8?q?=E5=BC=95=E5=85=A5=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../hmcl/ui/instances/DataPackListPage.java | 56 ++++++++----------- 1 file changed, 22 insertions(+), 34 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java index 4e077ee4e6e..72bd48e058f 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/instances/DataPackListPage.java @@ -43,13 +43,14 @@ import org.jackhuang.hmcl.ui.animation.AnimationUtils; import org.jackhuang.hmcl.ui.animation.ContainerAnimations; import org.jackhuang.hmcl.ui.animation.TransitionPane; -import org.jackhuang.hmcl.ui.construct.*; +import org.jackhuang.hmcl.ui.construct.ImageContainer; +import org.jackhuang.hmcl.ui.construct.MessageDialogPane; +import org.jackhuang.hmcl.ui.construct.TwoLineListItem; import org.jackhuang.hmcl.util.StringUtils; import org.jackhuang.hmcl.util.io.FileUtils; import org.jackhuang.hmcl.util.javafx.ItemPropertyAsyncCache; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.Unmodifiable; import java.io.IOException; import java.lang.ref.WeakReference; @@ -57,7 +58,6 @@ import java.util.ArrayList; import java.util.List; import java.util.Objects; -import java.util.concurrent.locks.ReentrantLock; import java.util.function.Predicate; import java.util.regex.PatternSyntaxException; @@ -80,15 +80,14 @@ public final class DataPackListPage extends ListPaneBase items = FXCollections.observableArrayList(); + /// All loaded items before search filtering. + private final ObservableList sourceItems = FXCollections.observableArrayList(); /// Source items matching the current search. - private final FilteredList filteredItems = new FilteredList<>(items); + private final FilteredList filteredItems = new FilteredList<>(sourceItems); private final DataPackManager dataPackManager; private final BooleanProperty readOnly; - private final ReentrantLock lock = new ReentrantLock(); public DataPackListPage(WorldManagePage worldManagePage) { dataPackManager = worldManagePage.getWorld().getDataPackManager(); @@ -179,7 +178,7 @@ private void initializeView() { }); FXUtils.onChangeAndOperate(listView.getSelectionModel().selectedItemProperty(), - (@Nullable DataPackInfoObject selectedItem) -> { + selectedItem -> { if (selectedItem == null) changeToolbar(isSearching.get() ? searchBar : normalToolbar); else @@ -241,19 +240,14 @@ private void addFiles(List files) { public void refresh() { setLoading(true); Task.supplyAsync(Schedulers.io(), () -> { - lock.lock(); - try { - dataPackManager.refresh(); - return dataPackManager.getLocalFiles().stream().map(DataPackInfoObject::new).toList(); - } finally { - lock.unlock(); - } - }).whenComplete(Schedulers.javafx(), (@Nullable @Unmodifiable List result, @Nullable Exception exception) -> { + dataPackManager.refresh(); + return dataPackManager.getLocalFiles().stream().map(DataPackInfoObject::new).toList(); + }).whenComplete(Schedulers.javafx(), (result, exception) -> { if (exception == null) { - items.setAll(Objects.requireNonNull(result)); + sourceItems.setAll(result); } else { LOG.warning("Error refreshing data pack list page", exception); - items.clear(); + sourceItems.clear(); } setLoading(false); }).start(); @@ -263,7 +257,7 @@ public void add() { FileChooser chooser = new FileChooser(); chooser.setTitle(i18n("datapack.add.title")); chooser.getExtensionFilters().setAll(new FileChooser.ExtensionFilter(i18n("extension.datapack"), "*.zip")); - @Nullable List res = Controllers.showOpenMultipleDialog(chooser); + List res = Controllers.showOpenMultipleDialog(chooser); if (res != null) { addFiles(res); } @@ -309,7 +303,7 @@ void openDataPackFolder() { private void search() { isSearching.set(true); - @Nullable String queryString = searchField.getText(); + String queryString = searchField.getText(); if (StringUtils.isBlank(queryString)) { filteredItems.setPredicate(null); } else { @@ -342,15 +336,15 @@ private void changeToolbar(HBox newToolbar) { } } - static class DataPackInfoObject { + public static class DataPackInfoObject { private final DataPackFile file; private final ItemPropertyAsyncCache iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon); - DataPackInfoObject(DataPackFile file) { + public DataPackInfoObject(DataPackFile file) { this.file = file; } - DataPackFile getFile() { + public DataPackFile getFile() { return file; } @@ -360,8 +354,8 @@ private Image getDefaultIcon() { /// Loads the icon, using the default icon if it is absent or invalid. private Image loadIcon() { - @Nullable Image icon = file.loadIcon(ImageLoaders.DEFAULT); - return icon != null && FXUtils.isValidIcon(icon) ? icon : getDefaultIcon(); + Image icon = file.loadIcon(ImageLoaders.DEFAULT); + return FXUtils.isValidIcon(icon) ? icon : getDefaultIcon(); } } @@ -370,8 +364,7 @@ private static final class DataPackCell extends ItemCell { ImageContainer imageContainer = new ImageContainer(32); final TwoLineListItem content = new TwoLineListItem(); - private final InvalidationListener activeListener = observable -> - activeSwitch.setSelected(((ReadOnlyBooleanProperty) observable).get()); + private final InvalidationListener activeListener = obs -> activeSwitch.setSelected(((BooleanProperty) obs).get()); private final WeakInvalidationListener weakActiveListener = new WeakInvalidationListener(activeListener); private @Nullable ReadOnlyBooleanProperty observedActiveProperty; @@ -402,14 +395,9 @@ private static final class DataPackCell extends ItemCell { @Override protected void updateListItem(@Nullable DataPackInfoObject dataItem) { - if (observedActiveProperty != null) { + if (observedActiveProperty != null) observedActiveProperty.removeListener(weakActiveListener); - observedActiveProperty = null; - } - if (dataItem == null) { - activeSwitch.setOnAction(null); - return; - } + if (dataItem == null) return; DataPackFile packInfo = dataItem.getFile(); content.setTitle(packInfo.getFileName());