Implement replay folders & sorting

This commit is contained in:
Moulberry committed 2024-11-17 02:18:26 +08:00
1 parent 44794e4edd
commit 1a17640856
21 files changed
+1088 -565

No files matched your search

@@ -378,6 +378,8 @@ public class Flashback implements ModInitializer, ClientModInitializer {
}
}
}
Flashback.getConfig().tickDelayedSave();
});
ClientTickEvents.START_CLIENT_TICK.register(minecraft -> {
@@ -536,7 +538,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
private void deleteUnusedReplayStates() {
Path flashbackDir = Flashback.getDataDirectory();
Path replayDir = flashbackDir.resolve("replays");
Path replayDir = Flashback.getReplayFolder();
Path replayStatesDir = flashbackDir.resolve("editor_states");
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
@@ -777,7 +779,7 @@ public class Flashback implements ModInitializer, ClientModInitializer {
if (config.recentReplays.size() > 32) {
config.recentReplays.remove(config.recentReplays.size() - 1);
}
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
// Actually load
try {
@@ -5,6 +5,7 @@ import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.FlashbackGson;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.keyframe.interpolation.InterpolationType;
import com.moulberry.flashback.screen.select_replay.ReplaySorting;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.ChatFormatting;
import net.minecraft.client.OptionInstance;
@@ -79,6 +80,11 @@ public class FlashbackConfig {
public String defaultExportFilename = "%date%T%time%";
public InterpolationType defaultInterpolationType = InterpolationType.SMOOTH;
public ReplaySorting replaySorting = ReplaySorting.CREATED_DATE;
public boolean sortDescending = true;
private transient int saveDelay = 0;
@SuppressWarnings("unchecked")
public OptionInstance<?>[] createOptionInstances() {
List<OptionInstance<?>> options = new ArrayList<>();
@@ -213,12 +219,28 @@ public class FlashbackConfig {
return new FlashbackConfig();
}
public void delayedSaveToDefaultFolder() {
if (this.saveDelay <= 0) {
this.saveDelay = 200;
}
}
public void tickDelayedSave() {
if (this.saveDelay > 0) {
this.saveDelay -= 1;
if (this.saveDelay == 0) {
this.saveToDefaultFolder();
}
}
}
public void saveToDefaultFolder() {
Path configFolder = FabricLoader.getInstance().getConfigDir().resolve("flashback");
this.saveToFolder(configFolder);
this.saveDelay = 0;
}
public void saveToFolder(Path configFolder) {
public synchronized void saveToFolder(Path configFolder) {
Path primary = configFolder.resolve("flashback.json");
Path backup = configFolder.resolve(".flashback.json.backup");
@@ -2,9 +2,8 @@ package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.exporting.AsyncFileDialogs;
import com.moulberry.flashback.exporting.ExportJobQueue;
import com.moulberry.flashback.screen.SelectReplayScreen;
import com.moulberry.flashback.screen.select_replay.SelectReplayScreen;
import imgui.ImGui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.TitleScreen;
@@ -73,7 +72,7 @@ public class MainMenuBar {
minecraft.level.disconnect();
}
minecraft.disconnect();
minecraft.setScreen(new SelectReplayScreen(new TitleScreen()));
minecraft.setScreen(new SelectReplayScreen(new TitleScreen(), Flashback.getReplayFolder()));
}
ImGui.endMenu();
}
@@ -105,7 +104,7 @@ public class MainMenuBar {
} else {
openedWindows.add(windowName);
}
Flashback.getConfig().saveToDefaultFolder();
Flashback.getConfig().delayedSaveToDefaultFolder();
}
}
@@ -54,39 +54,39 @@ public class MovementWindow {
boolean flightCameraDirection = direction[0] == 1;
if (config.flightCameraDirection != flightCameraDirection) {
config.flightCameraDirection = flightCameraDirection;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
float[] momentum = new float[]{config.flightMomentum};
ImGui.sliderFloat("Momentum", momentum, 0.0f, 1.0f);
if (config.flightMomentum != momentum[0]) {
config.flightMomentum = momentum[0];
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
if (ImGui.checkbox("Lock X", config.flightLockX)) {
config.flightLockX = !config.flightLockX;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Y", config.flightLockY)) {
config.flightLockY = !config.flightLockY;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Z", config.flightLockZ)) {
config.flightLockZ = !config.flightLockZ;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
if (ImGui.checkbox("Lock Yaw", config.flightLockYaw)) {
config.flightLockYaw = !config.flightLockYaw;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
ImGui.sameLine();
if (ImGui.checkbox("Lock Pitch", config.flightLockPitch)) {
config.flightLockPitch = !config.flightLockPitch;
config.saveToDefaultFolder();
config.delayedSaveToDefaultFolder();
}
}
ImGui.end();
@@ -1,6 +1,7 @@
package com.moulberry.flashback.editor.ui.windows;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.editor.ui.WindowOpenState;
import imgui.type.ImBoolean;
@@ -22,7 +23,8 @@ public enum WindowType {
}
public static void renderAll() {
Set<String> openWindows = Flashback.getConfig().openedWindows;
FlashbackConfig config = Flashback.getConfig();
Set<String> openWindows = config.openedWindows;
for (WindowType windowType : values()) {
if (openWindows.contains(windowType.windowId)) {
@@ -33,6 +35,7 @@ public enum WindowType {
if (!windowType.open.get()) {
openWindows.remove(windowType.windowId);
config.delayedSaveToDefaultFolder();
}
windowType.openState = WindowOpenState.OPEN;
@@ -2,26 +2,18 @@ package com.moulberry.flashback.mixin.ui;
import com.llamalad7.mixinextras.injector.wrapoperation.Operation;
import com.llamalad7.mixinextras.injector.wrapoperation.WrapOperation;
import com.llamalad7.mixinextras.sugar.Local;
import com.llamalad7.mixinextras.sugar.ref.LocalIntRef;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.screen.FlashbackButton;
import com.moulberry.flashback.screen.SelectReplayScreen;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import com.moulberry.flashback.screen.select_replay.SelectReplayScreen;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.components.AbstractButton;
import net.minecraft.client.gui.components.AbstractWidget;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.ImageButton;
import net.minecraft.client.gui.components.Renderable;
import net.minecraft.client.gui.components.events.GuiEventListener;
import net.minecraft.client.gui.screens.AlertScreen;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
@@ -95,7 +87,7 @@ public class MixinTitleScreen extends Screen {
List<String> incompatibleMods = Screen.hasShiftDown() ? List.of() : Flashback.getReplayIncompatibleMods();
if (incompatibleMods.isEmpty()) {
this.minecraft.setScreen(new SelectReplayScreen(this));
this.minecraft.setScreen(new SelectReplayScreen(this, Flashback.getReplayFolder()));
} else {
String mods = StringUtils.join(incompatibleMods, ", ");
String description = """
@@ -20,6 +20,7 @@ public class FlashbackMeta {
public UUID replayIdentifier = UUID.randomUUID();
public String name = "Unnamed";
public String versionString = null;
public String worldName = null;
public String bobbyWorldName = null;
public int dataVersion = 0;
public int protocolVersion = 0;
@@ -39,6 +40,9 @@ public class FlashbackMeta {
if (this.versionString != null) {
meta.addProperty("version_string", this.versionString);
}
if (this.worldName != null) {
meta.addProperty("world_name", this.worldName);
}
if (this.dataVersion != 0) {
meta.addProperty("data_version", this.dataVersion);
}
@@ -98,6 +102,9 @@ public class FlashbackMeta {
if (meta.has("version_string")) {
flashbackMeta.versionString = meta.get("version_string").getAsString();
}
if (meta.has("world_name")) {
flashbackMeta.worldName = meta.get("world_name").getAsString();
}
if (meta.has("data_version")) {
flashbackMeta.dataVersion = meta.get("data_version").getAsInt();
}
@@ -27,9 +27,12 @@ import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.ClientPacketListener;
import net.minecraft.client.multiplayer.MultiPlayerGameMode;
import net.minecraft.client.multiplayer.PlayerInfo;
import net.minecraft.client.multiplayer.ServerData;
import net.minecraft.client.player.AbstractClientPlayer;
import net.minecraft.client.player.LocalPlayer;
import net.minecraft.client.resources.language.I18n;
import net.minecraft.client.resources.server.ServerPackManager;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.core.*;
import net.minecraft.nbt.NbtOps;
import net.minecraft.nbt.Tag;
@@ -156,6 +159,24 @@ public class Recorder {
if (Flashback.supportsDistantHorizons) {
this.metadata.distantHorizonPaths.putAll(DistantHorizonsSupport.getDimensionPaths());
}
String worldName = null;
ServerData serverData = Minecraft.getInstance().getCurrentServer();
if (serverData != null) {
worldName = serverData.name;
if (worldName.equalsIgnoreCase(I18n.get("selectServer.defaultName"))) {
worldName = null;
}
} else {
IntegratedServer integratedServer = Minecraft.getInstance().getSingleplayerServer();
if (integratedServer != null) {
worldName = integratedServer.worldData.getLevelName();
if (worldName.equalsIgnoreCase(I18n.get("selectWorld.newWorld"))) {
worldName = null;
}
}
}
this.metadata.worldName = worldName;
}
public boolean readyToWrite() {
@@ -36,7 +36,7 @@ public class EditReplayScreen extends Screen {
private Path replayPath;
protected EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) {
public EditReplayScreen(@Nullable Screen lastScreen, ReplaySummary summary) {
super(Component.literal("Edit Replay"));
this.lastScreen = lastScreen;
this.metadata = summary.getReplayMetadata();
@@ -1,525 +0,0 @@
/*
* 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.google.gson.reflect.TypeToken;
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.FlashbackGson;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.record.FlashbackMeta;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.SharedConstants;
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.WidgetSprites;
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 WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted");
static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning");
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;
private final LoadFromDeviceHeader loadFromDeviceHeader;
private Map<UUID, Long> lastOpenTimes = null;
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.loadFromDeviceHeader = new LoadFromDeviceHeader(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 Path getOpenTimeCachePath() {
// Path flashbackDir = Flashback.getDataDirectory();
// Path replayDir = flashbackDir.resolve("replays");
// return replayDir.resolve(".lastopened.json");
// }
//
// private synchronized long getOpenTime(UUID uuid) {
// if (this.lastOpenTimes == null) {
// Path path = getOpenTimeCachePath();
//
// if (Files.exists(path)) {
// try {
// String serialized = Files.readString(path);
// TypeToken<Map<UUID, Long>> typeToken = (TypeToken<Map<UUID, Long>>) TypeToken.getParameterized(Map.class, UUID.class, Long.class);
// this.lastOpenTimes = FlashbackGson.PRETTY.fromJson(serialized, typeToken);
// return this.lastOpenTimes.getOrDefault(uuid, 0L);
// } catch (IOException e) {
// Flashback.LOGGER.error("Unable to read last opened cache", e);
// }
// }
//
// this.lastOpenTimes = new HashMap<>();
// }
//
// return this.lastOpenTimes.getOrDefault(uuid, 0L);
// }
//
// private synchronized void setOpenTime(UUID uuid, long time) {
// this.lastOpenTimes.put(uuid, time);
// }
//
// private synchronized void saveOpenTimeCache() {
// String serialized = FlashbackGson.PRETTY.toJson(this.lastOpenTimes);
// try {
// Files.writeString(getOpenTimeCachePath(), serialized, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING,
// StandardOpenOption.CREATE);
// } catch (IOException e) {
// Flashback.LOGGER.error("Unable to write last opened cache", e);
// }
// }
private CompletableFuture<List<ReplaySummary>> loadReplays() {
Path flashbackDir = Flashback.getDataDirectory();
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 lastModified = Math.max(basicFileAttributes.creationTime().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, lastModified, iconBytes);
}
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay", 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();
this.addEntry(this.loadFromDeviceHeader);
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.loadFromDeviceHeader);
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) {
if (entry instanceof LoadFromDeviceHeader) {
Flashback.openReplayFromFileBrowser();
return;
}
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 static class LoadFromDeviceHeader extends Entry {
private static final Component LOAD_REPLAY_LABEL = Component.translatable("flashback.select_replay.load_replay_from_file");
private static final WidgetSprites SPRITES = new WidgetSprites(ResourceLocation.withDefaultNamespace("widget/button"), ResourceLocation.withDefaultNamespace("widget/button_disabled"),
ResourceLocation.withDefaultNamespace("widget/button_highlighted"));
private final Minecraft minecraft;
public LoadFromDeviceHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
guiGraphics.blitSprite(SPRITES.get(true, hovered), x + 4, y + 2, width - 8, height - 4);
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOAD_REPLAY_LABEL)) / 2;
int q = y + (height - this.minecraft.font.lineHeight) / 2 + 1;
guiGraphics.drawString(this.minecraft.font, LOAD_REPLAY_LABEL, p, q, 0xFFFFFF, true);
}
@Override
public Component getNarration() {
return LOAD_REPLAY_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.getLastModified())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
String title = this.summary.getReplayName();
String fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastModified();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (index + 1);
}
Component info = this.summary.getInfo();
int titleColour = 0xFFFFFF;
if (!this.summary.canOpen()) {
titleColour = 0xFF5555;
} else if (this.summary.hasWarning()) {
titleColour = 0xFFAA55;
}
guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false);
guiGraphics.drawString(this.minecraft.font, fileAndTime, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
guiGraphics.drawString(this.minecraft.font, info, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blit(this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
if (hovered && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY);
}
ResourceLocation iconOverlay;
if (!this.summary.canOpen()) {
iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
} else if (this.summary.hasWarning()) {
iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE;
} else {
iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
}
guiGraphics.blitSprite(iconOverlay, x, y, 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());
// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis());
// saveOpenTimeCache();
}
}
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() {
Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary));
}
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() {}
}
}
@@ -19,17 +19,19 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
private final FlashbackMeta metadata;
private final String replayId;
private final long lastModified;
private final long filesize;
private final byte[] iconBytes;
private Component info = null;
private Component hoverInfo = null;
private boolean canOpen = true;
private boolean hasWarning = false;
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, @Nullable byte[] iconBytes) {
public ReplaySummary(Path path, FlashbackMeta metadata, String replayId, long lastModified, long filesize, @Nullable byte[] iconBytes) {
this.path = path;
this.metadata = metadata;
this.replayId = replayId;
this.lastModified = lastModified;
this.filesize = filesize;
this.iconBytes = iconBytes;
if (metadata.protocolVersion != 0 && metadata.protocolVersion != SharedConstants.getProtocolVersion()) {
@@ -71,10 +73,18 @@ public class ReplaySummary implements Comparable<ReplaySummary> {
return this.metadata.name.isEmpty() ? this.replayId : this.metadata.name;
}
public @Nullable String getWorldName() {
return this.metadata.worldName;
}
public long getLastModified() {
return this.lastModified;
}
public long getFilesize() {
return filesize;
}
public Component getInfo() {
if (this.info == null) {
MutableComponent mutable = Component.empty();
@@ -48,7 +48,7 @@ public class UnsupportedLoaderScreen extends Screen {
if (this.countdown == 0) {
var button = Button.builder(Component.literal("I Understand"), b -> {
Flashback.getConfig().nextUnsupportedModLoaderWarning = System.currentTimeMillis() + Duration.ofDays(7).toMillis();
Flashback.getConfig().saveToDefaultFolder();
Flashback.getConfig().delayedSaveToDefaultFolder();
Minecraft.getInstance().setScreen(this.lastScreen);
}).bounds((this.width - 150) / 2, buttonY, 150, 20).build();
this.addRenderableWidget(button);
@@ -0,0 +1,157 @@
package com.moulberry.flashback.screen.select_replay;/*
NaturalOrderComparator.java -- Perform 'natural order' comparisons of strings in Java.
Copyright (C) 2003 by Pierre-Luc Paour <[email protected]>
Based on the C version by Martin Pool, of which this is more or less a straight conversion.
Copyright (C) 2000 by Martin Pool <[email protected]>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
===== Moulberry =====
This is an altered source version.
This message is marking it as such.
=====================
*/
import java.util.*;
public class NaturalOrderComparator implements Comparator<String> {
public static NaturalOrderComparator INSTANCE = new NaturalOrderComparator();
private int compareRight(String a, String b) {
int bias = 0, ia = 0, ib = 0;
// The longest run of digits wins. That aside, the greatest
// value wins, but we can't know that it will until we've scanned
// both numbers to know that they have the same magnitude, so we
// remember it in BIAS.
for (;; ia++, ib++) {
char ca = charAt(a, ia);
char cb = charAt(b, ib);
if (!isDigit(ca) && !isDigit(cb)) {
return bias;
}
if (!isDigit(ca)) {
return -1;
}
if (!isDigit(cb)) {
return +1;
}
if (ca == 0 && cb == 0) {
return bias;
}
if (bias == 0) {
if (ca < cb) {
bias = -1;
} else if (ca > cb) {
bias = +1;
}
}
}
}
public int compare(String a, String b) {
int indexA = 0, indexB = 0;
int numZeroesA, numZeroesB;
char charA, charB;
while (true) {
// Only count the number of zeroes leading the last number compared
numZeroesA = numZeroesB = 0;
charA = charAt(a, indexA);
charB = charAt(b, indexB);
// skip over leading spaces or zeros
while (Character.isSpaceChar(charA) || charA == '0') {
if (charA == '0') {
numZeroesA++;
} else {
// Only count consecutive zeroes
numZeroesA = 0;
}
charA = charAt(a, ++indexA);
}
while (Character.isSpaceChar(charB) || charB == '0') {
if (charB == '0') {
numZeroesB++;
} else {
// Only count consecutive zeroes
numZeroesB = 0;
}
charB = charAt(b, ++indexB);
}
if (charA == 0 && charB == 0) {
// The strings compare the same. Perhaps the caller
// will want to call strcmp to break the tie.
return compareEqual(a, b, numZeroesA, numZeroesB);
}
// Process run of digits
boolean isDigitA = Character.isDigit(charA);
boolean isDigitB = Character.isDigit(charB);
if (isDigitA && isDigitB) {
int bias = compareRight(a.substring(indexA), b.substring(indexB));
if (bias != 0) {
return bias;
}
}
if (isDigitA && !isDigitB) {
return 1;
}
if (isDigitB && !isDigitA) {
return -1;
}
int charCompare = Character.compare(charA, charB);
if (charCompare != 0) {
return charCompare;
}
++indexA;
++indexB;
}
}
private static boolean isDigit(char c) {
return Character.isDigit(c) || c == '.' || c == ',';
}
private static char charAt(String s, int i) {
return i >= s.length() ? 0 : s.charAt(i);
}
private static int compareEqual(String a, String b, int nza, int nzb) {
if (nza - nzb != 0) {
return nza - nzb;
}
if (a.length() == b.length()) {
return a.compareTo(b);
}
return a.length() - b.length();
}
}
@@ -0,0 +1,52 @@
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.client.Minecraft;
import java.nio.file.Path;
import java.util.Locale;
public interface PendingSelectionEntry {
ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft);
boolean matchesFilter(String filter);
record Folder(Path path, String filename, long modifiedTime, int replayCount) implements PendingSelectionEntry {
public Folder(Path path, long modifiedTime, int replayCount) {
this(path, path.getFileName().toString().toLowerCase(Locale.ROOT), modifiedTime, replayCount);
}
@Override
public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) {
return new ReplaySelectionEntry.ReplayFolder(replaySelectionList, minecraft, this.path, this.modifiedTime, this.replayCount);
}
@Override
public boolean matchesFilter(String filter) {
return this.filename.contains(filter);
}
}
record Replay(ReplaySummary summary) implements PendingSelectionEntry {
@Override
public ReplaySelectionEntry createEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft) {
return new ReplaySelectionEntry.ReplayListEntry(replaySelectionList, minecraft, this.summary);
}
@Override
public boolean matchesFilter(String filter) {
if (this.summary.getReplayName().toLowerCase(Locale.ROOT).contains(filter) ||
this.summary.getReplayId().toLowerCase(Locale.ROOT).contains(filter)) {
return true;
}
String worldName = this.summary.getWorldName();
if (worldName != null) {
return worldName.toLowerCase(Locale.ROOT).contains(filter);
} else {
return false;
}
}
}
}
@@ -0,0 +1,342 @@
package com.moulberry.flashback.screen.select_replay;
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.screen.EditReplayScreen;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.ChatFormatting;
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.WidgetSprites;
import net.minecraft.client.gui.components.toasts.SystemToast;
import net.minecraft.client.gui.screens.ConfirmScreen;
import net.minecraft.client.gui.screens.FaviconTexture;
import net.minecraft.client.gui.screens.GenericMessageScreen;
import net.minecraft.client.gui.screens.LoadingDotsText;
import net.minecraft.client.gui.screens.ProgressScreen;
import net.minecraft.client.renderer.RenderType;
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.NotNull;
import org.slf4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Date;
import java.util.Locale;
public abstract class ReplaySelectionEntry extends ObjectSelectionList.Entry<ReplaySelectionEntry> implements AutoCloseable {
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withZone(ZoneId.systemDefault());
private static final ResourceLocation FOLDER_SPRITE = Flashback.createResourceLocation("folder");
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 WARNING_HIGHLIGHTED_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning_highlighted");
static private final ResourceLocation WARNING_SPRITE = ResourceLocation.withDefaultNamespace("world_list/warning");
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();
@Override
public void close() {
}
public static class LoadFromDeviceHeader extends ReplaySelectionEntry {
private static final Component LOAD_REPLAY_LABEL = Component.translatable("flashback.select_replay.load_replay_from_file");
private static final WidgetSprites SPRITES = new WidgetSprites(ResourceLocation.withDefaultNamespace("widget/button"), ResourceLocation.withDefaultNamespace("widget/button_disabled"),
ResourceLocation.withDefaultNamespace("widget/button_highlighted"));
private final Minecraft minecraft;
public LoadFromDeviceHeader(Minecraft minecraft) {
this.minecraft = minecraft;
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
guiGraphics.blitSprite(RenderType::guiTextured, SPRITES.get(true, hovered), x + 4, y + 2, width - 8, height - 4);
int p = (this.minecraft.screen.width - this.minecraft.font.width(LOAD_REPLAY_LABEL)) / 2;
int q = y + (height - this.minecraft.font.lineHeight) / 2 + 1;
guiGraphics.drawString(this.minecraft.font, LOAD_REPLAY_LABEL, p, q, 0xFFFFFF, true);
}
@Override
public Component getNarration() {
return LOAD_REPLAY_LABEL;
}
}
public static class LoadingHeader extends ReplaySelectionEntry {
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 static class ReplayFolder extends ReplaySelectionEntry implements AutoCloseable {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final ReplaySelectionList replaySelectionList;
private final Path path;
private final String nameString;
private final Component nameComponent;
private final long modifiedTime;
private final int replayCount;
private long lastClickTime;
public ReplayFolder(ReplaySelectionList replaySelectionList, Minecraft minecraft, Path path, long modifiedTime, int replayCount) {
this.minecraft = minecraft;
this.replaySelectionList = replaySelectionList;
this.path = path;
this.nameString = path.getFileName().toString();
this.nameComponent = Component.literal(this.nameString).withStyle(ChatFormatting.BOLD);
this.modifiedTime = modifiedTime;
this.replayCount = replayCount;
}
@Override
public Component getNarration() {
return Component.translatable("narrator.select", nameComponent);
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
guiGraphics.drawString(this.minecraft.font, this.nameComponent, x + ICON_WIDTH + 3, y + 1, -1, false);
int textY = y + this.minecraft.font.lineHeight + 2;
if (this.modifiedTime > 0) {
String time = "Created: " + DATE_FORMAT.format(Instant.ofEpochMilli(this.modifiedTime));
guiGraphics.drawString(this.minecraft.font, time, x + ICON_WIDTH + 3, textY + 1, 0xFF808080, false);
textY += this.minecraft.font.lineHeight;
}
guiGraphics.drawString(this.minecraft.font, "Replays: " + this.replayCount, x + ICON_WIDTH + 3, textY + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blitSprite(RenderType::guiTextured, FOLDER_SPRITE, x, y, ICON_WIDTH, ICON_HEIGHT);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
ResourceLocation iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
this.replaySelectionList.setSelected(this);
if (d - (double) this.replaySelectionList.getRowLeft() <= 32.0 || Util.getMillis() - this.lastClickTime < 250L) {
this.minecraft.getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0f));
this.minecraft.setScreen(new SelectReplayScreen(this.replaySelectionList.getScreen(), this.path));
return true;
}
this.lastClickTime = Util.getMillis();
return super.mouseClicked(d, e, i);
}
}
public static class ReplayListEntry extends ReplaySelectionEntry implements AutoCloseable {
private static final int ICON_WIDTH = 32;
private static final int ICON_HEIGHT = 32;
private final Minecraft minecraft;
private final ReplaySelectionList replaySelectionList;
final ReplaySummary summary;
private FaviconTexture icon;
private long lastClickTime;
public ReplayListEntry(ReplaySelectionList replaySelectionList, Minecraft minecraft, ReplaySummary ReplaySummary) {
this.minecraft = minecraft;
this.replaySelectionList = replaySelectionList;
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.getLastModified())),
this.summary.getInfo());
return Component.translatable("narrator.select", component);
}
@Override
public void render(GuiGraphics guiGraphics, int index, int y, int x, int width, int height, int mouseX, int mouseY, boolean hovered, float partialTick) {
String title = this.summary.getReplayName();
String fileAndTime = this.summary.getReplayId();
long p = this.summary.getLastModified();
if (p != -1L) {
fileAndTime = fileAndTime + " (" + DATE_FORMAT.format(Instant.ofEpochMilli(p)) + ")";
}
if (StringUtils.isEmpty(title)) {
title = I18n.get("flashback.select_replay.replay") + " " + (index + 1);
}
Component info = this.summary.getInfo();
int titleColour = 0xFFFFFF;
if (!this.summary.canOpen()) {
titleColour = 0xFF5555;
} else if (this.summary.hasWarning()) {
titleColour = 0xFFAA55;
}
int titleEnd = guiGraphics.drawString(this.minecraft.font, title, x + ICON_WIDTH + 3, y + 1, titleColour, false);
String worldName = this.summary.getWorldName();
if (worldName != null) {
guiGraphics.drawString(this.minecraft.font, "(" + worldName + ")", titleEnd + 4, y + 1, 0xFF808080, false);
}
guiGraphics.drawString(this.minecraft.font, fileAndTime, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
guiGraphics.drawString(this.minecraft.font, info, x + ICON_WIDTH + 3, y + this.minecraft.font.lineHeight + this.minecraft.font.lineHeight + 3, 0xFF808080, false);
RenderSystem.enableBlend();
guiGraphics.blit(RenderType::guiTextured, this.icon.textureLocation(), x, y, 0.0f, 0.0f, 32, 32, 32, 32);
RenderSystem.disableBlend();
if (this.minecraft.options.touchscreen().get() || hovered) {
guiGraphics.fill(x, y, x + ICON_WIDTH, y + ICON_HEIGHT, -1601138544);
int q = mouseX - x;
boolean hoveredIcon = q < 32;
if (hovered && this.summary.getHoverInfo() != null) {
guiGraphics.renderTooltip(this.minecraft.font, this.minecraft.font.split(this.summary.getHoverInfo(), 240), mouseX, mouseY);
}
ResourceLocation iconOverlay;
if (!this.summary.canOpen()) {
iconOverlay = hoveredIcon ? ERROR_HIGHLIGHTED_SPRITE : ERROR_SPRITE;
} else if (this.summary.hasWarning()) {
iconOverlay = hoveredIcon ? WARNING_HIGHLIGHTED_SPRITE : WARNING_SPRITE;
} else {
iconOverlay = hoveredIcon ? JOIN_HIGHLIGHTED_SPRITE : JOIN_SPRITE;
}
guiGraphics.blitSprite(RenderType::guiTextured, iconOverlay, x, y, ICON_WIDTH, ICON_HEIGHT);
}
}
@Override
public boolean mouseClicked(double d, double e, int i) {
if (!this.summary.canOpen()) {
return true;
}
this.replaySelectionList.setSelected(this);
if (d - (double) this.replaySelectionList.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());
// setOpenTime(this.summary.getReplayMetadata().replayIdentifier, System.currentTimeMillis());
// saveOpenTimeCache();
}
}
public void deleteReplay() {
this.minecraft.setScreen(new ConfirmScreen(bl -> {
if (bl) {
this.minecraft.setScreen(new ProgressScreen(true));
this.doDeleteReplay();
}
this.minecraft.setScreen(this.replaySelectionList.getScreen());
}, 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);
}
this.replaySelectionList.reloadReplayList();
}
public void editReplay() {
Minecraft.getInstance().setScreen(new EditReplayScreen(Minecraft.getInstance().screen, this.summary));
}
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() {
if (this.icon != null) {
this.icon.close();
this.icon = null;
}
}
}
}
@@ -0,0 +1,282 @@
/*
* Decompiled with CFR 0.2.2 (FabricMC 7c48b8c4).
*/
package com.moulberry.flashback.screen.select_replay;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.SneakyThrow;
import com.moulberry.flashback.record.FlashbackMeta;
import com.moulberry.flashback.screen.ReplaySummary;
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.narration.NarrationElementOutput;
import net.minecraft.client.gui.navigation.CommonInputs;
import net.minecraft.client.resources.sounds.SimpleSoundInstance;
import net.minecraft.sounds.SoundEvents;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ReplaySelectionList extends ObjectSelectionList<ReplaySelectionEntry> {
private final SelectReplayScreen screen;
private CompletableFuture<List<PendingSelectionEntry>> pendingReplays;
@Nullable
private List<PendingSelectionEntry> currentlyDisplayedReplays;
private String filter;
private ReplaySorting replaySorting;
private boolean sortDescending;
private final ReplaySelectionEntry.LoadingHeader loadingHeader;
private final ReplaySelectionEntry.LoadFromDeviceHeader loadFromDeviceHeader;
public ReplaySelectionList(SelectReplayScreen selectReplayScreen, Minecraft minecraft, int i, int j, int k, int l,
String filter, ReplaySorting replaySorting, boolean sortDescending,
@Nullable ReplaySelectionList replaySelectionList) {
super(minecraft, i, j, k, l);
this.screen = selectReplayScreen;
this.loadingHeader = new ReplaySelectionEntry.LoadingHeader(minecraft);
this.loadFromDeviceHeader = new ReplaySelectionEntry.LoadFromDeviceHeader(minecraft);
this.filter = filter;
this.replaySorting = replaySorting;
this.sortDescending = sortDescending;
this.pendingReplays = replaySelectionList != null ? replaySelectionList.pendingReplays : this.loadReplays();
this.fillLoadingReplays();
}
@Override
protected void clearEntries() {
this.children().forEach(ReplaySelectionEntry::close);
super.clearEntries();
}
@Nullable
private List<PendingSelectionEntry> pollReplaysIgnoreErrors() {
try {
return this.pendingReplays.getNow(null);
} catch (CancellationException | CompletionException runtimeException) {
return null;
}
}
public void reloadReplayList() {
this.pendingReplays = this.loadReplays();
}
@Override
public boolean keyPressed(int i, int j, int k) {
if (CommonInputs.selected(i)) {
ReplaySelectionEntry.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<PendingSelectionEntry> list = this.pollReplaysIgnoreErrors();
if (this.currentlyDisplayedReplays != list) {
if (list == null) {
this.fillLoadingReplays();
} else {
list.sort(this.replaySorting.comparator(this.sortDescending));
this.fillReplays(this.filter, list);
}
this.currentlyDisplayedReplays = list;
}
super.renderWidget(guiGraphics, i, j, f);
}
public void updateFilter(String filter, ReplaySorting replaySorting, boolean sortDescending) {
if (this.currentlyDisplayedReplays != null) {
if (this.replaySorting != replaySorting || this.sortDescending != sortDescending) {
this.currentlyDisplayedReplays.sort(replaySorting.comparator(sortDescending));
this.fillReplays(filter, this.currentlyDisplayedReplays);
} else if (!filter.equals(this.filter)) {
this.fillReplays(filter, this.currentlyDisplayedReplays);
}
}
this.filter = filter;
this.replaySorting = replaySorting;
this.sortDescending = sortDescending;
}
private CompletableFuture<List<PendingSelectionEntry>> loadReplays() {
Path replayDir = this.screen.path;
if (!Files.exists(replayDir) || !Files.isDirectory(replayDir)) {
return CompletableFuture.completedFuture(List.of());
}
ArrayList<CompletableFuture<PendingSelectionEntry>> futures = new ArrayList<>();
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(replayDir)) {
for (Path path : directoryStream) {
if (Files.isDirectory(path)) {
futures.add(CompletableFuture.supplyAsync(() -> {
try {
BasicFileAttributeView attributeView = Files.getFileAttributeView(path, BasicFileAttributeView.class);
BasicFileAttributes basicFileAttributes = attributeView.readAttributes();
long lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
int replaysInFolder = 0;
try (DirectoryStream<Path> filesInFolder = Files.newDirectoryStream(path)) {
for (Path fileInFolder : filesInFolder) {
if (fileInFolder.toString().endsWith(".zip")) {
replaysInFolder += 1;
}
}
}
return new PendingSelectionEntry.Folder(path, lastModified, replaysInFolder);
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay folder", e);
}
return null;
}, Util.backgroundExecutor()));
continue;
}
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 lastModified = Math.max(basicFileAttributes.creationTime().toMillis(), basicFileAttributes.lastModifiedTime().toMillis());
long filesize = basicFileAttributes.size();
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) {
ReplaySummary summary = new ReplaySummary(path, metadata, fileName, lastModified, filesize, iconBytes);
return new PendingSelectionEntry.Replay(summary);
}
} catch (IOException e) {
Flashback.LOGGER.error("Failed to load replay", e);
}
return null;
}, Util.backgroundExecutor()));
}
} catch (IOException e) {
SneakyThrow.sneakyThrow(e);
}
return Util.sequenceFailFastAndCancel(futures).thenApply(list -> {
list.removeIf(Objects::isNull);
return list;
});
}
private void fillReplays(String filter, List<PendingSelectionEntry> list) {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
filter = filter.toLowerCase(Locale.ROOT);
for (PendingSelectionEntry entry : list) {
if (entry.matchesFilter(filter)) {
this.addEntry(entry.createEntry(this, this.minecraft));
}
}
this.notifyListUpdated();
}
private void fillLoadingReplays() {
this.clearEntries();
this.addEntry(this.loadFromDeviceHeader);
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 ReplaySelectionEntry entry) {
if (entry instanceof ReplaySelectionEntry.LoadFromDeviceHeader) {
Flashback.openReplayFromFileBrowser();
return;
}
super.setSelected(entry);
if (entry instanceof ReplaySelectionEntry.ReplayListEntry replayListEntry) {
this.screen.updateButtonStatus(replayListEntry.summary);
} else {
this.screen.updateButtonStatus(null);
}
}
@Nullable
public ReplaySelectionEntry.ReplayListEntry getReplayListEntry() {
if (this.getSelected() instanceof ReplaySelectionEntry.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);
}
}
@@ -0,0 +1,76 @@
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.network.chat.Component;
import java.util.Comparator;
public enum ReplaySorting {
CREATED_DATE(
Component.literal("Created Date"),
Comparator.comparingLong(ReplaySummary::getLastModified).reversed(),
Comparator.comparingLong(ReplaySummary::getLastModified)
),
REPLAY_NAME(
Component.literal("Replay Name"),
Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE),
Comparator.comparing(ReplaySummary::getReplayName, NaturalOrderComparator.INSTANCE.reversed())
),
WORLD_NAME(
Component.literal("World Name"),
Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE)),
Comparator.comparing(ReplaySummary::getWorldName, Comparator.nullsLast(NaturalOrderComparator.INSTANCE.reversed()))
),
DURATION(
Component.literal("Duration"),
Comparator.<ReplaySummary>comparingLong(replay -> replay.getReplayMetadata().totalTicks).reversed(),
Comparator.comparingLong(replay -> replay.getReplayMetadata().totalTicks)
),
FILESIZE(
Component.literal("Filesize"),
Comparator.comparingLong(ReplaySummary::getFilesize).reversed(),
Comparator.comparingLong(ReplaySummary::getFilesize)
);
private final Component component;
private final Comparator<ReplaySummary> descendingComparator;
private final Comparator<ReplaySummary> ascendingComparator;
ReplaySorting(Component component, Comparator<ReplaySummary> descendingComparator, Comparator<ReplaySummary> ascendingComparator) {
this.component = component;
this.descendingComparator = descendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE);
this.ascendingComparator = ascendingComparator.thenComparing(ReplaySummary::getReplayId, NaturalOrderComparator.INSTANCE);
}
public Component component() {
return this.component;
}
public Comparator<PendingSelectionEntry> comparator(boolean descending) {
Comparator<ReplaySummary> replayComparator;
if (descending) {
replayComparator = this.descendingComparator;
} else {
replayComparator = this.ascendingComparator;
}
return (entry1, entry2) -> {
if (entry1 instanceof PendingSelectionEntry.Replay replay1) {
if (entry2 instanceof PendingSelectionEntry.Replay replay2) {
return replayComparator.compare(replay1.summary(), replay2.summary());
} else {
return 1;
}
} else if (entry1 instanceof PendingSelectionEntry.Folder folder1) {
if (entry2 instanceof PendingSelectionEntry.Folder folder2) {
return NaturalOrderComparator.INSTANCE.compare(folder1.filename(), folder2.filename());
} else {
return -1;
}
} else {
return 0;
}
};
}
}
@@ -1,44 +1,77 @@
package com.moulberry.flashback.screen;
package com.moulberry.flashback.screen.select_replay;
import com.moulberry.flashback.Flashback;
import com.moulberry.flashback.configuration.FlashbackConfig;
import com.moulberry.flashback.screen.ConfigScreen;
import com.moulberry.flashback.screen.ReplaySummary;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.gui.components.CycleButton;
import net.minecraft.client.gui.components.EditBox;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.network.chat.CommonComponents;
import net.minecraft.network.chat.Component;
import org.jetbrains.annotations.Nullable;
import java.nio.file.Path;
public class SelectReplayScreen extends Screen {
protected final Screen lastScreen;
public final Path path;
private Button selectButton;
private Button editButton;
private Button deleteButton;
protected EditBox searchBox;
private ReplaySelectionList list;
public SelectReplayScreen(Screen screen) {
public SelectReplayScreen(Screen screen, Path path) {
super(Component.translatable("flashback.select_replay"));
this.lastScreen = screen;
this.path = path;
}
@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.searchBox = new EditBox(this.font, this.width / 2 - 128, 22, 126, 20, this.searchBox, Component.translatable("selectWorld.search"));
this.searchBox.setResponder(string -> {
FlashbackConfig config = Flashback.getConfig();
this.list.updateFilter(string, config.replaySorting, config.sortDescending);
});
this.addWidget(this.searchBox);
FlashbackConfig config = Flashback.getConfig();
this.addRenderableWidget(CycleButton.builder(ReplaySorting::component)
.withValues(ReplaySorting.values())
.withInitialValue(config.replaySorting)
.create(this.width / 2 + 2, 22, 125, 20, Component.literal("Sort"), (button, sorting) -> {
FlashbackConfig configuration = Flashback.getConfig();
configuration.replaySorting = sorting;
configuration.delayedSaveToDefaultFolder();
this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending);
})
);
this.addRenderableWidget(new SortDirectionButton(this.width / 2 + 131, 22, 20, 20, Component.literal("Sort Direction"),
sortDescending -> {
FlashbackConfig configuration = Flashback.getConfig();
configuration.sortDescending = sortDescending;
configuration.delayedSaveToDefaultFolder();
this.list.updateFilter(this.searchBox.getValue(), configuration.replaySorting, configuration.sortDescending);
}, config.sortDescending));
this.list = this.addRenderableWidget(new ReplaySelectionList(this, this.minecraft,
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), this.list));
this.width, this.height - 112, 48, 36, this.searchBox.getValue(), config.replaySorting, config.sortDescending, this.list));
this.selectButton = this.addRenderableWidget(Button.builder(Component.translatable("flashback.select_replay.open"), this::tryOpenReplay)
.bounds(this.width / 2 - 154, this.height - 52, 308, 20).build());
.bounds(this.width / 2 - 151, this.height - 52, 302, 20).build());
this.editButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.edit"), this::tryEditReplay)
.bounds(this.width / 2 - 154, this.height - 28, 97, 20).build());
.bounds(this.width / 2 - 151, this.height - 28, 98, 20).build());
this.deleteButton = this.addRenderableWidget(Button.builder(Component.translatable("selectWorld.delete"), this::tryDeleteReplay)
.bounds(this.width / 2 - 49, this.height - 28, 98, 20).build());
this.addRenderableWidget(Button.builder(CommonComponents.GUI_BACK, button -> this.minecraft.setScreen(this.lastScreen))
.bounds(this.width / 2 + 57, this.height - 28, 97, 20).build());
.bounds(this.width / 2 + 53, this.height - 28, 98, 20).build());
if (this.width/2 > 154 + 128) {
this.addRenderableWidget(Button.builder(Component.literal("Flashback Settings"), btn -> Minecraft.getInstance().setScreen(new ConfigScreen(this)))
@@ -83,26 +116,26 @@ public class SelectReplayScreen extends Screen {
@Override
public void removed() {
if (this.list != null) {
this.list.children().forEach(ReplaySelectionList.Entry::close);
this.list.clearEntries();
}
}
private void tryOpenReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.openReplay();
}
}
private void tryEditReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.editReplay();
}
}
private void tryDeleteReplay(Button button) {
ReplaySelectionList.ReplayListEntry entry = this.list.getReplayListEntry();
ReplaySelectionEntry.ReplayListEntry entry = this.list.getReplayListEntry();
if (entry != null) {
entry.deleteReplay();
}
@@ -0,0 +1,50 @@
package com.moulberry.flashback.screen.select_replay;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.Button;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.ResourceLocation;
import java.util.function.Consumer;
public class SortDirectionButton extends Button {
private static final ResourceLocation DOWN_ARROW = ResourceLocation.parse("flashback:down_arrow.png");
private static final ResourceLocation UP_ARROW = ResourceLocation.parse("flashback:up_arrow.png");
public boolean sortDescending;
public SortDirectionButton(int x, int y, int width, int height, Component component, Consumer<Boolean> changed, boolean initialSortDescending) {
super(x, y, width, height, component, button -> {
SortDirectionButton sortButton = (SortDirectionButton) button;
sortButton.sortDescending = !sortButton.sortDescending;
changed.accept(sortButton.sortDescending);
}, DEFAULT_NARRATION);
this.sortDescending = initialSortDescending;
}
@Override
protected void renderWidget(GuiGraphics guiGraphics, int i, int j, float f) {
super.renderWidget(guiGraphics, i, j, f);
final int size = 16;
int paddingX = (this.getWidth() - size) / 2;
int paddingY = (this.getHeight() - size) / 2;
int x = this.getX() + paddingX;
int y = this.getY() + paddingY;
if (this.sortDescending) {
guiGraphics.blit(RenderType::guiTextured, DOWN_ARROW, x, y, 0f, 0f, size, size, size, size);
} else {
guiGraphics.blit(RenderType::guiTextured, UP_ARROW, x, y, 0f, 0f, size, size, size, size);
}
}
@Override
public void renderString(GuiGraphics guiGraphics, Font font, int i) {
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 156 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 143 B