Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

minor updates #122

Merged
merged 18 commits into from
May 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import me.xmrvizzy.skyblocker.config.SkyblockerConfig;
import me.xmrvizzy.skyblocker.discord.DiscordRPCManager;
import me.xmrvizzy.skyblocker.skyblock.HotbarSlotLock;
import me.xmrvizzy.skyblocker.skyblock.api.RepositoryUpdate;
import me.xmrvizzy.skyblocker.skyblock.api.StatsCommand;
import me.xmrvizzy.skyblocker.skyblock.dwarven.DwarvenHud;
import me.xmrvizzy.skyblocker.skyblock.item.PriceInfoTooltip;
Expand All @@ -20,6 +21,7 @@ public void onInitializeClient() {
PriceInfoTooltip.init();
WikiLookup.init();
ItemRegistry.init();
RepositoryUpdate.init();
StatsCommand.init();
DwarvenHud.init();
ChatMessageListener.init();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public enum BarPosition {
NONE;

@Override
public String toString() {
public String toString() {
return I18n.translate("text.autoconfig.skyblocker.option.general.bars.barpositions." + name());
}

Expand Down Expand Up @@ -215,7 +215,7 @@ public enum Average {
BOTH;

@Override
public String toString() {
public String toString() {
return I18n.translate("text.autoconfig.skyblocker.option.general.itemTooltip.avg." + name());
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package me.xmrvizzy.skyblocker.skyblock.api;

import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager;
import net.fabricmc.fabric.api.client.command.v2.ClientCommandRegistrationCallback;
import net.minecraft.text.Text;

import java.io.File;
import java.nio.file.Files;
import java.util.concurrent.CompletableFuture;

public class RepositoryUpdate {

/**
* Adds command to update repository manually from ingame.
* <p></p>
* TODO A button could be added to the settings menu that will trigger this command.
*/
public static void init(){
ClientCommandRegistrationCallback.EVENT.register((dispatcher, registryAccess) -> dispatcher.register(
ClientCommandManager.literal("skyblocker")
.then(ClientCommandManager.literal("updaterepository")
.executes(context -> {
CompletableFuture.runAsync(() -> {
try {
ItemRegistry.filesImported = false;
File dir = ItemRegistry.LOCAL_ITEM_REPO_DIR.toFile();
recursiveDelete(dir);
} catch (Exception ex) {
ItemRegistry.client.player.sendMessage(
Text.translatable("skyblocker.updaterepository.failed")
, false
);
return;
}

ItemRegistry.init();
});

return 1;
})
)
)
);

}

private static void recursiveDelete(File dir) {
if (dir.isDirectory() && !Files.isSymbolicLink(dir.toPath())) {
for (File child : dir.listFiles()) {
recursiveDelete(child);
}
}
dir.delete();
}
}
363 changes: 166 additions & 197 deletions src/main/java/me/xmrvizzy/skyblocker/skyblock/item/PriceInfoTooltip.java

Large diffs are not rendered by default.

29 changes: 6 additions & 23 deletions src/main/java/me/xmrvizzy/skyblocker/skyblock/item/WikiLookup.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package me.xmrvizzy.skyblocker.skyblock.item;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import me.xmrvizzy.skyblocker.skyblock.itemlist.ItemRegistry;
import me.xmrvizzy.skyblocker.utils.Utils;
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.minecraft.client.MinecraftClient;
Expand All @@ -16,11 +14,7 @@
import net.minecraft.util.Util;
import org.lwjgl.glfw.GLFW;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.CompletableFuture;

public class WikiLookup {
public static KeyBinding wikiLookup;
Expand Down Expand Up @@ -51,23 +45,12 @@ public static void openWiki(Slot slot) {
if (Utils.isOnSkyblock) {
id = getSkyblockId(slot);
try {
//Setting up a connection with the repo
String urlString = "https://raw.githubusercontent.com/NotEnoughUpdates/NotEnoughUpdates-REPO/master/items/" + id + ".json";
URL url = new URL(urlString);
URLConnection request = url.openConnection();
request.connect();

//yoinking the wiki link
JsonElement root = JsonParser.parseReader(new InputStreamReader((InputStream) request.getContent()));
JsonObject rootobj = root.getAsJsonObject();
String wikiLink = rootobj.get("info").getAsJsonArray().get(1).getAsString();
Util.getOperatingSystem().open(wikiLink);
} catch (IOException | NullPointerException e) {
e.printStackTrace();
client.player.sendMessage(Text.of("Can't locate a wiki article for this item..."), false);
String wikiLink = ItemRegistry.getWikiLink(id);
CompletableFuture.runAsync(() -> Util.getOperatingSystem().open(wikiLink));
} catch (IndexOutOfBoundsException | IllegalStateException e) {
e.printStackTrace();
client.player.sendMessage(Text.of("Error while retrieving wiki article..."), false);
if (client.player != null)
client.player.sendMessage(Text.of("Error while retrieving wiki article..."), false);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package me.xmrvizzy.skyblocker.skyblock.itemlist;

import com.mojang.blaze3d.systems.RenderSystem;

import me.xmrvizzy.skyblocker.mixin.RecipeBookWidgetAccessor;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
Expand Down Expand Up @@ -40,8 +39,10 @@ public void initialize(int parentWidth, int parentHeight, MinecraftClient client
this.searchField = ((RecipeBookWidgetAccessor)this).getSearchField();
int x = (this.parentWidth - 147) / 2 - this.leftOffset;
int y = (this.parentHeight - 166) / 2;
this.results = new SearchResultsWidget(this.client, x , y);
this.updateSearchResult();
if (ItemRegistry.filesImported) {
this.results = new SearchResultsWidget(this.client, x, y);
this.updateSearchResult();
}
}

@Override
Expand All @@ -57,34 +58,45 @@ public void render(MatrixStack matrices, int mouseX, int mouseY, float delta) {
int j = (this.parentHeight - 166) / 2;
DrawableHelper.drawTexture(matrices, i, j, 1, 1, 147, 166);
this.searchField = ((RecipeBookWidgetAccessor)this).getSearchField();
if (!this.searchField.isFocused() && this.searchField.getText().isEmpty()) {

if (!ItemRegistry.filesImported && !this.searchField.isFocused() && this.searchField.getText().isEmpty()) {
Text hintText = (Text.literal("Loading...")).formatted(Formatting.ITALIC).formatted(Formatting.GRAY);
drawTextWithShadow(matrices, this.client.textRenderer, hintText, i + 25, j + 14, -1);
} else if (!this.searchField.isFocused() && this.searchField.getText().isEmpty()) {
Text hintText = (Text.translatable("gui.recipebook.search_hint")).formatted(Formatting.ITALIC).formatted(Formatting.GRAY);
drawTextWithShadow(matrices, this.client.textRenderer, hintText, i + 25, j + 14, -1);
} else {
this.searchField.render(matrices, mouseX, mouseY, delta);
}
this.updateSearchResult();
this.results.render(matrices, mouseX, mouseY, delta);
if (ItemRegistry.filesImported){
if (results == null) {
int x = (this.parentWidth - 147) / 2 - this.leftOffset;
int y = (this.parentHeight - 166) / 2;
this.results = new SearchResultsWidget(this.client, x, y);
}
this.updateSearchResult();
this.results.render(matrices, mouseX, mouseY, delta);
}
matrices.pop();
}
}

@Override
public void drawTooltip(MatrixStack matrices, int x, int y, int mouseX, int mouseY) {
if (this.isOpen()) {
if (this.isOpen() && ItemRegistry.filesImported && results != null) {
this.results.drawTooltip(matrices, mouseX, mouseY);
}
}

@Override
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (!this.isOpen() || this.client.player.isSpectator()) {
return false;
}
if (this.searchField != null && this.searchField.mouseClicked(mouseX, mouseY, button)) {
this.results.closeRecipeView();
return true;
}
return this.results.mouseClicked(mouseX, mouseY, button);
}
public boolean mouseClicked(double mouseX, double mouseY, int button) {
if (this.isOpen() && !this.client.player.isSpectator() && ItemRegistry.filesImported && results != null) {
if (this.searchField != null && this.searchField.mouseClicked(mouseX, mouseY, button)) {
this.results.closeRecipeView();
return true;
} else
return this.results.mouseClicked(mouseX, mouseY, button);
} else
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,46 @@
import com.google.gson.JsonParser;

import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.text.Text;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.PullResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.concurrent.CompletableFuture;

public class ItemRegistry {
protected static final String REMOTE_ITEM_REPO = "https://github.com/KonaeAkira/NotEnoughUpdates-REPO.git";
protected static final Path LOCAL_ITEM_REPO_DIR = FabricLoader.getInstance().getConfigDir().resolve("skyblocker/item-repo");
private static final Logger LOGGER = LoggerFactory.getLogger(ItemRegistry.class);
protected static final String REMOTE_ITEM_REPO = "https://github.com/NotEnoughUpdates/NotEnoughUpdates-REPO";
public static final Path LOCAL_ITEM_REPO_DIR = FabricLoader.getInstance().getConfigDir().resolve("skyblocker/item-repo");

private static final Path ITEM_LIST_DIR = LOCAL_ITEM_REPO_DIR.resolve("items");
protected static final Path ITEM_LIST_DIR = LOCAL_ITEM_REPO_DIR.resolve("items");

protected static final List<ItemStack> items = new ArrayList<>();
protected static final Map<String, ItemStack> itemsMap = new HashMap<>();
protected static final List<Recipe> recipes = new ArrayList<>();
public static final MinecraftClient client = MinecraftClient.getInstance();
public static boolean filesImported = false;

// TODO: make async
public static void init() {
updateItemRepo();
ItemStackBuilder.init();
importItemFiles();
CompletableFuture.runAsync(ItemRegistry::updateItemRepo)
.whenComplete((result, ex) -> {
if (ex == null) {
ItemStackBuilder.init();
importItemFiles();
}
else {
LOGGER.error("[Skyblocker-ItemRegistry] " + ex);
}
});
}

private static void updateItemRepo() {
Expand All @@ -46,7 +60,14 @@ private static void updateItemRepo() {
}
} else {
try {
Git.open(LOCAL_ITEM_REPO_DIR.toFile()).pull().call();
PullResult pull = Git.open(LOCAL_ITEM_REPO_DIR.toFile()).pull().setRebase(true).call();
if (pull.getRebaseResult() == null) {
LOGGER.info("[Skyblocker Repository Update] No update result");
} else if (pull.getRebaseResult().getStatus().isSuccessful()) {
LOGGER.info("[Skyblocker Repository Update] Status: " + pull.getRebaseResult().getStatus().name());
} else if (!pull.getRebaseResult().getStatus().isSuccessful()) {
LOGGER.warn("[Skyblocker Repository Update] Status: " + pull.getRebaseResult().getStatus().name());
}
} catch (Exception e) {
e.printStackTrace();
}
Expand Down Expand Up @@ -93,6 +114,24 @@ private static void importItemFiles() {
}
return lhsFamilyName.compareTo(rhsFamilyName);
});
filesImported = true;
}

public static String getWikiLink(String internalName) {
try {
String fileContent = Files.readString(ITEM_LIST_DIR.resolve(internalName + ".json"));
JsonObject fileJson = JsonParser.parseString(fileContent).getAsJsonObject();
//TODO optional official or unofficial wiki link
try {
return fileJson.get("info").getAsJsonArray().get(1).getAsString();
} catch (IndexOutOfBoundsException e) {
return fileJson.get("info").getAsJsonArray().get(0).getAsString();
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
client.player.sendMessage(Text.of("Can't locate a wiki article for this item..."), false);
return null;
}
}

public static List<Recipe> getRecipes(String internalName) {
Expand Down Expand Up @@ -135,7 +174,7 @@ public static Recipe fromJsonObject(JsonObject jsonObj) {
private static ItemStack getItemStack(String internalName) {
try {
if (internalName.length() > 0) {
int count = Integer.parseInt(internalName.split(":")[1]);
int count = Integer.parseInt(internalName.split(":").length > 1 ? internalName.split(":")[1] : "1");
internalName = internalName.split(":")[0];
ItemStack itemStack = ItemRegistry.itemsMap.get(internalName).copy();
itemStack.setCount(count);
Expand Down
2 changes: 2 additions & 0 deletions src/main/resources/assets/skyblocker/lang/en_us.json
Original file line number Diff line number Diff line change
Expand Up @@ -195,5 +195,7 @@
"text.autoconfig.skyblocker.option.general.enableUpdateNotification": "Update Notification",
"text.autoconfig.skyblocker.option.general.hideEmptyTooltips": "Hide empty item tooltips in menus",

"skyblocker.updaterepository.failed": "§b[§6Skyblocker§b] §cUpdating local repository failed. Remove files manually and restart game.",

"skyblocker.api.got_key": "§b[§6Skyblocker§b] §2Automatically set your API key!"
}