Skip to content

Commit

Permalink
Better saving system and further ContextMenu layout
Browse files Browse the repository at this point in the history
  • Loading branch information
tanishisherewithhh committed Apr 6, 2024
1 parent b7a36c0 commit 762d88e
Show file tree
Hide file tree
Showing 8 changed files with 83 additions and 24 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class DynamicHUD implements ClientModInitializer {

public static MinecraftClient MC = MinecraftClient.getInstance();
public static String MOD_ID = "dynamichud";
private static final Logger logger = LoggerFactory.getLogger("DynamicHud");
Expand Down Expand Up @@ -60,7 +60,9 @@ public void onInitializeClient() {
GlobalConfig.HANDLER.load();

printInfo("Integrating mods...");
FabricLoader.getInstance().getEntrypointContainers("dynamicHud", DynamicHudIntegration.class).forEach(entrypoint -> {
FabricLoader.getInstance()
.getEntrypointContainers("dynamicHud", DynamicHudIntegration.class)
.forEach(entrypoint -> {
ModMetadata metadata = entrypoint.getProvider().getMetadata();
String modId = metadata.getId();
AbstractMoveableScreen screen;
Expand Down Expand Up @@ -92,18 +94,18 @@ public void onInitializeClient() {
});

// Save during exiting a world, server or Minecraft itself
// Also saved when a resource pack is reloaded.
ServerLifecycleEvents.SERVER_STOPPING.register(server -> saveWidgetsSafely(widgetsFile));
ServerLifecycleEvents.END_DATA_PACK_RELOAD.register((server, resourceManager, s) -> saveWidgetsSafely(widgetsFile));
ServerPlayConnectionEvents.DISCONNECT.register((handler, packetSender) -> saveWidgetsSafely(widgetsFile));
Runtime.getRuntime().addShutdownHook(new Thread(() -> saveWidgetsSafely(widgetsFile)));


printInfo(String.format("Integration of mod %s was successful",modId));
} catch (Throwable e) {
if(e instanceof IOException){
logger.warn("An error has occured while loading widgets of mod {}", modId,e);
logger.warn("An error has occurred while loading widgets of mod {}", modId,e);
}else {
logger.warn("Mod {} has incorrect implementation of dynamicHud", modId, e);
logger.warn("Mod {} has incorrect implementation of DynamicHUD", modId, e);
}
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package com.tanishisherewith.dynamichud.newTrial.utils;

import com.tanishisherewith.dynamichud.newTrial.DynamicHUD;

public class Util {
public enum Quadrant {
UPPER_LEFT, UPPER_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT
}

public static Quadrant getQuadrant(int x, int y) {
int screenWidth = DynamicHUD.MC.getWindow().getScaledWidth();
int screenHeight = DynamicHUD.MC.getWindow().getScaledHeight();

if (x < screenWidth / 2) {
if (y < screenHeight / 2) {
return Quadrant.UPPER_LEFT;
} else {
return Quadrant.BOTTOM_LEFT;
}
} else {
if (y < screenHeight / 2) {
return Quadrant.UPPER_RIGHT;
} else {
return Quadrant.BOTTOM_RIGHT;
}
}
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.tanishisherewith.dynamichud.newTrial.utils.contextmenu;

public class ContextMenu {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package com.tanishisherewith.dynamichud.newTrial.utils.contextmenu;

public abstract class Option<T> {
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,13 @@ public boolean isOverlapping(Widget other) {
/**
* Renders the widget on the screen.
*/
public void render(DrawContext drawContext) {
public void render(DrawContext drawContext, int mouseX, int mouseY) {
if (!shouldDisplay()) return;

if (shouldScale) {
DrawHelper.scaleAndPosition(drawContext.getMatrices(), getX(), getY(), GlobalConfig.get().scale);
}
renderWidget(drawContext);
updateWidgetBox();
renderWidget(drawContext,mouseX,mouseY);

if (shouldScale) {
DrawHelper.stopScaling(drawContext.getMatrices());
Expand All @@ -137,8 +136,7 @@ public void renderInEditor(DrawContext drawContext, int mouseX, int mouseY) {
if (shouldScale) {
DrawHelper.scaleAndPosition(drawContext.getMatrices(), getX(), getY(), GlobalConfig.get().scale);
}
renderWidgetInEditor(drawContext);
updateWidgetBox();
renderWidgetInEditor(drawContext,mouseX,mouseY);

if (shouldScale) {
DrawHelper.stopScaling(drawContext.getMatrices());
Expand All @@ -151,10 +149,15 @@ protected void updateWidgetBox(){

/**
* Renders the widget on the screen
* <p>
* The mouse position values are only passed when in a {@link com.tanishisherewith.dynamichud.newTrial.screens.AbstractMoveableScreen} screen.
* </p>
*
* @param context
* @param mouseX X position of mouse.
* @param mouseY Y position of mouse
*/
public abstract void renderWidget(DrawContext context);
public abstract void renderWidget(DrawContext context,int mouseX, int mouseY);


/**
Expand All @@ -164,10 +167,10 @@ protected void updateWidgetBox(){
*
* @param context
*/
private void renderWidgetInEditor(DrawContext context) {
private void renderWidgetInEditor(DrawContext context,int mouseX, int mouseY) {
displayBg(context);

renderWidget(context);
renderWidget(context,mouseX,mouseY);
}

public boolean mouseClicked(double mouseX, double mouseY, int button) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.tanishisherewith.dynamichud.newTrial.widget;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

import com.tanishisherewith.dynamichud.DynamicHUD;
Expand Down Expand Up @@ -164,18 +166,32 @@ public static void saveWidgets(File file) throws IOException {
widget.writeToTag(widgetTag);
// Check for duplicates
if (widgetSet.add(widgetTag.toString())) {
printInfo("Saving Widget: " + widget);
widgetList.add(widgetTag);
}
}

rootTag.put("widgets", widgetList);

//Write the data to the file
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(file))) {
// Backup the old file
File backupFile = new File(file.getAbsolutePath() + ".bak");
if (file.exists()) {
Files.copy(file.toPath(), backupFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

// Write the data to a temporary file
File tempFile = new File(file.getAbsolutePath() + ".tmp");
try (DataOutputStream out = new DataOutputStream(new FileOutputStream(tempFile))) {
NbtIo.write(rootTag, out);
}catch (IOException e){
DynamicHUD.logger.warn("Error while saving",e);
} catch (IOException e) {
DynamicHUD.logger.warn("Error while saving", e);
// If save operation failed, restore the backup
Files.move(backupFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
throw e; // rethrow the exception
}

// If save operation was successful, replace the old file with the new one
Files.move(tempFile.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

/**
Expand All @@ -195,6 +211,7 @@ public static void loadWidgets(File file) throws IOException {
WidgetData<?> widgetData = widgetDataMap.get(widgetTag.getString("name"));
Widget widget = widgetData.createWidget();
widget.readFromTag(widgetTag);
printInfo("Loading Widget: " + widget);
widgets.add(widget);
}
}else{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public void renderWidgets(DrawContext context, int mouseX, int mouseY) {
if(currentScreen == null && renderInGameHud){
for (Widget widget : widgets) {
widget.isInEditor = false;
widget.render(context);
widget.render(context,0,0);
}
return;
}
Expand All @@ -52,7 +52,7 @@ public void renderWidgets(DrawContext context, int mouseX, int mouseY) {
if (currentScreen != null && allowedScreens.contains(DynamicHUD.MC.currentScreen.getClass()) && !this.isInEditor) {
for (Widget widget : widgets) {
widget.isInEditor = false;
widget.render(context);
widget.render(context,0,0);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public TextWidget(DynamicValueRegistry dynamicValueRegistry,String dynamicRegist
}

@Override
public void renderWidget(DrawContext drawContext) {
public void renderWidget(DrawContext drawContext,int mouseX, int mouseY) {
int color = rainbow ? ColorHelper.getColorFromHue((System.currentTimeMillis() % 10000) / 10000f) : Color.WHITE.getRGB();
if(textSupplier != null) {
String text = textSupplier.get();
Expand All @@ -66,23 +66,23 @@ public void renderWidget(DrawContext drawContext) {
@Override
public void writeToTag(NbtCompound tag) {
super.writeToTag(tag);
tag.putString("DRKey",dynamicRegistryKey);
tag.putString("DynamicRegistryKey",dynamicRegistryKey);
tag.putBoolean("shadow",shadow);
tag.putBoolean("rainbow",rainbow);

// If true then it means that we should use local registry and if false (i.e. null) then use global registry
tag.putBoolean("DVRObj", dynamicValueRegistry != null);
tag.putBoolean("DynamicValueRegistry", dynamicValueRegistry != null);
}

@Override
public void readFromTag(NbtCompound tag) {
super.readFromTag(tag);
shadow = tag.getBoolean("shadow");
rainbow = tag.getBoolean("rainbow");
dynamicRegistryKey = tag.getString("DRKey");
dynamicRegistryKey = tag.getString("DynamicRegistryKey");

// If true then it means that we should use local registry and if false (i.e. null) then use global registry
boolean dvrObj = tag.getBoolean("DVRObj");
boolean dvrObj = tag.getBoolean("DynamicValueRegistry");

if(!dvrObj && dynamicRegistryKey != null){
textSupplier = (Supplier<String>) DynamicValueRegistry.getGlobal(dynamicRegistryKey);
Expand Down

0 comments on commit 762d88e

Please sign in to comment.