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 3a96a2c6ef1..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 @@ -13,6 +13,7 @@ import javafx.beans.property.BooleanProperty; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.SimpleBooleanProperty; +import javafx.collections.FXCollections; import javafx.collections.ListChangeListener; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; @@ -20,9 +21,9 @@ import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.control.Label; +import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.image.Image; -import javafx.scene.control.ListView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.HBox; @@ -30,8 +31,8 @@ import javafx.scene.layout.StackPane; import javafx.stage.FileChooser; import javafx.util.Duration; -import org.jackhuang.hmcl.addon.datapack.DataPack; -import org.jackhuang.hmcl.game.World; +import org.jackhuang.hmcl.addon.datapack.DataPackFile; +import org.jackhuang.hmcl.addon.datapack.DataPackManager; import org.jackhuang.hmcl.image.ImageLoaders; import org.jackhuang.hmcl.task.Schedulers; import org.jackhuang.hmcl.task.Task; @@ -42,11 +43,12 @@ 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.jackhuang.hmcl.util.javafx.MappedObservableList; import org.jetbrains.annotations.NotNullByDefault; import org.jetbrains.annotations.Nullable; @@ -78,25 +80,21 @@ public final class DataPackListPage extends ListPaneBase sourceItems = FXCollections.observableArrayList(); /// Source items matching the current search. - private final FilteredList filteredItems; + private final FilteredList filteredItems = new FilteredList<>(sourceItems); - private final World world; - private final DataPack dataPack; - final BooleanProperty readOnly; + private final DataPackManager dataPackManager; + private final BooleanProperty readOnly; public DataPackListPage(WorldManagePage worldManagePage) { - world = worldManagePage.getWorld(); - dataPack = new DataPack(world.getFile().resolve("datapacks")); - filteredItems = new FilteredList<>(MappedObservableList.create(dataPack.getPacks(), DataPackInfoObject::new)); + dataPackManager = worldManagePage.getWorld().getDataPackManager(); readOnly = worldManagePage.readOnlyProperty(); - FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), - this::installMultiDataPack, this::refresh); - - refresh(); - + FXUtils.applyDragListener(this, it -> Objects.equals("zip", FileUtils.getExtension(it)), this::addFiles); initializeView(); + refresh(); } @Override @@ -213,26 +211,46 @@ private void initializeView() { } } - private void installMultiDataPack(List dataPackPath) { - dataPackPath.forEach(this::installSingleDataPack); - 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); - } + 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); + } + } + }).thenRunAsync(Schedulers.javafx(), () -> { + if (!failures.isEmpty()) { + StringBuilder failure = new StringBuilder(i18n("datapack.add.failed")); + for (Path file : failures) { + failure.append("\n").append(file); + } + Controllers.dialog(failure.toString(), i18n("message.error"), MessageDialogPane.MessageType.ERROR); + } + if (readOnly.get()) + Controllers.showToast(i18n("datapack.reload.toast")); + refresh(); + }).start(); } + @Override public void refresh() { setLoading(true); - Task.runAsync(dataPack::loadFromDir) - .withRunAsync(Schedulers.javafx(), () -> setLoading(false)) - .start(); + Task.supplyAsync(Schedulers.io(), () -> { + dataPackManager.refresh(); + return dataPackManager.getLocalFiles().stream().map(DataPackInfoObject::new).toList(); + }).whenComplete(Schedulers.javafx(), (result, exception) -> { + if (exception == null) { + sourceItems.setAll(result); + } else { + LOG.warning("Error refreshing data pack list page", exception); + sourceItems.clear(); + } + setLoading(false); + }).start(); } public void add() { @@ -241,24 +259,21 @@ 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); } - - dataPack.loadFromDir(); } void removeSelected(ObservableList selectedItems) { List failed = new ArrayList<>(); - selectedItems.stream() - .map(DataPackInfoObject::getPackInfo) - .forEach(pack -> { - try { - dataPack.deletePack(pack); - } catch (IOException e) { - failed.add(pack.getPath().toString()); - LOG.warning("Failed to delete datapack \"" + pack.getId() + "\"", e); - } - }); + selectedItems.stream().map(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), i18n("message.error"), MessageDialogPane.MessageType.ERROR); @@ -266,23 +281,21 @@ void removeSelected(ObservableList selectedItems) { void setSelectedEnabled(ObservableList selectedItems, boolean enabled) { List failed = new ArrayList<>(); - selectedItems.stream() - .map(DataPackInfoObject::getPackInfo) - .forEach(pack -> { - try { - pack.setActive(enabled); - } catch (IOException e) { - failed.add(pack.getPath().toString()); - LOG.warning("Failed to enable or disable datapack \"" + pack.getId() + "\"", e); - } - }); + selectedItems.stream().map(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); } void openDataPackFolder() { - FXUtils.openFolder(dataPack.getPath()); + FXUtils.openFolder(dataPackManager.getDirectory()); } /// Filters pack IDs and descriptions using the shared query syntax; invalid regular expressions leave the list empty. @@ -304,7 +317,8 @@ private void search() { } filteredItems.setPredicate(item -> { - return predicate.test(item.getTitle()) || predicate.test(item.getSubtitle()); + DataPackFile file = item.getFile(); + return predicate.test(file.getFileName()) || predicate.test(file.getDescription().toString()); }); } } @@ -322,25 +336,16 @@ private void changeToolbar(HBox newToolbar) { } } - static class DataPackInfoObject { - private final DataPack.Pack packInfo; - private final ItemPropertyAsyncCache iconCache; - - DataPackInfoObject(DataPack.Pack packInfo) { - this.packInfo = packInfo; - this.iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon); - } - - String getTitle() { - return packInfo.getId(); - } + public static class DataPackInfoObject { + private final DataPackFile file; + private final ItemPropertyAsyncCache iconCache = new ItemPropertyAsyncCache.Soft<>(this, this::loadIcon, this::getDefaultIcon); - String getSubtitle() { - return packInfo.getDescription().toStringSingleLine(); + public DataPackInfoObject(DataPackFile file) { + this.file = file; } - DataPack.Pack getPackInfo() { - return packInfo; + public DataPackFile getFile() { + return file; } private Image getDefaultIcon() { @@ -349,7 +354,7 @@ private Image getDefaultIcon() { /// Loads the icon, using the default icon if it is absent or invalid. private Image loadIcon() { - Image icon = packInfo.loadIcon(ImageLoaders.DEFAULT); + Image icon = file.loadIcon(ImageLoaders.DEFAULT); return FXUtils.isValidIcon(icon) ? icon : getDefaultIcon(); } } @@ -359,7 +364,7 @@ private static final class DataPackCell extends ItemCell { ImageContainer imageContainer = new ImageContainer(32); final TwoLineListItem content = new TwoLineListItem(); - private final InvalidationListener activeListener = obs -> activeSwitch.setSelected(getItem().getPackInfo().isActive()); + private final InvalidationListener activeListener = obs -> activeSwitch.setSelected(((BooleanProperty) obs).get()); private final WeakInvalidationListener weakActiveListener = new WeakInvalidationListener(activeListener); private @Nullable ReadOnlyBooleanProperty observedActiveProperty; @@ -393,10 +398,10 @@ protected void updateListItem(@Nullable DataPackInfoObject dataItem) { if (observedActiveProperty != null) observedActiveProperty.removeListener(weakActiveListener); if (dataItem == null) return; - content.setTitle(dataItem.getTitle()); - content.setSubtitle(dataItem.getSubtitle()); - DataPack.Pack packInfo = dataItem.getPackInfo(); + DataPackFile packInfo = dataItem.getFile(); + content.setTitle(packInfo.getFileName()); + content.setSubtitle(packInfo.getDescription().toStringSingleLine()); (observedActiveProperty = packInfo.activeProperty()).addListener(weakActiveListener); activeSwitch.setDisableAnimation(true); activeSwitch.setSelected(packInfo.isActive()); @@ -404,7 +409,7 @@ protected void updateListItem(@Nullable DataPackInfoObject dataItem) { try { packInfo.setActive(activeSwitch.isSelected()); } catch (IOException e) { - LOG.warning("Unable to change state of datapack " + packInfo.getPath(), e); + LOG.warning("Unable to change state of datapack " + packInfo.getFile(), e); Controllers.showToast(i18n("datapack.toggle.failed")); } finally { activeSwitch.setSelected(packInfo.isActive()); 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 154a8b7d12e..8b60b3cd60c 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 @@ -33,6 +33,7 @@ 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; @@ -40,6 +41,7 @@ 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; @@ -130,7 +132,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())); + } 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 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 cab26df1a0a..2a248927117 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 @@ -150,6 +150,10 @@ public World getWorld() { return world; } + public HMCLGameInstance getGameInstance() { + return gameInstance; + } + public Path getBackupsDir() { return backupsDir; } diff --git a/HMCL/src/main/resources/assets/lang/I18N.properties b/HMCL/src/main/resources/assets/lang/I18N.properties index 10e0294cb07..c79b3022732 100644 --- a/HMCL/src/main/resources/assets/lang/I18N.properties +++ b/HMCL/src/main/resources/assets/lang/I18N.properties @@ -1214,6 +1214,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 b3ad20c670c..a005614013c 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ar.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ar.properties @@ -1217,6 +1217,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 0591f6d78ed..3a5fd172e08 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_de.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_de.properties @@ -1216,6 +1216,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 395bc8fd731..5e192774336 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_es.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_es.properties @@ -1208,6 +1208,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 8ed7d72074d..ee2aa44965c 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ja.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ja.properties @@ -1016,6 +1016,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 c599eb84f08..25381b8846b 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_lzh.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_lzh.properties @@ -1028,6 +1028,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 f5d9801332f..fc443db967d 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_ru.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_ru.properties @@ -1149,6 +1149,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 b0458a7ef23..f08912ea3f8 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_uk.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_uk.properties @@ -1172,6 +1172,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 e48329ed861..11a3224fdac 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_zh_Hans.properties @@ -1030,6 +1030,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 2c109c7180e..9e3b3788df0 100644 --- a/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties +++ b/HMCL/src/main/resources/assets/lang/I18N_zh_Hant.properties @@ -1024,6 +1024,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/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 new file mode 100644 index 00000000000..03cddec77f7 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackFile.java @@ -0,0 +1,154 @@ +// 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; +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 { + 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"); + try { + info = JsonUtils.fromNonNullJson(Files.readString(mcmetaPath), PackMcMeta.class).pack(); + } catch (Exception e) { + throw new IOException(e); + } + statusFile = mcmetaPath; + } else { + 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; + } + + this.activeProperty = new ReadOnlyBooleanWrapper(this, "active", !FileUtils.getName(statusFile).endsWith(DISABLED_EXTENSION)); + } + + public PackMcMeta.PackInfo getInfo() { + return info; + } + + public LocalAddonFile.Description getDescription() { + return info.description(); + } + + 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; + } + + /// 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; + } + + @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(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..e6698731747 --- /dev/null +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/addon/datapack/DataPackManager.java @@ -0,0 +1,177 @@ +// 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; +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.NotNullByDefault; +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; + +@NotNullByDefault +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 importDataPack(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.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 2b646c5b310..36239b3d450 100644 --- a/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java +++ b/HMCLCore/src/main/java/org/jackhuang/hmcl/game/World.java @@ -5,6 +5,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; @@ -41,6 +42,9 @@ public final class World { private CompoundTag playerData; // Use for both reading/modification and writing back to the file private Path playerDataPath; + /// Lazily created data pack manager. + private @Nullable DataPackManager dataPackManager; + public World(Path file) throws IOException { this.file = file; @@ -434,24 +438,11 @@ private static boolean isLocked(Path sessionLockFile) { } } - 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); - } + /// Returns the data pack manager for this world. + public DataPackManager getDataPackManager() { + if (dataPackManager == null) { + dataPackManager = new DataPackManager(this); } - return List.of(); + return dataPackManager; } }