| 1 | package net.minecraft.client.gui.screens.packs;
|
| 2 |
|
| 3 | import com.google.common.collect.Maps;
|
| 4 | import com.google.common.hash.Hashing;
|
| 5 | import com.mojang.blaze3d.Blaze3D;
|
| 6 | import com.mojang.blaze3d.platform.NativeImage;
|
| 7 | import com.mojang.logging.LogUtils;
|
| 8 | import java.io.IOException;
|
| 9 | import java.io.InputStream;
|
| 10 | import java.nio.file.DirectoryStream;
|
| 11 | import java.nio.file.Files;
|
| 12 | import java.nio.file.LinkOption;
|
| 13 | import java.nio.file.Path;
|
| 14 | import java.nio.file.StandardWatchEventKinds;
|
| 15 | import java.nio.file.WatchEvent;
|
| 16 | import java.nio.file.WatchKey;
|
| 17 | import java.nio.file.WatchService;
|
| 18 | import java.util.ArrayList;
|
| 19 | import java.util.Collection;
|
| 20 | import java.util.HashSet;
|
| 21 | import java.util.List;
|
| 22 | import java.util.Locale;
|
| 23 | import java.util.Map;
|
| 24 | import java.util.Set;
|
| 25 | import java.util.function.Consumer;
|
| 26 | import java.util.stream.Collectors;
|
| 27 | import java.util.stream.Stream;
|
| 28 | import net.fabricmc.api.EnvType;
|
| 29 | import net.fabricmc.api.Environment;
|
| 30 | import net.minecraft.ChatFormatting;
|
| 31 | import net.minecraft.client.Minecraft;
|
| 32 | import net.minecraft.client.gui.components.Button;
|
| 33 | import net.minecraft.client.gui.components.EditBox;
|
| 34 | import net.minecraft.client.gui.components.StringWidget;
|
| 35 | import net.minecraft.client.gui.components.Tooltip;
|
| 36 | import net.minecraft.client.gui.components.toasts.SystemToast;
|
| 37 | import net.minecraft.client.gui.layouts.HeaderAndFooterLayout;
|
| 38 | import net.minecraft.client.gui.layouts.LinearLayout;
|
| 39 | import net.minecraft.client.gui.screens.AlertScreen;
|
| 40 | import net.minecraft.client.gui.screens.ConfirmScreen;
|
| 41 | import net.minecraft.client.gui.screens.NoticeWithLinkScreen;
|
| 42 | import net.minecraft.client.gui.screens.Screen;
|
| 43 | import net.minecraft.client.renderer.texture.DynamicTexture;
|
| 44 | import net.minecraft.client.renderer.texture.TextureManager;
|
| 45 | import net.minecraft.network.chat.CommonComponents;
|
| 46 | import net.minecraft.network.chat.Component;
|
| 47 | import net.minecraft.resources.Identifier;
|
| 48 | import net.minecraft.server.packs.PackMetadataResources;
|
| 49 | import net.minecraft.server.packs.repository.Pack;
|
| 50 | import net.minecraft.server.packs.repository.PackDetector;
|
| 51 | import net.minecraft.server.packs.repository.PackRepository;
|
| 52 | import net.minecraft.server.packs.resources.IoSupplier;
|
| 53 | import net.minecraft.util.Util;
|
| 54 | import net.minecraft.world.level.validation.ForbiddenSymlinkInfo;
|
| 55 | import org.apache.commons.lang3.mutable.MutableBoolean;
|
| 56 | import org.jspecify.annotations.Nullable;
|
| 57 | import org.slf4j.Logger;
|
| 58 |
|
| 59 | @Environment(EnvType.CLIENT)
|
| 60 | public class PackSelectionScreen extends Screen {
|
| 61 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 62 | private static final Component AVAILABLE_TITLE = Component.translatable("pack.available.title");
|
| 63 | private static final Component SELECTED_TITLE = Component.translatable("pack.selected.title");
|
| 64 | private static final Component OPEN_PACK_FOLDER_TITLE = Component.translatable("pack.openFolder");
|
| 65 | private static final Component SEARCH = Component.translatable("gui.packSelection.search").withStyle(EditBox.SEARCH_HINT_STYLE);
|
| 66 | private static final int LIST_WIDTH = 200;
|
| 67 | private static final int HEADER_ELEMENT_SPACING = 4;
|
| 68 | private static final int SEARCH_BOX_HEIGHT = 15;
|
| 69 | private static final Component DRAG_AND_DROP = Component.translatable("pack.dropInfo").withStyle(ChatFormatting.GRAY);
|
| 70 | private static final Component DIRECTORY_BUTTON_TOOLTIP = Component.translatable("pack.folderInfo");
|
| 71 | private static final int RELOAD_COOLDOWN = 20;
|
| 72 | private static final Identifier DEFAULT_ICON = Identifier.withDefaultNamespace("textures/misc/unknown_pack.png");
|
| 73 | private final HeaderAndFooterLayout layout = new HeaderAndFooterLayout(this);
|
| 74 | private final PackSelectionModel model;
|
| 75 | private PackSelectionScreen.@Nullable Watcher watcher;
|
| 76 | private long ticksToReload;
|
| 77 | private @Nullable TransferableSelectionList availablePackList;
|
| 78 | private @Nullable TransferableSelectionList selectedPackList;
|
| 79 | private @Nullable EditBox search;
|
| 80 | private final Path packDir;
|
| 81 | private @Nullable Button doneButton;
|
| 82 | private final Map<String, Identifier> packIcons = Maps.newHashMap();
|
| 83 |
|
| 84 | public PackSelectionScreen(final PackRepository repository, final Consumer<PackRepository> output, final Path packDir, final Component title) {
|
| 85 | super(title);
|
| 86 | this.model = new PackSelectionModel(this::populateLists, this::getPackIcon, repository, output);
|
| 87 | this.packDir = packDir;
|
| 88 | this.watcher = PackSelectionScreen.Watcher.create(packDir);
|
| 89 | }
|
| 90 |
|
| 91 | @Override
|
| 92 | public void onClose() {
|
| 93 | this.model.commit();
|
| 94 | this.closeWatcher();
|
| 95 | }
|
| 96 |
|
| 97 | private void closeWatcher() {
|
| 98 | if (this.watcher != null) {
|
| 99 | try {
|
| 100 | this.watcher.close();
|
| 101 | this.watcher = null;
|
| 102 | } catch (Exception var2) {
|
| 103 | }
|
| 104 | }
|
| 105 | }
|
| 106 |
|
| 107 | @Override
|
| 108 | protected void init() {
|
| 109 | this.layout.setHeaderHeight(4 + 9 + 4 + 9 + 4 + 15 + 4);
|
| 110 | LinearLayout header = this.layout.addToHeader(LinearLayout.vertical().spacing(4));
|
| 111 | header.defaultCellSetting().alignHorizontallyCenter();
|
| 112 | header.addChild(new StringWidget(this.getTitle(), this.font));
|
| 113 | header.addChild(new StringWidget(DRAG_AND_DROP, this.font));
|
| 114 | this.search = header.addChild(new EditBox(this.font, 0, 0, 200, 15, Component.empty()));
|
| 115 | this.search.setHint(SEARCH);
|
| 116 | this.search.setResponder(this::updateFilteredEntries);
|
| 117 | this.availablePackList = this.layout.addToContents(new TransferableSelectionList(this.minecraft, this, 200, this.height - 66, AVAILABLE_TITLE));
|
| 118 | this.selectedPackList = this.layout.addToContents(new TransferableSelectionList(this.minecraft, this, 200, this.height - 66, SELECTED_TITLE));
|
| 119 | LinearLayout footer = this.layout.addToFooter(LinearLayout.horizontal().spacing(8));
|
| 120 | footer.addChild(Button.builder(OPEN_PACK_FOLDER_TITLE, button -> Blaze3D.openPath(this.packDir)).tooltip(Tooltip.create(DIRECTORY_BUTTON_TOOLTIP)).build());
|
| 121 | this.doneButton = footer.addChild(Button.builder(CommonComponents.GUI_DONE, button -> this.onClose()).build());
|
| 122 | this.layout.visitWidgets(x$0 -> this.addRenderableWidget(x$0));
|
| 123 | this.repositionElements();
|
| 124 | this.reload();
|
| 125 | }
|
| 126 |
|
| 127 | @Override
|
| 128 | protected void setInitialFocus() {
|
| 129 | if (this.search != null) {
|
| 130 | this.setInitialFocus(this.search);
|
| 131 | } else {
|
| 132 | super.setInitialFocus();
|
| 133 | }
|
| 134 | }
|
| 135 |
|
| 136 | private void updateFilteredEntries(final String value) {
|
| 137 | this.updateFilteredEntries(value, null);
|
| 138 | }
|
| 139 |
|
| 140 | private void updateFilteredEntries(final String value, final PackSelectionModel.@Nullable EntryBase transferredEntry) {
|
| 141 | this.filterEntries(value, this.model.getSelected(), this.selectedPackList, transferredEntry);
|
| 142 | this.filterEntries(value, this.model.getUnselected(), this.availablePackList, transferredEntry);
|
| 143 | }
|
| 144 |
|
| 145 | private void filterEntries(
|
| 146 | final String value,
|
| 147 | final Stream<PackSelectionModel.Entry> oldEntries,
|
| 148 | final @Nullable TransferableSelectionList listToUpdate,
|
| 149 | final PackSelectionModel.@Nullable EntryBase transferredEntry
|
| 150 | ) {
|
| 151 | if (listToUpdate != null) {
|
| 152 | String lowerCaseValue = value.toLowerCase(Locale.ROOT);
|
| 153 | Stream<PackSelectionModel.Entry> filteredEntries = oldEntries.filter(
|
| 154 | packEntry -> value.isBlank()
|
| 155 | || packEntry.getId().toLowerCase(Locale.ROOT).contains(lowerCaseValue)
|
| 156 | || packEntry.getTitle().getString().toLowerCase(Locale.ROOT).contains(lowerCaseValue)
|
| 157 | || packEntry.getDescription().getString().toLowerCase(Locale.ROOT).contains(lowerCaseValue)
|
| 158 | );
|
| 159 | listToUpdate.updateList(filteredEntries, transferredEntry);
|
| 160 | }
|
| 161 | }
|
| 162 |
|
| 163 | @Override
|
| 164 | protected void repositionElements() {
|
| 165 | this.layout.arrangeElements();
|
| 166 | if (this.availablePackList != null) {
|
| 167 | this.availablePackList.updateSizeAndPosition(200, this.layout.getContentHeight(), this.width / 2 - 15 - 200, this.layout.getHeaderHeight());
|
| 168 | }
|
| 169 |
|
| 170 | if (this.selectedPackList != null) {
|
| 171 | this.selectedPackList.updateSizeAndPosition(200, this.layout.getContentHeight(), this.width / 2 + 15, this.layout.getHeaderHeight());
|
| 172 | }
|
| 173 | }
|
| 174 |
|
| 175 | @Override
|
| 176 | public void tick() {
|
| 177 | if (this.watcher != null) {
|
| 178 | try {
|
| 179 | if (this.watcher.pollForChanges()) {
|
| 180 | this.ticksToReload = 20L;
|
| 181 | }
|
| 182 | } catch (IOException e) {
|
| 183 | LOGGER.warn("Failed to poll for directory {} changes, stopping", this.packDir);
|
| 184 | this.closeWatcher();
|
| 185 | }
|
| 186 | }
|
| 187 |
|
| 188 | if (this.ticksToReload > 0L && --this.ticksToReload == 0L) {
|
| 189 | this.reload();
|
| 190 | }
|
| 191 | }
|
| 192 |
|
| 193 | private void populateLists(final PackSelectionModel.@Nullable EntryBase transferredEntry) {
|
| 194 | if (this.selectedPackList != null) {
|
| 195 | this.selectedPackList.updateList(this.model.getSelected(), transferredEntry);
|
| 196 | }
|
| 197 |
|
| 198 | if (this.availablePackList != null) {
|
| 199 | this.availablePackList.updateList(this.model.getUnselected(), transferredEntry);
|
| 200 | }
|
| 201 |
|
| 202 | if (this.search != null) {
|
| 203 | this.updateFilteredEntries(this.search.getValue(), transferredEntry);
|
| 204 | }
|
| 205 |
|
| 206 | if (this.doneButton != null) {
|
| 207 | this.doneButton.active = !this.selectedPackList.children().isEmpty();
|
| 208 | }
|
| 209 | }
|
| 210 |
|
| 211 | private void reload() {
|
| 212 | this.model.findNewPacks();
|
| 213 | this.populateLists(null);
|
| 214 | this.ticksToReload = 0L;
|
| 215 | this.packIcons.clear();
|
| 216 | }
|
| 217 |
|
| 218 | protected static void copyPacks(final Minecraft minecraft, final List<Path> files, final Path targetDir) {
|
| 219 | MutableBoolean showErrorToast = new MutableBoolean();
|
| 220 | files.forEach(pack -> {
|
| 221 | try (Stream<Path> contents = Files.walk(pack)) {
|
| 222 | contents.forEach(path -> {
|
| 223 | try {
|
| 224 | Util.copyBetweenDirs(pack.getParent(), targetDir, path);
|
| 225 | } catch (IOException e) {
|
| 226 | LOGGER.warn("Failed to copy datapack file from {} to {}", path, targetDir, ex);
|
| 227 | showErrorToast.setTrue();
|
| 228 | }
|
| 229 | });
|
| 230 | } catch (IOException e) {
|
| 231 | LOGGER.warn("Failed to copy datapack file from {} to {}", pack, targetDir);
|
| 232 | showErrorToast.setTrue();
|
| 233 | }
|
| 234 | });
|
| 235 | if (showErrorToast.isTrue()) {
|
| 236 | SystemToast.onPackCopyFailure(minecraft, targetDir.toString());
|
| 237 | }
|
| 238 | }
|
| 239 |
|
| 240 | @Override
|
| 241 | public void onFilesDrop(final List<Path> files) {
|
| 242 | String names = extractPackNames(files).collect(Collectors.joining(", "));
|
| 243 | this.minecraft
|
| 244 | .gui
|
| 245 | .setScreen(
|
| 246 | new ConfirmScreen(
|
| 247 | result -> {
|
| 248 | if (result) {
|
| 249 | List<Path> packCandidates = new ArrayList<>(files.size());
|
| 250 | Set<Path> leftoverPacks = new HashSet<>(files);
|
| 251 | PackDetector<Path> packDetector = new PackDetector<Path>(this.minecraft.directoryValidator()) {
|
| 252 | protected Path createZipPack(final Path content) {
|
| 253 | return content;
|
| 254 | }
|
| 255 |
|
| 256 | protected Path createDirectoryPack(final Path content) {
|
| 257 | return content;
|
| 258 | }
|
| 259 | };
|
| 260 | List<ForbiddenSymlinkInfo> issues = new ArrayList<>();
|
| 261 |
|
| 262 | for (Path path : files) {
|
| 263 | try {
|
| 264 | Path candidate = packDetector.detectPackResources(path, issues);
|
| 265 | if (candidate == null) {
|
| 266 | LOGGER.warn("Path {} does not seem like pack", path);
|
| 267 | } else {
|
| 268 | packCandidates.add(candidate);
|
| 269 | leftoverPacks.remove(candidate);
|
| 270 | }
|
| 271 | } catch (IOException e) {
|
| 272 | LOGGER.warn("Failed to check {} for packs", path, e);
|
| 273 | }
|
| 274 | }
|
| 275 |
|
| 276 | if (!issues.isEmpty()) {
|
| 277 | this.minecraft.gui.setScreen(NoticeWithLinkScreen.createPackSymlinkWarningScreen(() -> this.minecraft.gui.setScreen(this)));
|
| 278 | return;
|
| 279 | }
|
| 280 |
|
| 281 | if (!packCandidates.isEmpty()) {
|
| 282 | copyPacks(this.minecraft, packCandidates, this.packDir);
|
| 283 | this.reload();
|
| 284 | }
|
| 285 |
|
| 286 | if (!leftoverPacks.isEmpty()) {
|
| 287 | String leftoverNames = extractPackNames(leftoverPacks).collect(Collectors.joining(", "));
|
| 288 | this.minecraft
|
| 289 | .gui
|
| 290 | .setScreen(
|
| 291 | new AlertScreen(
|
| 292 | () -> this.minecraft.gui.setScreen(this),
|
| 293 | Component.translatable("pack.dropRejected.title"),
|
| 294 | Component.translatable("pack.dropRejected.message", leftoverNames)
|
| 295 | )
|
| 296 | );
|
| 297 | return;
|
| 298 | }
|
| 299 | }
|
| 300 |
|
| 301 | this.minecraft.gui.setScreen(this);
|
| 302 | },
|
| 303 | Component.translatable("pack.dropConfirm"),
|
| 304 | Component.literal(names)
|
| 305 | )
|
| 306 | );
|
| 307 | }
|
| 308 |
|
| 309 | private static Stream<String> extractPackNames(final Collection<Path> files) {
|
| 310 | return files.stream().map(Path::getFileName).map(Path::toString);
|
| 311 | }
|
| 312 |
|
| 313 | private Identifier loadPackIcon(final TextureManager textureManager, final Pack pack) {
|
| 314 | try (PackMetadataResources packResources = pack.openMetadata()) {
|
| 315 | IoSupplier<InputStream> resource = packResources.getRootResource("pack.png");
|
| 316 | if (resource == null) {
|
| 317 | return DEFAULT_ICON;
|
| 318 | }
|
| 319 |
|
| 320 | String id = pack.getId();
|
| 321 | Identifier location = Identifier.withDefaultNamespace(
|
| 322 | "pack/" + Util.sanitizeName(id, Identifier::validPathChar) + "/" + Hashing.sha1().hashUnencodedChars(id) + "/icon"
|
| 323 | );
|
| 324 |
|
| 325 | try (InputStream stream = resource.get()) {
|
| 326 | NativeImage iconImage = NativeImage.read(stream);
|
| 327 | textureManager.register(location, new DynamicTexture(location::toString, iconImage));
|
| 328 | return location;
|
| 329 | }
|
| 330 | } catch (Exception e) {
|
| 331 | LOGGER.warn("Failed to load icon from pack {}", pack.getId(), e);
|
| 332 | return DEFAULT_ICON;
|
| 333 | }
|
| 334 | }
|
| 335 |
|
| 336 | private Identifier getPackIcon(final Pack pack) {
|
| 337 | return this.packIcons.computeIfAbsent(pack.getId(), s -> this.loadPackIcon(this.minecraft.getTextureManager(), pack));
|
| 338 | }
|
| 339 |
|
| 340 | @Environment(EnvType.CLIENT)
|
| 341 | private static class Watcher implements AutoCloseable {
|
| 342 | private final WatchService watcher;
|
| 343 | private final Path packPath;
|
| 344 |
|
| 345 | public Watcher(final Path packPath) throws IOException {
|
| 346 | this.packPath = packPath;
|
| 347 | this.watcher = packPath.getFileSystem().newWatchService();
|
| 348 |
|
| 349 | try {
|
| 350 | this.watchDir(packPath);
|
| 351 |
|
| 352 | try (DirectoryStream<Path> paths = Files.newDirectoryStream(packPath)) {
|
| 353 | for (Path path : paths) {
|
| 354 | if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) {
|
| 355 | this.watchDir(path);
|
| 356 | }
|
| 357 | }
|
| 358 | }
|
| 359 | } catch (Exception e) {
|
| 360 | this.watcher.close();
|
| 361 | throw e;
|
| 362 | }
|
| 363 | }
|
| 364 |
|
| 365 | public static PackSelectionScreen.@Nullable Watcher create(final Path packDir) {
|
| 366 | try {
|
| 367 | return new PackSelectionScreen.Watcher(packDir);
|
| 368 | } catch (IOException e) {
|
| 369 | PackSelectionScreen.LOGGER.warn("Failed to initialize pack directory {} monitoring", packDir, e);
|
| 370 | return null;
|
| 371 | }
|
| 372 | }
|
| 373 |
|
| 374 | private void watchDir(final Path packPath) throws IOException {
|
| 375 | packPath.register(this.watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
|
| 376 | }
|
| 377 |
|
| 378 | public boolean pollForChanges() throws IOException {
|
| 379 | boolean hasChanges = false;
|
| 380 |
|
| 381 | WatchKey key;
|
| 382 | while ((key = this.watcher.poll()) != null) {
|
| 383 | for (WatchEvent<?> watchEvent : key.pollEvents()) {
|
| 384 | hasChanges = true;
|
| 385 | if (key.watchable() == this.packPath && watchEvent.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
|
| 386 | Path newPath = this.packPath.resolve((Path)watchEvent.context());
|
| 387 | if (Files.isDirectory(newPath, LinkOption.NOFOLLOW_LINKS)) {
|
| 388 | this.watchDir(newPath);
|
| 389 | }
|
| 390 | }
|
| 391 | }
|
| 392 |
|
| 393 | key.reset();
|
| 394 | }
|
| 395 |
|
| 396 | return hasChanges;
|
| 397 | }
|
| 398 |
|
| 399 | @Override
|
| 400 | public void close() throws IOException {
|
| 401 | this.watcher.close();
|
| 402 | }
|
| 403 | }
|
| 404 | }
|
| 405 |
|