This commit is contained in:
Moulberry committed 2024-07-25 16:40:29 +08:00
1 parent 9c4a30d224
commit 666398e480
174 files changed
+8694 -2942

No files matched your search

@@ -0,0 +1,28 @@
package com.moulberry.flashback.screen;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractStringWidget;
import net.minecraft.network.chat.Component;
public class BottomTextWidget extends AbstractStringWidget {
public BottomTextWidget(int width, int height, Component component, Font font) {
super(0, 0, width, height, component, font);
this.active = false;
}
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
Component component = this.getMessage();
Font font = this.getFont();
int width = this.getWidth();
int textWidth = font.width(component);
int x = this.getX() + Math.round((width - textWidth)/2.0f);
int y = this.getY() + this.getHeight() - this.getFont().lineHeight + 1;
guiGraphics.drawString(font, component.getVisualOrderText(), x, y, this.getColor());
}
}
@@ -0,0 +1,24 @@
package com.moulberry.flashback.screen;
import com.moulberry.flashback.configuration.FlashbackConfig;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.options.OptionsSubScreen;
import net.minecraft.network.chat.Component;
public class ConfigScreen extends OptionsSubScreen {
public ConfigScreen(Screen previous) {
super(previous, Minecraft.getInstance().options, Component.literal("Flashback Options"));
}
protected void addOptions() {
if (this.list != null) {
this.list.addSmall(FlashbackConfig.createOptionInstances());
}
}
public void removed() {
}
}
@@ -0,0 +1,462 @@
/*
* Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4).
*/
package com.moulberry.flashback.screen;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mojang.blaze3d.platform.NativeImage;
import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.logging.LogUtils;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.record.FlashbackMeta;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.Util;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.ObjectSelectionList;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.CommonInputs;
import net.minecraft.client.gui.screens.*;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.sounds.SoundEvents;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionList.Entry> {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault());
private static final ResourceLocation ERROR_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error_highlighted");
private static final ResourceLocation ERROR_SPRITE = ResourceLocation.withDefaultNamespace("world_list/error");
private static final ResourceLocation JOIN_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join_highlighted");
private static final ResourceLocation JOIN_SPRITE = ResourceLocation.withDefaultNamespace("world_list/join");
private static final Logger LOGGER = LogUtils.getLogger();
private final SelectReplayScreen screen;
private CompletableFuture<List<ReplaySummary>> pendingReplays;
@Nullable
private List<ReplaySummary> currentlyDisplayedReplays;
private String filter;
private final LoadingHeader loadingHeader;
public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l, String string, @Nullable ReplaySelectionList replaySelectionList) {
super(minecraft, i, j, k, l);
this.screen = selectReplayScreen;
this.loadingHeader = new LoadingHeader(minecraft);
this.filter = string;
this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays();
this.handleNewReplays(this.pollReplaysIgnoreErrors());
}
@Override
protected void clearEntries() {
this.children().forEach(Entry::close);
super.clearEntries();
}
@Nullable
private List<ReplaySummary> pollReplaysIgnoreErrors() {
try {
return this.pendingReplays.getNow(null);
} catch (CancellationException | CompletionException runtimeException) {
return null;
}
}
private void reloadWorldList() {
this.pendingReplays = this.loadReplays();
}
@Override
public boolean keyPressed(int i, int j, int k) {
if (CommonInputs.selected(i)) {
ReplayListEntry replayListEntry = this.getReplayListEntry();
if (replayListEntry != null && replayListEntry.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
replayListEntry.openReplay();
return true;
}
}
return super.keyPressed(i, j, k);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
List<ReplaySummary> list = this.pollReplaysIgnoreErrors();
if (list != this.currentlyDisplayedReplays) {
this.handleNewReplays(list);
}
super.renderWidget(guiGraphics, i, j, f);
}
private void handleNewReplays(@Nullable List<ReplaySummary> list) {
if (list == null) {
this.fillLoadingReplays();
} else {
this.fillReplays(this.filter, list);
}
this.currentlyDisplayedReplays = list;
}
public void updateFilter(String string) {
if (this.currentlyDisplayedReplays != null && !string.equals(this.filter)) {
this.fillReplays(string, this.currentlyDisplayedReplays);
}
this.filter = string;
}
private CompletableFuture<List<ReplaySummary>> loadReplays() {
Path flashbackDir = FabricLoader.getInstance().getGameDir().resolve("flashback");
Path replayDir = flashbackDir.resolve("replays");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
return CompletableFuture.completedFuture(List.of());
}
ArrayList<CompletableFuture<ReplaySummary>> futures = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
for (Path path : directoryStream) {
if (!path.toString().endsWith(".zip")) {
continue;
}
futures.add(CompletableFuture.supplyAsync(() -> {
try {
String fileName = path.getFileName().toString();
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastOpened = Math.max(basicFileAttributes.creationTime().toMillis(),
Math.max(basicFileAttributes.lastAccessTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis()));
byte[] iconBytes = null;
String metadataString = null;
try (FileSystem fs = FileSystems.newFileSystem(path)) {
Path iconPath = fs.getPath("/icon.png");
if (Files.exists(iconPath)) {
iconBytes = Files.readAllBytes(iconPath);
}
Path metadataPath = fs.getPath("/metadata.json");
if (Files.exists(metadataPath)) {
metadataString = Files.readString(metadataPath);
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
if (metadataString == null) {
return null;
}
JsonObject metadataJson = new Gson().fromJson(metadataString, JsonObject.class);
FlashbackMeta metadata = FlashbackMeta.fromJson(metadataJson);
if (metadata != null) {
return new ReplaySummary(path, metadata, fileName, lastOpened, iconBytes);
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
return null;
}, Util.backgroundExecutor()));
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
return Util.sequenceFailFastAndCancel(futures).thenApply(list -> list.stream().filter(Objects::nonNull).sorted().toList());
}
private void fillReplays(String string, List<ReplaySummary> list) {
this.clearEntries();
string = string.toLowerCase(Locale.ROOT);
for (ReplaySummary ReplaySummary : list) {
if (!this.filterAccepts(string, ReplaySummary)) continue;
this.addEntry(new ReplayListEntry(this, ReplaySummary));
}
this.notifyListUpdated();
}
private boolean filterAccepts(String string, ReplaySummary ReplaySummary) {
return ReplaySummary.getReplayName().toLowerCase(Locale.ROOT).contains(string) || ReplaySummary.getReplayId().toLowerCase(Locale.ROOT).contains(string);
}
private void fillLoadingReplays() {
this.clearEntries();
this.addEntry(this.loadingHeader);
this.notifyListUpdated();
}
private void notifyListUpdated() {
this.setScrollAmount(this.getScrollAmount());
this.screen.triggerImmediateNarration(true);
this.screen.updateButtonStatus(null);
}
@Override
public int getRowWidth() {
return 270;
}
@Override
public void setSelected(@Nullable Entry entry) {
super.setSelected(entry);
if (entry instanceof ReplayListEntry replayListEntry) {
this.screen.updateButtonStatus(replayListEntry.summary);
} else {
this.screen.updateButtonStatus(null);
}
}
@Nullable
public ReplayListEntry getReplayListEntry() {
if (this.getSelected() instanceof ReplayListEntry replayListEntry) {
return replayListEntry;
} else {
return null;
}
}
public SelectReplayScreen getScreen() {
return this.screen;
}
@Override
public void updateWidgetNarration(NarrationElementOutput narrationElementOutput) {
if (this.children().contains(this.loadingHeader)) {
this.loadingHeader.updateNarration(narrationElementOutput);
return;
}
super.updateWidgetNarration(narrationElementOutput);
}
public static class LoadingHeader extends Entry {
private static final Component LOADING_LABEL = Component.translatable("flashback.select_replay.loading_replays");
private final Minecraft minecraft;
public LoadingHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) {
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOADING_LABEL)) / 2;
int q = j + (m - this.minecraft.font.lineHeight) / 2;
guiGraphics.drawString(this.minecraft.font, LOADING_LABEL, p, q, 0xFFFFFF, false);
String string = LoadingDotsText.get(Util.getMillis());
int r = (this.minecraft.screen.width - this.minecraft.font.width(string)) / 2;
int s = q + this.minecraft.font.lineHeight;
guiGraphics.drawString(this.minecraft.font, string, r, s, -8355712, false);
}
@Override
public Component getNarration() {
return LOADING_LABEL;
}
}
public final class ReplayListEntry extends Entry implements AutoCloseable {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final SelectReplayScreen screen;
final ReplaySummary summary;
private final FaviconTexture icon;
private long lastClickTime;
public ReplayListEntry(ReplaySelectionList replaySelectionList2, ReplaySummary ReplaySummary) {
this.minecraft = replaySelectionList2.minecraft;
this.screen = replaySelectionList2.getScreen();
this.summary = ReplaySummary;
this.icon = FaviconTexture.forWorld(this.minecraft.getTextureManager(), ReplaySummary.getReplayId());
this.loadIcon();
}
@Override
public Component getNarration() {
MutableComponent component = Component.translatable("narrator.select.world_info", this.summary.getReplayName(),
Component.translationArg(new Date(this.summary.getLastPlayed())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@Override
public void render(GuiGraphics guiGraphics, int i, int j, int k, int l, int m, int n, int o, boolean bl, float f) {
String title = this.summary.getReplayName();
String fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastPlayed();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (i + 1);
}
Component info = this.summary.getInfo();
guiGraphics.drawString(this.minecraft.font, title, k + ICON_WIDTH + 3, j + 1, 0xFFFFFF, false);
guiGraphics.drawString(this.minecraft.font, fileAndTime, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
guiGraphics.drawString(this.minecraft.font, info, k + ICON_WIDTH + 3, j + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blit(this.icon.textureLocation(), k, j, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || bl) {
guiGraphics.fill(k, j, k + ICON_WIDTH, j + ICON_HEIGHT, -1601138544);
int q = n - k;
boolean bl2 = q < 32;
if (!this.summary.canOpen()) {
ResourceLocation resourceLocation3 = bl2 ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
guiGraphics.blitSprite(resourceLocation3, k, j, ICON_WIDTH, ICON_HEIGHT);
} else {
ResourceLocation resourceLocation = bl2 ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
guiGraphics.blitSprite(resourceLocation, k, j, ICON_WIDTH, ICON_HEIGHT);
}
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
if (!this.summary.canOpen()) {
return true;
}
ReplaySelectionList.this.setSelected(this);
if (d - (double) ReplaySelectionList.this.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) {
if (this.canOpen()) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
this.openReplay();
}
return true;
}
this.lastClickTime = Util.getMillis();
return super.mouseClicked(d, e, i);
}
public boolean canOpen() {
return this.summary.canOpen();
}
public void openReplay() {
if (this.summary.canOpen()) {
this.minecraft.forceSetScreen(new GenericMessageScreen(Component.translatable("flashback.select_replay.data_read")));
Flashback.openReplayWorld(this.summary.getPath());
}
}
public void deleteReplay() {
this.minecraft.setScreen(new ConfirmScreen(bl -> {
if (bl) {
this.minecraft.setScreen(new ProgressScreen(true));
this.doDeleteReplay();
}
this.minecraft.setScreen(this.screen);
}, Component.translatable("flashback.select_replay.delete_question"),
Component.translatable("selectWorld.deleteWarning", this.summary.getReplayName()),
Component.translatable("selectWorld.deleteButton"),
CommonComponents.GUI_CANCEL)
);
}
private void doDeleteReplay() {
String id = this.summary.getReplayId();
try {
Files.delete(this.summary.getPath());
} catch (IOException e) {
SystemToast.onWorldDeleteFailure(this.minecraft, id);
LOGGER.error("Failed to delete replay {}", id, e);
}
ReplaySelectionList.this.reloadWorldList();
}
public void editReplay() {
SystemToast.add(this.minecraft.getToasts(), new SystemToast.SystemToastId(3000),
Component.literal("Sorry"), Component.literal("Editing replay data hasn't been implemented yet"));
// todo:
// EditWorldScreen editWorldScreen;
// ReplayStorageSource.ReplayStorageAccess levelStorageAccess;
// this.queueLoadScreen();
// String string = this.summary.getReplayId();
// try {
// levelStorageAccess = this.minecraft.getReplaySource().validateAndCreateAccess;
// } catch (IOException iOException) {
// SystemToast.onWorldAccessFailure(this.minecraft, string);
// LOGGER.error("Failed to access level {}", (Object)string, (Object)iOException);
// ReplaySelectionList.this.reloadWorldList();
// return;
// } catch (ContentValidationException contentValidationException) {
// LOGGER.warn("{}", (Object)contentValidationException.getMessage());
// this.minecraft.setScreen(NoticeWithLinkScreen.createWorldSymlinkWarningScreen(() -> this.minecraft.setScreen(this.screen)));
// return;
// }
// try {
// editWorldScreen = EditWorldScreen.create(this.minecraft, levelStorageAccess, bl -> {
// levelStorageAccess.safeClose();
// if (bl) {
// ReplaySelectionList.this.reloadWorldList();
// }
// this.minecraft.setScreen(this.screen);
// });
// } catch (IOException | NbtException | ReportedNbtException exception) {
// levelStorageAccess.safeClose();
// SystemToast.onWorldAccessFailure(this.minecraft, string);
// LOGGER.error("Failed to load world data {}", (Object)string, (Object)exception);
// ReplaySelectionList.this.reloadWorldList();
// return;
// }
// this.minecraft.setScreen(editWorldScreen);
}
private void loadIcon() {
byte[] iconBytes = this.summary.getIconBytes();
if (iconBytes != null) {
try {
this.icon.upload(NativeImage.read(iconBytes));
return;
} catch (Throwable t) {
LOGGER.error("Invalid icon for replay {}", this.summary.getReplayId(), t);
}
}
this.icon.clear();
}
@Override
public void close() {
this.icon.close();
}
}
public static abstract class Entry extends ObjectSelectionList.Entry<Entry> implements AutoCloseable {
@Override
public void close() {}
}
}
@@ -0,0 +1,100 @@
/*
* Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4).
*/
package com.moulberry.flashback.screen;
import com.moulberry.flashback.editor.ui.windows.TimelineWindow;
import com.moulberry.flashback.record.FlashbackMeta;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.MutableComponent;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
public class ReplaySummary implements Comparable<ReplaySummary> {
private final Path path;
private final FlashbackMeta metadata;
private final String replayId;
private final long lastOpened;
private final byte[] iconBytes;
private Component info = null;
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastOpened, @Nullable byte[] iconBytes) {
this.path = path;
this.metadata = metadata;
this.replayId = replayId;
this.lastOpened = lastOpened;
this.iconBytes = iconBytes;
}
public Path getPath() {
return this.path;
}
public String getReplayId() {
return this.replayId;
}
public String getReplayName() {
return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name;
}
public long getLastPlayed() {
return this.lastOpened;
}
public Component getInfo() {
if (this.info == null) {
MutableComponent mutable = Component.empty();
if (this.metadata.totalTicks > 0) {
int ticks = this.metadata.totalTicks;
int seconds = (ticks / 20) % 60;
int minutes = (ticks / 20 / 60) % 60;
int hours = ticks / 20 / 60 / 60;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours).append('h');
}
if (minutes > 0) {
if (!builder.isEmpty()) {
builder.append(' ');
}
builder.append(minutes).append('m');
}
if (seconds > 0) {
if (!builder.isEmpty()) {
builder.append(' ');
}
builder.append(seconds).append('s');
}
mutable.append(Component.translatable("flashback.select_replay.duration", builder));
}
this.info = mutable;
}
return this.info;
}
public byte[] getIconBytes() {
return this.iconBytes;
}
public boolean canOpen() {
return true;
}
@Override
public int compareTo(ReplaySummary levelSummary) {
if (this.getLastPlayed() < levelSummary.getLastPlayed()) {
return 1;
}
if (this.getLastPlayed() > levelSummary.getLastPlayed()) {
return -1;
}
return this.replayId.compareTo(levelSummary.replayId);
}
}
@@ -0,0 +1,100 @@
package com.moulberry.flashback.screen;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
public class SelectReplayScreen extends Screen {
protected final Screen lastScreen;
private Button deleteButton;
private Button selectButton;
private Button editButton;
protected EditBox searchBox;
private ReplaySelectionList list;
public SelectReplayScreen(Screen screen) {
super(Component.translatable("flashback.select_replay"));
this.lastScreen = screen;
}
@Override
protected void init() {
this.searchBox = new EditBox(this.font, this.width / 2 - 100, 22, 200, 20, this.searchBox, Component.translatable("selectWorld.search"));
this.searchBox.setResponder(string -> this.list.updateFilter(string));
this.addWidget(this.searchBox);
this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft,
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list));
this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay)
.bounds(this.width / 2 - 150, this.height - 52, 300, 20).build());
this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay)
.bounds(this.width / 2 - 150, this.height - 28, 146, 20).build());
this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay)
.bounds(this.width / 2 + 4, this.height - 28, 146, 20).build());
this.updateButtonStatus(null);
}
@Override
protected void setInitialFocus() {
this.setInitialFocus(this.searchBox);
}
@Override
public void onClose() {
this.minecraft.setScreen(this.lastScreen);
}
@Override
public void render(GuiGraphics guiGraphics, int i, int j, float f) {
super.render(guiGraphics, i, j, f);
this.searchBox.render(guiGraphics, i, j, f);
guiGraphics.drawCenteredString(this.font, this.title, this.width / 2, 8, 0xFFFFFF);
}
public void updateButtonStatus(@Nullable ReplaySummary replaySummary) {
if (this.selectButton == null) {
return;
}
if (replaySummary == null) {
this.selectButton.active = false;
this.editButton.active = false;
this.deleteButton.active = false;
} else {
this.selectButton.active = replaySummary.canOpen();
this.editButton.active = true;
this.deleteButton.active = true;
}
}
@Override
public void removed() {
if (this.list != null) {
this.list.children().forEach(ReplaySelectionList.Entry::close);
}
}
private void tryOpenReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.openReplay();
}
}
private void tryEditReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.editReplay();
}
}
private void tryDeleteReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.deleteReplay();
}
}
}