Files
src
build.gradle
gradle.properties
settings.gradle
Code
5 393
src/client/java/com/kodari/dialogdiagnoser/DialogDiagnoserClient.java
package com.kodari.dialogdiagnoser;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.mojang.serialization.JsonOps;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents;
import net.minecraft.ChatFormatting;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.gui.screens.dialog.DialogScreen;
import net.minecraft.network.chat.Component;
import net.minecraft.server.dialog.Dialog;
import net.minecraft.resources.RegistryOps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
public final class DialogDiagnoserClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("dialogdiagnoser");
private static final Gson PRETTY_GSON = new GsonBuilder().setPrettyPrinting().create();
private static WeakReference<Screen> LAST_REPORTED_SCREEN = new WeakReference<>(null);
private static final Set<String> ACTION_TYPES = Set.of(
"run_command", "dynamic/run_command", "suggest_command", "open_url", "open_file",
"copy_to_clipboard", "change_page", "show_dialog", "custom", "dynamic/custom"
);
private static final Set<String> SENSITIVE_COMMANDS = Set.of(
"op", "deop", "stop", "ban", "ban-ip", "pardon", "kick", "whitelist",
"execute", "function", "reload", "transfer", "data"
);
@Override
public void onInitializeClient() {
ScreenEvents.AFTER_INIT.register((client, screen, scaledWidth, scaledHeight) -> {
if (!(screen instanceof DialogScreen<?>) || LAST_REPORTED_SCREEN.get() == screen) {
return;
}
LAST_REPORTED_SCREEN = new WeakReference<>(screen);
diagnose(client, screen);
});
}
private static void diagnose(Minecraft client, Screen screen) {
Dialog dialog = findDialog(screen);
if (dialog == null) {
LOGGER.warn("Could not find a Dialog field on {}", screen.getClass().getName());
return;
}
JsonElement json;
try {
var connection = client.getConnection();
if (connection != null) {
json = Dialog.DIRECT_CODEC.encodeStart(
RegistryOps.create(JsonOps.INSTANCE, connection.registryAccess()), dialog
).getOrThrow();
} else {
json = Dialog.DIRECT_CODEC.encodeStart(JsonOps.INSTANCE, dialog).getOrThrow();
}
} catch (RuntimeException exception) {
LOGGER.error("Could not encode the dialog for inspection", exception);
return;
}
saveDialogJson(client, json);
String title = json.isJsonObject() ? flattenComponent(json.getAsJsonObject().get("title")) : "";
String type = json.isJsonObject() ? stripMinecraft(stringValue(json.getAsJsonObject().get("type"))) : "unknown";
if (title.isBlank()) {
title = "<untitled>";
}
if (type.isBlank()) {
type = "unknown";
}
List<ReportedAction> actions = new ArrayList<>();
walk(json, "<unknown>", false, true, type.equals("notice"), actions);
List<String> lines = new ArrayList<>();
lines.add("Dialog: " + title + " | type: " + type + " | actions: " + actions.size());
for (ReportedAction action : actions) {
String line = "- [" + action.type() + "] button: \"" + action.label() + "\" -> " + action.detail();
if (action.alsoOnClose()) {
line += " [also fires on ESC/close]";
}
lines.add(line);
}
for (int index = 0; index < lines.size(); index++) {
String line = lines.get(index);
LOGGER.info("{}", line);
var message = Component.literal(line);
if (index > 0 && actions.get(index - 1).sensitive()) {
message = message.withStyle(ChatFormatting.RED);
}
client.gui.hud.getChat().addClientSystemMessage(message);
}
}
private static Dialog findDialog(Screen screen) {
for (Class<?> current = screen.getClass(); current != null; current = current.getSuperclass()) {
for (Field field : current.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()) || !Dialog.class.isAssignableFrom(field.getType())) {
continue;
}
try {
if (!field.trySetAccessible()) {
continue;
}
Object value = field.get(screen);
if (value instanceof Dialog dialog) {
return dialog;
}
} catch (ReflectiveOperationException | RuntimeException exception) {
LOGGER.warn("Could not read dialog field {} on {}", field.getName(), current.getName(), exception);
}
}
}
return null;
}
private static void saveDialogJson(Minecraft client, JsonElement json) {
Path output = client.gameDirectory.toPath().resolve("config/dialogdiagnoser/last_dialog.json");
try {
Files.createDirectories(output.getParent());
Files.writeString(output, PRETTY_GSON.toJson(json), StandardCharsets.UTF_8);
} catch (IOException exception) {
LOGGER.error("Could not save dialog JSON to {}", output, exception);
}
}
private static void walk(JsonElement element, String inheritedLabel, boolean alsoOnClose,
boolean root, boolean noticeDialog, List<ReportedAction> actions) {
if (element == null || element.isJsonNull()) {
return;
}
if (element.isJsonArray()) {
for (JsonElement child : element.getAsJsonArray()) {
walk(child, inheritedLabel, alsoOnClose, false, false, actions);
}
return;
}
if (!element.isJsonObject()) {
return;
}
JsonObject object = element.getAsJsonObject();
String label = inheritedLabel;
if (object.has("label")) {
String buttonLabel = flattenComponent(object.get("label"));
if (!buttonLabel.isBlank()) {
label = buttonLabel;
}
} else if (object.has("click_event")) {
String componentText = flattenComponent(object);
if (!componentText.isBlank()) {
label = componentText;
}
}
String type = stripMinecraft(stringValue(object.get("type")));
if (ACTION_TYPES.contains(type)) {
actions.add(describeAction(type, object, label, alsoOnClose));
}
String clickAction = stripMinecraft(stringValue(object.get("action")));
if (ACTION_TYPES.contains(clickAction)) {
actions.add(describeAction(clickAction, object, label, alsoOnClose));
}
for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
String key = entry.getKey();
boolean childAlsoOnClose = alsoOnClose
|| key.equals("exit_action")
|| key.equals("no")
|| (root && noticeDialog && key.equals("action"));
walk(entry.getValue(), label, childAlsoOnClose, false, false, actions);
}
}
private static ReportedAction describeAction(String type, JsonObject object, String label, boolean alsoOnClose) {
String detail;