Create optional AstraPlus admin editor with validated forms and protocol
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
package online.astradev.plus.editor;
|
||||
|
||||
import net.neoforged.api.distmarker.Dist;
|
||||
import net.neoforged.bus.api.IEventBus;
|
||||
import net.neoforged.fml.common.Mod;
|
||||
import net.neoforged.neoforge.common.NeoForge;
|
||||
import online.astradev.plus.editor.client.EditorClient;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
/** Client bootstrap; the server and ordinary players do not install this mod. */
|
||||
@Mod(value = "astrapluseditor", dist = Dist.CLIENT)
|
||||
public final class AstraPlusEditor {
|
||||
public AstraPlusEditor(IEventBus modBus) {
|
||||
var connection = EditorConnection.INSTANCE;
|
||||
var client = new EditorClient(connection);
|
||||
modBus.addListener(connection::register);
|
||||
modBus.addListener(client::registerKeys);
|
||||
NeoForge.EVENT_BUS.addListener(client::registerCommands);
|
||||
NeoForge.EVENT_BUS.addListener(client::tick);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package online.astradev.plus.editor.client;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.StreamSupport;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
public final class EditorCatalog {
|
||||
private JsonObject catalogs = new JsonObject();
|
||||
|
||||
public void update(JsonObject response) {
|
||||
if (response.has("catalogs") && response.get("catalogs").isJsonObject())
|
||||
catalogs = response.getAsJsonObject("catalogs").deepCopy();
|
||||
}
|
||||
|
||||
public List<String> values(String name) {
|
||||
if (!catalogs.has(name) || !catalogs.get(name).isJsonArray()) return List.of();
|
||||
return StreamSupport.stream(catalogs.getAsJsonArray(name).spliterator(), false)
|
||||
.map(value -> value.getAsString()).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package online.astradev.plus.editor.client;
|
||||
|
||||
import net.minecraft.client.KeyMapping;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.commands.Commands;
|
||||
import net.neoforged.neoforge.client.event.ClientTickEvent;
|
||||
import net.neoforged.neoforge.client.event.RegisterClientCommandsEvent;
|
||||
import net.neoforged.neoforge.client.event.RegisterKeyMappingsEvent;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
import online.astradev.plus.editor.screen.ContentBrowserScreen;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
public final class EditorClient {
|
||||
private final EditorConnection connection;
|
||||
private final KeyMapping open = new KeyMapping("key.astrapluseditor.open", GLFW.GLFW_KEY_F8, KeyMapping.Category.MISC);
|
||||
private boolean requested;
|
||||
|
||||
public EditorClient(EditorConnection connection) { this.connection = connection; }
|
||||
|
||||
public void registerKeys(RegisterKeyMappingsEvent event) { event.register(open); }
|
||||
|
||||
public void registerCommands(RegisterClientCommandsEvent event) {
|
||||
event.getDispatcher().register(Commands.literal("astraplus-editor").executes(context -> {
|
||||
requested = true;
|
||||
return 1;
|
||||
}));
|
||||
}
|
||||
|
||||
public void tick(ClientTickEvent.Post event) {
|
||||
connection.tick();
|
||||
if (requested) { requested = false; open(); }
|
||||
while (open.consumeClick()) {
|
||||
if (Minecraft.getInstance().gui.screen() == null) open();
|
||||
}
|
||||
}
|
||||
|
||||
private void open() {
|
||||
if (Minecraft.getInstance().player != null)
|
||||
Minecraft.getInstance().gui.setScreen(new ContentBrowserScreen(connection));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
/** Examples follow the Minecraft 26.2 component codecs; the server remains the validator. */
|
||||
public final class ComponentExamples {
|
||||
private ComponentExamples() {}
|
||||
|
||||
public static String value(String id) {
|
||||
return switch (id) {
|
||||
case "minecraft:max_damage" -> "1800";
|
||||
case "minecraft:max_stack_size" -> "1";
|
||||
case "minecraft:damage", "minecraft:repair_cost" -> "0";
|
||||
case "minecraft:enchantment_glint_override" -> "true";
|
||||
case "minecraft:damage_resistant" -> "{\"types\":\"#minecraft:is_fire\"}";
|
||||
case "minecraft:enchantable" -> "{\"value\":15}";
|
||||
case "minecraft:enchantments", "minecraft:stored_enchantments" -> "{\"minecraft:unbreaking\":3}";
|
||||
case "minecraft:food" -> "{\"nutrition\":6,\"saturation\":7.2,\"can_always_eat\":false}";
|
||||
case "minecraft:consumable" -> "{\"consume_seconds\":1.6,\"animation\":\"eat\"}";
|
||||
case "minecraft:tool" -> "{\"rules\":[{\"blocks\":\"#minecraft:mineable/pickaxe\",\"speed\":8.0,\"correct_for_drops\":true}],\"default_mining_speed\":1.0,\"damage_per_block\":1,\"can_destroy_blocks_in_creative\":true}";
|
||||
case "minecraft:attribute_modifiers" -> "[{\"type\":\"minecraft:attack_damage\",\"id\":\"astraplus:damage\",\"amount\":5.0,\"operation\":\"add_value\",\"slot\":\"mainhand\"}]";
|
||||
case "minecraft:lore" -> "[\"Описание предмета\"]";
|
||||
default -> "{}";
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonNull;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
|
||||
/** Lossless local draft: helpers change only the selected fields, never rebuild a server document. */
|
||||
public final class ContentDraft {
|
||||
private JsonObject document;
|
||||
private JsonObject saved;
|
||||
private String revision;
|
||||
|
||||
public ContentDraft(JsonObject document, String revision) {
|
||||
this.document = document.deepCopy();
|
||||
this.saved = document.deepCopy();
|
||||
this.revision = revision;
|
||||
}
|
||||
|
||||
public static ContentDraft create(boolean block) {
|
||||
var json = new JsonObject();
|
||||
json.addProperty("id", "astraplus:new_" + (block ? "block" : "item"));
|
||||
json.addProperty("name", block ? "Новый блок" : "Новый предмет");
|
||||
json.addProperty("material", block ? "minecraft:note_block" : "minecraft:paper");
|
||||
json.addProperty("texture", block ? "minecraft:block/stone" : "minecraft:item/paper");
|
||||
if (block) {
|
||||
var settings = new JsonObject();
|
||||
settings.addProperty("slot", 0);
|
||||
settings.addProperty("base", "minecraft:stone");
|
||||
json.add("block", settings);
|
||||
}
|
||||
return new ContentDraft(json, "new");
|
||||
}
|
||||
|
||||
public String id() { return text("", "id"); }
|
||||
public boolean block() { return document.has("block") && document.get("block").isJsonObject(); }
|
||||
public boolean fresh() { return revision.equals("new"); }
|
||||
public String revision() { return revision; }
|
||||
public boolean dirty() { return fresh() || !document.equals(saved); }
|
||||
public JsonObject document() { return document.deepCopy(); }
|
||||
|
||||
public JsonElement get(String... path) {
|
||||
JsonElement value = document;
|
||||
for (String key : path) {
|
||||
if (!value.isJsonObject() || !value.getAsJsonObject().has(key)) return JsonNull.INSTANCE;
|
||||
value = value.getAsJsonObject().get(key);
|
||||
}
|
||||
return value.deepCopy();
|
||||
}
|
||||
|
||||
public String text(String fallback, String... path) {
|
||||
var value = get(path);
|
||||
return value.isJsonPrimitive() ? value.getAsString() : fallback;
|
||||
}
|
||||
|
||||
public void set(JsonElement value, String... path) {
|
||||
var parent = document;
|
||||
for (int index = 0; index < path.length - 1; index++) {
|
||||
String key = path[index];
|
||||
if (!parent.has(key) || !parent.get(key).isJsonObject()) parent.add(key, new JsonObject());
|
||||
parent = parent.getAsJsonObject(key);
|
||||
}
|
||||
if (value == null || value.isJsonNull()) parent.remove(path[path.length - 1]);
|
||||
else parent.add(path[path.length - 1], value.deepCopy());
|
||||
}
|
||||
|
||||
public void string(String value, String... path) { set(new JsonPrimitive(value), path); }
|
||||
public void bool(boolean value, String... path) { set(new JsonPrimitive(value), path); }
|
||||
|
||||
public void number(String value, boolean integer, double min, double max, String... path) {
|
||||
if (value.isBlank()) { set(null, path); return; }
|
||||
BigDecimal number;
|
||||
try { number = new BigDecimal(value.trim()); }
|
||||
catch (NumberFormatException error) { throw new IllegalArgumentException("Введите число."); }
|
||||
if (integer && number.stripTrailingZeros().scale() > 0) throw new IllegalArgumentException("Нужно целое число.");
|
||||
if (number.compareTo(BigDecimal.valueOf(min)) < 0 || number.compareTo(BigDecimal.valueOf(max)) > 0)
|
||||
throw new IllegalArgumentException("Допустимо от " + min + " до " + max + ".");
|
||||
set(new JsonPrimitive(number), path);
|
||||
}
|
||||
|
||||
public void component(JsonElement value, String id) {
|
||||
set(null, "components", "!" + id);
|
||||
set(value, "components", id);
|
||||
}
|
||||
|
||||
public void removeComponent(String id, boolean removeBase) {
|
||||
set(null, "components", id);
|
||||
set(removeBase ? new JsonObject() : null, "components", "!" + id);
|
||||
}
|
||||
|
||||
public void model(String id, boolean customModel) {
|
||||
set(null, customModel ? "texture" : "model");
|
||||
string(id, customModel ? "model" : "texture");
|
||||
}
|
||||
|
||||
public boolean whitelist() { return get("enchantments", "allowed").isJsonArray(); }
|
||||
|
||||
public void whitelist(boolean enabled) {
|
||||
set(enabled ? new JsonArray() : null, "enchantments", "allowed");
|
||||
}
|
||||
|
||||
public Set<String> ids(String key) {
|
||||
var result = new LinkedHashSet<String>();
|
||||
var value = get("enchantments", key);
|
||||
if (value.isJsonArray()) value.getAsJsonArray().forEach(id -> result.add(id.getAsString()));
|
||||
return result;
|
||||
}
|
||||
|
||||
public void enchantment(String id, boolean enabled) {
|
||||
var denied = ids("denied");
|
||||
if (enabled) denied.remove(id); else denied.add(id);
|
||||
set(strings(denied), "enchantments", "denied");
|
||||
if (whitelist()) {
|
||||
var allowed = ids("allowed");
|
||||
if (enabled) allowed.add(id); else allowed.remove(id);
|
||||
set(strings(allowed), "enchantments", "allowed");
|
||||
}
|
||||
}
|
||||
|
||||
public boolean enabled(String id) {
|
||||
return !ids("denied").contains(id) && (!whitelist() || ids("allowed").contains(id));
|
||||
}
|
||||
|
||||
public boolean conflicts(String first, String second) {
|
||||
var value = get("enchantments", "conflicts");
|
||||
if (!value.isJsonArray()) return false;
|
||||
for (var pair : value.getAsJsonArray()) {
|
||||
if (samePair(pair, first, second)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void conflict(String first, String second, boolean enabled) {
|
||||
if (first.equals(second)) throw new IllegalArgumentException("Выберите два разных зачарования.");
|
||||
var old = get("enchantments", "conflicts");
|
||||
var pairs = new JsonArray();
|
||||
if (old.isJsonArray()) for (var pair : old.getAsJsonArray())
|
||||
if (!samePair(pair, first, second)) pairs.add(pair.deepCopy());
|
||||
if (enabled) {
|
||||
var pair = new JsonArray(); pair.add(first); pair.add(second); pairs.add(pair);
|
||||
}
|
||||
set(pairs, "enchantments", "conflicts");
|
||||
}
|
||||
|
||||
public void saved(JsonObject accepted, String revision) {
|
||||
this.document = accepted.deepCopy();
|
||||
this.saved = accepted.deepCopy();
|
||||
this.revision = revision;
|
||||
}
|
||||
|
||||
private static JsonArray strings(Set<String> values) {
|
||||
var array = new JsonArray(); values.forEach(array::add); return array;
|
||||
}
|
||||
|
||||
private static boolean samePair(JsonElement value, String first, String second) {
|
||||
if (!value.isJsonArray() || value.getAsJsonArray().size() != 2) return false;
|
||||
var pair = value.getAsJsonArray();
|
||||
String left = pair.get(0).getAsString(), right = pair.get(1).getAsString();
|
||||
return left.equals(first) && right.equals(second) || left.equals(second) && right.equals(first);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonPrimitive;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
|
||||
public final class ContentFields {
|
||||
private static final List<String> BOOLEAN = List.of("Наследовать", "Да", "Нет");
|
||||
private final ContentDraft draft;
|
||||
private final EditorCatalog catalog;
|
||||
|
||||
public ContentFields(ContentDraft draft, EditorCatalog catalog) {
|
||||
this.draft = draft;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
public List<FormField> basic() {
|
||||
var fields = new ArrayList<FormField>();
|
||||
if (draft.fresh()) fields.add(FormField.text("id", "Идентификатор", "namespace:путь. После создания изменить нельзя.",
|
||||
draft::id, value -> draft.string(value.trim(), "id")));
|
||||
fields.add(FormField.text("name", "Название", "Отображаемое имя предмета или блока.",
|
||||
() -> draft.text("", "name"), value -> draft.string(value, "name")));
|
||||
if (!draft.block()) fields.add(new FormField("material", "Ванильная основа", "Предмет, свойства которого наследуются.",
|
||||
() -> draft.text("minecraft:paper", "material"), value -> draft.string(value.trim(), "material"), catalog.values("items"), false));
|
||||
fields.add(new FormField("appearance", "Источник модели", "Текстура создаёт простую модель. Готовая модель задаёт собственную геометрию.",
|
||||
() -> draft.get("model").isJsonNull() ? "Текстура" : "Готовая модель",
|
||||
value -> draft.model(draft.text(draft.text("", "texture"), "model"), value.equals("Готовая модель")),
|
||||
List.of("Текстура", "Готовая модель"), true));
|
||||
fields.add(FormField.text("asset", "Путь к текстуре / модели", "Например minecraft:item/diamond_sword. Без расширения файла.",
|
||||
() -> draft.text(draft.text("", "texture"), "model"),
|
||||
value -> draft.model(value.trim(), !draft.get("model").isJsonNull())));
|
||||
if (!draft.block()) fields.add(new FormField("handheld", "Положение инструмента в руке", "Для простой автоматически созданной модели.",
|
||||
() -> draft.text("false", "handheld").equals("true") ? "Да" : "Нет",
|
||||
value -> draft.bool(value.equals("Да"), "handheld"), List.of("Нет", "Да"), true));
|
||||
return fields;
|
||||
}
|
||||
|
||||
public List<FormField> properties() {
|
||||
return List.of(
|
||||
numeric("minecraft:max_damage", "Максимальная прочность", true, 1, Integer.MAX_VALUE),
|
||||
numeric("minecraft:max_stack_size", "Размер стопки", true, 1, 99),
|
||||
new FormField("unbreakable", "Неразрушимый предмет", "Запретить расход прочности; пустое значение наследуется от основы.",
|
||||
() -> state("minecraft:unbreakable"), value -> unit(value, "minecraft:unbreakable"), BOOLEAN, true),
|
||||
new FormField("fireproof", "Не сгорает в огне и лаве", "Защита лежащего предмета от источников урона #minecraft:is_fire.",
|
||||
this::fireState, this::fireproof, List.of("Наследовать", "Да", "Нет", "Особая настройка"), true),
|
||||
new FormField("glint", "Эффект зачарования", "Только визуальный блеск. Сами зачарования задаются компонентом enchantments.",
|
||||
() -> componentBoolean("minecraft:enchantment_glint_override"), value -> booleanComponent(value, "minecraft:enchantment_glint_override"), BOOLEAN, true),
|
||||
FormField.text("enchantable", "Зачаровываемость", "Положительное целое число; пусто — наследовать. Влияет на стол зачарований.",
|
||||
() -> draft.text("", "components", "minecraft:enchantable", "value"), value -> {
|
||||
if (value.isBlank()) { draft.removeComponent("minecraft:enchantable", false); return; }
|
||||
draft.number(value, true, 1, Integer.MAX_VALUE, "components", "minecraft:enchantable", "value");
|
||||
draft.set(null, "components", "!minecraft:enchantable");
|
||||
}),
|
||||
FormField.text("nutrition", "Еда: питание", "Пусто — не переопределять. Для употребления нужен также компонент consumable.",
|
||||
() -> draft.text("", "components", "minecraft:food", "nutrition"), value ->
|
||||
food(value, true, "nutrition")),
|
||||
FormField.text("saturation", "Еда: насыщение", "Прямое значение насыщения; для еды задайте также питание.",
|
||||
() -> draft.text("", "components", "minecraft:food", "saturation"), value ->
|
||||
food(value, false, "saturation")));
|
||||
}
|
||||
|
||||
public List<FormField> block() {
|
||||
return List.of(
|
||||
new FormField("base", "Физическая основа на сервере", "Полный ванильный блок без BlockEntity. Коллизия модели остаётся полным блоком.",
|
||||
() -> draft.text("minecraft:stone", "block", "base"), value -> draft.string(value.trim(), "block", "base"), catalog.values("blocks"), false),
|
||||
FormField.text("hardness", "Твёрдость", "Пусто — наследовать от основы. -1 — неразрушимый; 0 — мгновенно.",
|
||||
() -> draft.text("", "block", "hardness"), this::hardness),
|
||||
FormField.text("resistance", "Взрывоустойчивость", "Пусто — наследовать от основы. Ноль не даёт сопротивления взрыву.",
|
||||
() -> draft.text("", "block", "explosionResistance"), value -> draft.number(value, false, 0, 3_600_000, "block", "explosionResistance")),
|
||||
new FormField("tool", "Нужен подходящий инструмент", "Пусто — наследовать. Подходящий тип определяется ванильной основой.",
|
||||
() -> booleanState("block", "requiresCorrectTool"), value -> booleanValue(value, "block", "requiresCorrectTool"), BOOLEAN, true),
|
||||
FormField.text("drop", "Количество выпадающих блоков", "От 0 до 64; пусто — обычный дроп 1. Выпадает этот же пользовательский блок.",
|
||||
() -> draft.text("", "block", "dropCount"), value -> draft.number(value, true, 0, 64, "block", "dropCount")));
|
||||
}
|
||||
|
||||
private FormField numeric(String id, String label, boolean integer, double min, double max) {
|
||||
return FormField.text(id, label, "Пустое поле — наследовать значение от ванильной основы.",
|
||||
() -> draft.text("", "components", id), value -> {
|
||||
draft.number(value, integer, min, max, "components", id);
|
||||
draft.set(null, "components", "!" + id);
|
||||
});
|
||||
}
|
||||
|
||||
private String state(String id) {
|
||||
if (!draft.get("components", "!" + id).isJsonNull()) return "Нет";
|
||||
return draft.get("components", id).isJsonNull() ? "Наследовать" : "Да";
|
||||
}
|
||||
|
||||
private void unit(String value, String id) {
|
||||
if (value.equals("Да")) draft.component(new JsonObject(), id);
|
||||
else draft.removeComponent(id, value.equals("Нет"));
|
||||
}
|
||||
|
||||
private String fireState() {
|
||||
var component = draft.get("components", "minecraft:damage_resistant");
|
||||
if (component.isJsonNull()) return state("minecraft:damage_resistant");
|
||||
return draft.text("", "components", "minecraft:damage_resistant", "types").equals("#minecraft:is_fire")
|
||||
? "Да" : "Особая настройка";
|
||||
}
|
||||
|
||||
private void fireproof(String value) {
|
||||
if (value.equals("Особая настройка")) return;
|
||||
if (value.equals("Да")) {
|
||||
var component = new JsonObject(); component.addProperty("types", "#minecraft:is_fire");
|
||||
draft.component(component, "minecraft:damage_resistant");
|
||||
} else draft.removeComponent("minecraft:damage_resistant", value.equals("Нет"));
|
||||
}
|
||||
|
||||
private String componentBoolean(String id) {
|
||||
return booleanState("components", id);
|
||||
}
|
||||
|
||||
private void booleanComponent(String value, String id) {
|
||||
if (value.equals("Наследовать")) draft.removeComponent(id, false);
|
||||
else draft.component(new JsonPrimitive(value.equals("Да")), id);
|
||||
}
|
||||
|
||||
private String booleanState(String... path) {
|
||||
String value = draft.text("", path);
|
||||
return value.isEmpty() ? "Наследовать" : value.equals("true") ? "Да" : "Нет";
|
||||
}
|
||||
|
||||
private void booleanValue(String value, String... path) {
|
||||
if (value.equals("Наследовать")) draft.set(null, path);
|
||||
else draft.bool(value.equals("Да"), path);
|
||||
}
|
||||
|
||||
private void food(String value, boolean integer, String key) {
|
||||
draft.number(value, integer, 0, 1_000_000, "components", "minecraft:food", key);
|
||||
draft.set(null, "components", "!minecraft:food");
|
||||
var food = draft.get("components", "minecraft:food");
|
||||
if (food.isJsonObject() && food.getAsJsonObject().isEmpty()) draft.removeComponent("minecraft:food", false);
|
||||
}
|
||||
|
||||
private void hardness(String value) {
|
||||
if (!value.isBlank()) {
|
||||
try {
|
||||
var number = new java.math.BigDecimal(value.trim());
|
||||
if (number.signum() < 0 && number.compareTo(java.math.BigDecimal.valueOf(-1)) != 0)
|
||||
throw new IllegalArgumentException("Допустимо -1 или неотрицательное число.");
|
||||
} catch (NumberFormatException error) { throw new IllegalArgumentException("Введите число."); }
|
||||
}
|
||||
draft.number(value, false, -1, 1_000_000, "block", "hardness");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package online.astradev.plus.editor.form;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public record FormField(String key, String label, String hint, Supplier<String> read,
|
||||
Consumer<String> write, List<String> choices, boolean cycle) {
|
||||
public static FormField text(String key, String label, String hint, Supplier<String> read, Consumer<String> write) {
|
||||
return new FormField(key, label, hint, read, write, List.of(), false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package online.astradev.plus.editor.network;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.multiplayer.ClientPacketListener;
|
||||
import net.neoforged.neoforge.client.network.ClientPacketDistributor;
|
||||
import net.neoforged.neoforge.network.event.RegisterPayloadHandlersEvent;
|
||||
|
||||
/** Correlates bounded requests; no packet is sent unless the remote server supports the editor. */
|
||||
public final class EditorConnection {
|
||||
public static final EditorConnection INSTANCE = new EditorConnection();
|
||||
private final Map<Integer, Pending> pending = new HashMap<>();
|
||||
private ClientPacketListener connection;
|
||||
private int nextRequest;
|
||||
|
||||
private EditorConnection() {}
|
||||
|
||||
public void register(RegisterPayloadHandlersEvent event) {
|
||||
event.registrar("1").optional()
|
||||
.playToServer(EditorRequest.TYPE, EditorRequest.CODEC, (request, context) -> {})
|
||||
.playToClient(EditorResponse.TYPE, EditorResponse.CODEC, (response, context) -> receive(response));
|
||||
}
|
||||
|
||||
public boolean available() {
|
||||
var listener = Minecraft.getInstance().getConnection();
|
||||
return listener != null && listener.hasChannel(EditorRequest.TYPE) && listener.hasChannel(EditorResponse.TYPE);
|
||||
}
|
||||
|
||||
public void request(String action, JsonObject body, Consumer<JsonObject> callback) {
|
||||
tick();
|
||||
if (!available()) {
|
||||
callback.accept(error("Сервер не поддерживает редактор AstraPlus или подключение ещё не готово."));
|
||||
return;
|
||||
}
|
||||
if (pending.size() >= 8) {
|
||||
callback.accept(error("Дождитесь ответа на предыдущие запросы."));
|
||||
return;
|
||||
}
|
||||
int requestId = ++nextRequest;
|
||||
var request = body.deepCopy();
|
||||
request.addProperty("requestId", requestId);
|
||||
request.addProperty("action", action);
|
||||
String json = request.toString();
|
||||
if (json.length() > EditorRequest.LIMIT) {
|
||||
callback.accept(error("Документ превышает лимит сетевого редактора (8192 символа). Сократите данные или измените файл на сервере."));
|
||||
return;
|
||||
}
|
||||
pending.put(requestId, new Pending(System.nanoTime(), callback));
|
||||
try {
|
||||
ClientPacketDistributor.sendToServer(new EditorRequest(json));
|
||||
} catch (RuntimeException failure) {
|
||||
pending.remove(requestId);
|
||||
callback.accept(error("Не удалось отправить запрос: " + failure.getMessage()));
|
||||
}
|
||||
}
|
||||
|
||||
public void tick() {
|
||||
var current = Minecraft.getInstance().getConnection();
|
||||
if (current != connection) {
|
||||
var abandoned = Map.copyOf(pending);
|
||||
pending.clear();
|
||||
connection = current;
|
||||
abandoned.values().forEach(value -> value.callback.accept(error("Подключение изменилось. Черновик не сохранён.")));
|
||||
}
|
||||
long now = System.nanoTime();
|
||||
var expired = pending.entrySet().stream()
|
||||
.filter(entry -> now - entry.getValue().started > 15_000_000_000L).toList();
|
||||
for (var entry : expired) {
|
||||
pending.remove(entry.getKey());
|
||||
entry.getValue().callback.accept(error("Сервер не ответил. Перед повторным сохранением проверьте актуальную версию."));
|
||||
}
|
||||
}
|
||||
|
||||
private void receive(EditorResponse payload) {
|
||||
try {
|
||||
var response = JsonParser.parseString(payload.json()).getAsJsonObject();
|
||||
var request = pending.remove(response.get("requestId").getAsInt());
|
||||
if (request != null) request.callback.accept(response);
|
||||
} catch (RuntimeException ignored) {
|
||||
// Malformed or unsolicited replies cannot update a document; pending requests expire normally.
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean success(JsonObject response) {
|
||||
return response.has("ok") && response.get("ok").getAsBoolean();
|
||||
}
|
||||
|
||||
public static String message(JsonObject response) {
|
||||
return response.has("message") ? response.get("message").getAsString() : "Ответ сервера не содержит сообщения.";
|
||||
}
|
||||
|
||||
private static JsonObject error(String message) {
|
||||
var response = new JsonObject();
|
||||
response.addProperty("ok", false);
|
||||
response.addProperty("message", message);
|
||||
return response;
|
||||
}
|
||||
|
||||
private record Pending(long started, Consumer<JsonObject> callback) {}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package online.astradev.plus.editor.network;
|
||||
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
public record EditorRequest(String json) implements CustomPacketPayload {
|
||||
public static final int LIMIT = 8192;
|
||||
public static final Type<EditorRequest> TYPE = new Type<>(Identifier.parse("astraplus:editor_request"));
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, EditorRequest> CODEC = StreamCodec.of(
|
||||
(buffer, request) -> buffer.writeUtf(request.json, LIMIT),
|
||||
buffer -> new EditorRequest(buffer.readUtf(LIMIT)));
|
||||
|
||||
@Override public Type<EditorRequest> type() { return TYPE; }
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package online.astradev.plus.editor.network;
|
||||
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
public record EditorResponse(String json) implements CustomPacketPayload {
|
||||
public static final int LIMIT = 262144;
|
||||
public static final Type<EditorResponse> TYPE = new Type<>(Identifier.parse("astraplus:editor_response"));
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, EditorResponse> CODEC = StreamCodec.of(
|
||||
(buffer, response) -> buffer.writeUtf(response.json, LIMIT),
|
||||
buffer -> new EditorResponse(buffer.readUtf(LIMIT)));
|
||||
|
||||
@Override public Type<EditorResponse> type() { return TYPE; }
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.minecraft.client.Minecraft;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.ObjectSelectionList;
|
||||
import net.minecraft.client.input.MouseButtonEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public final class ChoiceList extends ObjectSelectionList<ChoiceList.Row> {
|
||||
private final Consumer<String> selected;
|
||||
|
||||
public ChoiceList(Minecraft minecraft, int x, int y, int width, int height, Consumer<String> selected) {
|
||||
super(minecraft, width, height, y, 26);
|
||||
setX(x);
|
||||
this.selected = selected;
|
||||
}
|
||||
|
||||
public void values(List<String> values) {
|
||||
clearEntries();
|
||||
values.forEach(value -> addEntry(new Row(value)));
|
||||
}
|
||||
|
||||
@Override public int getRowWidth() { return width - 16; }
|
||||
|
||||
public final class Row extends ObjectSelectionList.Entry<Row> {
|
||||
private final String value;
|
||||
|
||||
private Row(String value) { this.value = value; }
|
||||
|
||||
@Override public Component getNarration() { return Component.literal(value); }
|
||||
|
||||
@Override public void extractContent(GuiGraphicsExtractor graphics, int mouseX, int mouseY, boolean hovered, float a) {
|
||||
if (hovered) graphics.fill(getX(), getY(), getX() + getWidth(), getY() + getHeight(), 0x80365962);
|
||||
graphics.text(minecraft.font, minecraft.font.plainSubstrByWidth(value, getContentWidth()),
|
||||
getContentX() + 3, getContentY() + 6, 0xFFE4EBED);
|
||||
}
|
||||
|
||||
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||
if (event.button() != 0) return false;
|
||||
setSelected(this);
|
||||
selected.accept(value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
public final class ChoiceScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final List<String> values;
|
||||
private final Consumer<String> selected;
|
||||
|
||||
public ChoiceScreen(Screen parent, String title, List<String> values, Consumer<String> selected) {
|
||||
super(title);
|
||||
this.parent = parent;
|
||||
this.values = values;
|
||||
this.selected = selected;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 65, width - 24, Math.max(30, height - 135), value -> {
|
||||
selected.accept(value);
|
||||
minecraft.gui.setScreen(parent);
|
||||
}));
|
||||
var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск")));
|
||||
search.setHint(Component.literal("Поиск по идентификатору"));
|
||||
search.setMaxLength(256);
|
||||
search.setResponder(query -> list.values(values.stream()
|
||||
.filter(value -> value.toLowerCase(Locale.ROOT).contains(query.toLowerCase(Locale.ROOT))).toList()));
|
||||
list.values(values);
|
||||
button("Назад", 12, height - 27, 100, this::onClose);
|
||||
if (values.isEmpty()) status("Каталог пуст. Проверьте ответ сервера.", true);
|
||||
setInitialFocus(search);
|
||||
}
|
||||
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
|
||||
public final class ComponentListScreen extends EditorScreen {
|
||||
private static final Set<String> RESERVED = Set.of("minecraft:custom_data", "minecraft:item_model", "minecraft:item_name",
|
||||
"minecraft:block_state", "minecraft:block_entity_data");
|
||||
private final ContentEditorScreen parent;
|
||||
private final ContentDraft draft;
|
||||
private final EditorCatalog catalog;
|
||||
|
||||
public ComponentListScreen(ContentEditorScreen parent, ContentDraft draft, EditorCatalog catalog) {
|
||||
super("AstraPlus: компоненты предмета");
|
||||
this.parent = parent;
|
||||
this.draft = draft;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var components = draft.get("components");
|
||||
var names = new LinkedHashSet<String>();
|
||||
if (components.isJsonObject()) components.getAsJsonObject().keySet().stream().sorted()
|
||||
.forEach(key -> names.add(key.startsWith("!") ? key.substring(1) : key));
|
||||
var list = addRenderableWidget(new ChoiceList(minecraft, 12, 38, width - 24, Math.max(30, height - 118), this::open));
|
||||
list.values(names.stream().toList());
|
||||
button("Добавить компонент", 12, height - 27, Math.min(170, width / 2), () -> {
|
||||
List<String> available = catalog.values("components").stream().filter(id -> !RESERVED.contains(id)).toList();
|
||||
minecraft.gui.setScreen(new ChoiceScreen(this, "Выберите компонент", available, this::scheduleOpen));
|
||||
});
|
||||
button("Назад", width - 102, height - 27, 90, this::onClose);
|
||||
status("Выберите переопределение. Сложные свойства редактируются отдельно в JSON; остальные поля сохраняются.", false);
|
||||
}
|
||||
|
||||
private void scheduleOpen(String id) {
|
||||
// ChoiceScreen restores this screen after its callback, so open the value editor on the next tick.
|
||||
selected = id;
|
||||
}
|
||||
|
||||
private String selected;
|
||||
|
||||
@Override public void tick() {
|
||||
if (selected != null) {
|
||||
String id = selected;
|
||||
selected = null;
|
||||
open(id);
|
||||
}
|
||||
}
|
||||
|
||||
private void open(String id) { minecraft.gui.setScreen(new ComponentValueScreen(this, parent, draft, id)); }
|
||||
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.google.gson.JsonParser;
|
||||
import net.minecraft.client.gui.components.MultiLineEditBox;
|
||||
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.form.ComponentExamples;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
|
||||
public final class ComponentValueScreen extends EditorScreen {
|
||||
private final ComponentListScreen parent;
|
||||
private final ContentEditorScreen editor;
|
||||
private final ContentDraft draft;
|
||||
private final String id;
|
||||
private final String initial;
|
||||
private String value;
|
||||
|
||||
public ComponentValueScreen(ComponentListScreen parent, ContentEditorScreen editor, ContentDraft draft, String id) {
|
||||
super(id);
|
||||
this.parent = parent;
|
||||
this.editor = editor;
|
||||
this.draft = draft;
|
||||
this.id = id;
|
||||
var component = draft.get("components", id);
|
||||
initial = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(
|
||||
component.isJsonNull() ? JsonParser.parseString(ComponentExamples.value(id)) : component);
|
||||
value = initial;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var input = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(39).setShowDecorations(false)
|
||||
.setPlaceholder(Component.literal("Значение компонента в формате JSON"))
|
||||
.build(font, width - 24, Math.max(30, height - 139), Component.literal("JSON компонента")));
|
||||
input.setCharacterLimit(Math.max(8192, value.length()));
|
||||
input.setValue(value);
|
||||
input.setValueListener(text -> value = text);
|
||||
int part = (width - 32) / 3;
|
||||
button("Наследовать", 12, height - 94, part, "Удалить только переопределение; вернуть свойство ванильной основы.",
|
||||
() -> remove(false));
|
||||
button("Убрать свойство", 16 + part, height - 94, part, "Убрать этот компонент даже у ванильной основы (!component).",
|
||||
() -> remove(true));
|
||||
button("Пример", 20 + part * 2, height - 94, part, () -> {
|
||||
value = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
|
||||
.toJson(JsonParser.parseString(ComponentExamples.value(id)));
|
||||
rebuildWidgets();
|
||||
});
|
||||
button("Назад", 12, height - 27, 100, this::onClose);
|
||||
button("В черновик", width - 142, height - 27, 130, this::apply);
|
||||
status("Значение одного компонента. Проверка Minecraft выполняется при сохранении определения на сервере.", false);
|
||||
}
|
||||
|
||||
private void apply() {
|
||||
try {
|
||||
var parsed = JsonParser.parseString(value);
|
||||
if (parsed.isJsonNull()) throw new IllegalArgumentException("Значение null не является компонентом.");
|
||||
draft.component(parsed, id);
|
||||
editor.componentChanged();
|
||||
minecraft.gui.setScreen(parent);
|
||||
} catch (RuntimeException error) {
|
||||
status("Некорректный JSON: " + error.getMessage(), true);
|
||||
}
|
||||
}
|
||||
|
||||
private void remove(boolean base) {
|
||||
draft.removeComponent(id, base);
|
||||
editor.componentChanged();
|
||||
minecraft.gui.setScreen(parent);
|
||||
}
|
||||
|
||||
@Override public void onClose() {
|
||||
if (!value.equals(initial)) minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||
Component.literal("Закрыть компонент?"), Component.literal("Изменения JSON ещё не перенесены в черновик определения.")));
|
||||
else minecraft.gui.setScreen(parent);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
public final class ContentBrowserScreen extends EditorScreen {
|
||||
private final EditorConnection connection;
|
||||
private final EditorCatalog catalog = new EditorCatalog();
|
||||
private final Map<String, String> rows = new LinkedHashMap<>();
|
||||
private ChoiceList list;
|
||||
private int page;
|
||||
private int pages = 1;
|
||||
private String query = "";
|
||||
private int searchDelay;
|
||||
private int requestGeneration;
|
||||
private boolean first = true;
|
||||
|
||||
public ContentBrowserScreen(EditorConnection connection) {
|
||||
super("AstraPlus: предметы и блоки");
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var search = addRenderableWidget(new EditBox(font, 12, 38, width - 24, 20, Component.literal("Поиск")));
|
||||
search.setMaxLength(256);
|
||||
search.setHint(Component.literal("Найти по имени или namespace:id"));
|
||||
search.setValue(query);
|
||||
search.setResponder(value -> { query = value; searchDelay = 6; page = 0; });
|
||||
list = addRenderableWidget(new ChoiceList(minecraft, 12, 64, width - 24, Math.max(25, height - 165), this::load));
|
||||
list.values(rows.keySet().stream().toList());
|
||||
int row = height - 94;
|
||||
int part = Math.max(50, (width - 48) / 4);
|
||||
button("+ Предмет", 12, row, part, () -> create(false));
|
||||
button("+ Блок", 20 + part, row, part, () -> create(true));
|
||||
button("Обновить", 28 + part * 2, row, part, this::refresh);
|
||||
button("Ресурспак", 36 + part * 3, row, part,
|
||||
"Собрать ресурспак и экспортировать его в AstraPacks, если интеграция включена.", () -> {
|
||||
status("Запрашивается сборка ресурспака…", false);
|
||||
connection.request("build", new JsonObject(), this::reply);
|
||||
});
|
||||
button("←", 12, height - 27, 30, () -> { if (page > 0) { page--; refresh(); } });
|
||||
button("→", 48, height - 27, 30, () -> { if (page + 1 < pages) { page++; refresh(); } });
|
||||
button("Закрыть", width - 102, height - 27, 90, this::onClose);
|
||||
if (first) {
|
||||
first = false;
|
||||
connection.request("catalog", new JsonObject(), response -> {
|
||||
if (EditorConnection.success(response)) catalog.update(response);
|
||||
else reply(response);
|
||||
});
|
||||
}
|
||||
refresh();
|
||||
}
|
||||
|
||||
@Override public void tick() {
|
||||
if (searchDelay > 0 && --searchDelay == 0) refresh();
|
||||
}
|
||||
|
||||
private void refresh() {
|
||||
int generation = ++requestGeneration;
|
||||
var request = new JsonObject();
|
||||
request.addProperty("page", page);
|
||||
request.addProperty("query", query);
|
||||
status("Загрузка…", false);
|
||||
connection.request("list", request, response -> {
|
||||
if (generation != requestGeneration) return;
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
rows.clear();
|
||||
if (response.has("entries")) for (var value : response.getAsJsonArray("entries")) {
|
||||
var entry = value.getAsJsonObject();
|
||||
String id = entry.get("id").getAsString();
|
||||
String kind = entry.get("kind").getAsString().toLowerCase(Locale.ROOT).startsWith("block") ? "Блок" : "Предмет";
|
||||
rows.put(kind + ": " + entry.get("name").getAsString() + " [" + id + "]", id);
|
||||
}
|
||||
page = response.has("page") ? response.get("page").getAsInt() : page;
|
||||
pages = Math.max(1, response.has("pages") ? response.get("pages").getAsInt() : 1);
|
||||
list.values(rows.keySet().stream().toList());
|
||||
status("Страница " + (page + 1) + " / " + pages + ": Выберите определение для редактирования.", false);
|
||||
});
|
||||
}
|
||||
|
||||
private void load(String label) {
|
||||
String id = rows.get(label);
|
||||
if (id == null) return;
|
||||
var request = new JsonObject(); request.addProperty("id", id);
|
||||
status("Открывается " + id + "…", false);
|
||||
connection.request("get", request, response -> {
|
||||
if (!EditorConnection.success(response)) { reply(response); return; }
|
||||
if (minecraft.gui.screen() != this) return;
|
||||
var draft = new ContentDraft(response.getAsJsonObject("document"), response.get("revision").getAsString());
|
||||
minecraft.gui.setScreen(new ContentEditorScreen(this, connection, catalog, draft));
|
||||
});
|
||||
}
|
||||
|
||||
private void create(boolean block) {
|
||||
minecraft.gui.setScreen(new ContentEditorScreen(this, connection, catalog, ContentDraft.create(block)));
|
||||
}
|
||||
|
||||
private void reply(JsonObject response) { status(EditorConnection.message(response), !EditorConnection.success(response)); }
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.google.gson.JsonObject;
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.AbstractWidget;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.ConfirmScreen;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
import online.astradev.plus.editor.form.ContentFields;
|
||||
import online.astradev.plus.editor.form.FormField;
|
||||
import online.astradev.plus.editor.network.EditorConnection;
|
||||
|
||||
public final class ContentEditorScreen extends EditorScreen {
|
||||
private final ContentBrowserScreen parent;
|
||||
private final EditorConnection connection;
|
||||
private final EditorCatalog catalog;
|
||||
private final ContentDraft draft;
|
||||
private final Map<String, String> typed = new LinkedHashMap<>();
|
||||
private final Map<String, String> errors = new LinkedHashMap<>();
|
||||
private final List<Label> labels = new ArrayList<>();
|
||||
private int section;
|
||||
private int page;
|
||||
private boolean saving;
|
||||
private Button save;
|
||||
|
||||
public ContentEditorScreen(ContentBrowserScreen parent, EditorConnection connection, EditorCatalog catalog, ContentDraft draft) {
|
||||
super(draft.block() ? "AstraPlus: редактор блока" : "AstraPlus: редактор предмета");
|
||||
this.parent = parent;
|
||||
this.connection = connection;
|
||||
this.catalog = catalog;
|
||||
this.draft = draft;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
labels.clear();
|
||||
int tabWidth = (width - 32) / 3;
|
||||
button("Основное", 12, 38, tabWidth, () -> section(0));
|
||||
button("Свойства", 16 + tabWidth, 38, tabWidth, () -> section(1));
|
||||
if (draft.block()) button("Блок", 20 + tabWidth * 2, 38, tabWidth, () -> section(2));
|
||||
else button("Зачарования", 20 + tabWidth * 2, 38, tabWidth, this::enchantments);
|
||||
int top = 76;
|
||||
var fieldSource = new ContentFields(draft, catalog);
|
||||
var fields = switch (section) { case 1 -> fieldSource.properties(); case 2 -> fieldSource.block(); default -> fieldSource.basic(); };
|
||||
int columns = width >= 560 ? 2 : 1;
|
||||
int rowCount = Math.max(1, (height - top - 110) / 42);
|
||||
int perPage = columns * rowCount;
|
||||
int pages = Math.max(1, (fields.size() + perPage - 1) / perPage);
|
||||
page = Math.min(page, pages - 1);
|
||||
int fieldWidth = (width - 24 - (columns - 1) * 14) / columns;
|
||||
for (int index = page * perPage; index < Math.min(fields.size(), (page + 1) * perPage); index++) {
|
||||
int relative = index - page * perPage;
|
||||
field(fields.get(index), 12 + (relative % columns) * (fieldWidth + 14), top + (relative / columns) * 42, fieldWidth);
|
||||
}
|
||||
int bottom = height - 94;
|
||||
button("←", 12, bottom, 26, () -> { if (page > 0) { page--; rebuildWidgets(); } });
|
||||
button("→", 42, bottom, 26, () -> { if (page + 1 < pages) { page++; rebuildWidgets(); } });
|
||||
labels.add(new Label("Поля " + (page + 1) + "/" + pages, 75, bottom + 6));
|
||||
button("Компоненты", width - 132, bottom, 120, () -> minecraft.gui.setScreen(new ComponentListScreen(this, draft, catalog)));
|
||||
if (draft.block() && width >= 420) button("Зачарования", width - 262, bottom, 122, this::enchantments);
|
||||
int size = (width - 40) / 3;
|
||||
button("Назад", 12, height - 27, size, this::onClose);
|
||||
save = button("Сохранить", 20 + size, height - 27, size, "Проверить и применить определение на сервере.", this::save);
|
||||
save.active = !saving;
|
||||
var give = button("Выдать образец", 28 + size * 2, height - 27, size,
|
||||
"Выдать сохранённую серверную версию. Несохранённый черновик не применяется.", this::give);
|
||||
give.active = !draft.fresh() && !saving;
|
||||
if (saving) for (var child : children()) if (child instanceof AbstractWidget widget) widget.active = false;
|
||||
if (status.isBlank()) status(draft.fresh() ? (draft.block() ? "Новый блок. Слот будет назначен автоматически." : "Новый предмет. Настройте свойства и сохраните определение.")
|
||||
: draft.id() + ": Изменения сохраняются только кнопкой «Сохранить».", false);
|
||||
}
|
||||
|
||||
private void field(FormField field, int x, int y, int width) {
|
||||
labels.add(new Label(field.label(), x, y - 11));
|
||||
String value = typed.getOrDefault(field.key(), field.read().get());
|
||||
if (field.cycle()) {
|
||||
button(value, x, y, width, field.hint(), () -> {
|
||||
int current = field.choices().indexOf(field.read().get());
|
||||
edit(field, field.choices().get((current + 1) % field.choices().size()));
|
||||
rebuildWidgets();
|
||||
});
|
||||
return;
|
||||
}
|
||||
boolean picker = !field.choices().isEmpty();
|
||||
var input = addRenderableWidget(new EditBox(font, x, y, width - (picker ? 30 : 0), 20, Component.literal(field.label())));
|
||||
input.setMaxLength(Math.max(value.length(), field.key().equals("name") ? 256 : 1024));
|
||||
input.setValue(value);
|
||||
input.setTooltip(Tooltip.create(Component.literal(field.hint())));
|
||||
input.setResponder(text -> edit(field, text));
|
||||
if (picker) button("…", x + width - 26, y, 26, () -> minecraft.gui.setScreen(new ChoiceScreen(this,
|
||||
field.label(), field.choices(), selected -> { edit(field, selected); })));
|
||||
}
|
||||
|
||||
private void edit(FormField field, String value) {
|
||||
typed.put(field.key(), value);
|
||||
try {
|
||||
field.write().accept(value);
|
||||
typed.remove(field.key());
|
||||
errors.remove(field.key());
|
||||
status("Черновик изменён. Сохраните, чтобы применить.", false);
|
||||
} catch (IllegalArgumentException error) {
|
||||
errors.put(field.key(), field.label() + ": " + error.getMessage());
|
||||
status(errors.get(field.key()), true);
|
||||
}
|
||||
}
|
||||
|
||||
private void section(int section) {
|
||||
this.section = section;
|
||||
page = 0;
|
||||
rebuildWidgets();
|
||||
}
|
||||
|
||||
private void enchantments() { minecraft.gui.setScreen(new EnchantmentScreen(this, draft, catalog)); }
|
||||
|
||||
private void save() {
|
||||
if (saving) return;
|
||||
if (!errors.isEmpty()) { status(errors.values().iterator().next(), true); return; }
|
||||
saving = true;
|
||||
rebuildWidgets();
|
||||
var request = new JsonObject();
|
||||
request.addProperty("id", draft.id());
|
||||
request.addProperty("revision", draft.revision());
|
||||
request.add("document", draft.document());
|
||||
status("Проверка и сохранение на сервере…", false);
|
||||
connection.request("save", request, response -> {
|
||||
saving = false;
|
||||
if (EditorConnection.success(response)) {
|
||||
draft.saved(response.has("document") ? response.getAsJsonObject("document") : request.getAsJsonObject("document"),
|
||||
response.get("revision").getAsString());
|
||||
typed.clear();
|
||||
status(EditorConnection.message(response) + " Для новой графики соберите ресурспак в списке определений.", false);
|
||||
} else status(EditorConnection.message(response), true);
|
||||
if (minecraft.gui.screen() == this) rebuildWidgets();
|
||||
});
|
||||
}
|
||||
|
||||
private void give() {
|
||||
var request = new JsonObject(); request.addProperty("id", draft.id());
|
||||
connection.request("give", request, response -> status(EditorConnection.message(response), !EditorConnection.success(response)));
|
||||
}
|
||||
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||
for (var label : labels) graphics.text(font, label.value, label.x, label.y, 0xFFB3C8D1);
|
||||
}
|
||||
|
||||
@Override public void onClose() {
|
||||
if (saving) { status("Дождитесь ответа на сохранение.", true); return; }
|
||||
if (draft.dirty() || !errors.isEmpty()) {
|
||||
minecraft.gui.setScreen(new ConfirmScreen(discard -> minecraft.gui.setScreen(discard ? parent : this),
|
||||
Component.literal("Закрыть без сохранения?"), Component.literal("Локальные изменения этого определения будут потеряны."),
|
||||
Component.literal("Не сохранять"), Component.literal("Продолжить")));
|
||||
} else minecraft.gui.setScreen(parent);
|
||||
}
|
||||
|
||||
public void componentChanged() {
|
||||
status("Компоненты черновика изменены. Сохраните определение, чтобы применить.", false);
|
||||
}
|
||||
|
||||
private record Label(String value, int x, int y) {}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.Button;
|
||||
import net.minecraft.client.gui.components.Tooltip;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.input.MouseButtonEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
|
||||
/** Shared spacing and status rendering; concrete screens own their interactions. */
|
||||
public abstract class EditorScreen extends Screen {
|
||||
protected String status = "";
|
||||
protected boolean failed;
|
||||
private boolean extendedStatus;
|
||||
|
||||
protected EditorScreen(String title) { super(Component.literal(title)); }
|
||||
|
||||
protected Button button(String text, int x, int y, int width, Runnable action) {
|
||||
return addRenderableWidget(Button.builder(Component.literal(text), button -> action.run())
|
||||
.bounds(x, y, width, 20).build());
|
||||
}
|
||||
|
||||
protected Button button(String text, int x, int y, int width, String hint, Runnable action) {
|
||||
var button = button(text, x, y, width, action);
|
||||
button.setTooltip(Tooltip.create(Component.literal(hint)));
|
||||
return button;
|
||||
}
|
||||
|
||||
protected void status(String message, boolean failed) {
|
||||
this.status = message;
|
||||
this.failed = failed;
|
||||
}
|
||||
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||
graphics.fill(0, 0, width, height, 0xEC121920);
|
||||
graphics.fill(0, 0, width, 31, 0xFF1D2D37);
|
||||
graphics.text(font, title, 12, 11, 0xFFE0F4F4);
|
||||
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||
extendedStatus = false;
|
||||
if (!status.isBlank()) {
|
||||
var lines = font.split(Component.literal(status), width - 24);
|
||||
extendedStatus = lines.size() > 2;
|
||||
for (int index = 0; index < Math.min(2, lines.size()); index++)
|
||||
graphics.text(font, lines.get(index), 12, height - 57 + index * 10, failed ? 0xFFFFA3A3 : 0xFF9DE5CE);
|
||||
if (extendedStatus) {
|
||||
graphics.text(font, "[Открыть сообщение полностью…]", 12, height - 36, 0xFFB3C8D1);
|
||||
if (mouseX >= 12 && mouseX < width - 12 && mouseY >= height - 58 && mouseY < height - 27)
|
||||
graphics.setTooltipForNextFrame(font, Component.literal("Нажмите, чтобы прочитать и скопировать полный текст."), mouseX, mouseY);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override public boolean mouseClicked(MouseButtonEvent event, boolean doubleClick) {
|
||||
if (extendedStatus && event.button() == 0 && event.x() >= 12 && event.x() < width - 12
|
||||
&& event.y() >= height - 58 && event.y() < height - 27) {
|
||||
minecraft.gui.setScreen(new MessageScreen(this, status));
|
||||
return true;
|
||||
}
|
||||
return super.mouseClicked(event, doubleClick);
|
||||
}
|
||||
|
||||
@Override public boolean isPauseScreen() { return false; }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import net.minecraft.client.gui.GuiGraphicsExtractor;
|
||||
import net.minecraft.client.gui.components.EditBox;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import online.astradev.plus.editor.client.EditorCatalog;
|
||||
import online.astradev.plus.editor.form.ContentDraft;
|
||||
|
||||
public final class EnchantmentScreen extends EditorScreen {
|
||||
private final ContentEditorScreen parent;
|
||||
private final ContentDraft draft;
|
||||
private final EditorCatalog catalog;
|
||||
private String selected = "minecraft:unbreaking";
|
||||
private String partner = "minecraft:mending";
|
||||
private String levelError = "";
|
||||
private String levelText;
|
||||
private final List<Label> labels = new ArrayList<>();
|
||||
|
||||
public EnchantmentScreen(ContentEditorScreen parent, ContentDraft draft, EditorCatalog catalog) {
|
||||
super("AstraPlus: правила зачарований");
|
||||
this.parent = parent;
|
||||
this.draft = draft;
|
||||
this.catalog = catalog;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
labels.clear();
|
||||
int contentWidth = width - 24;
|
||||
int half = (contentWidth - 8) / 2;
|
||||
button(draft.whitelist() ? "Режим: только выбранные" : "Режим: правила основы", 12, 39, contentWidth,
|
||||
"Белый список разрешает только добавленные в него зачарования. Ванильные ограничения сохраняются.", () -> {
|
||||
draft.whitelist(!draft.whitelist());
|
||||
rebuildWidgets();
|
||||
});
|
||||
button(shortId(selected), 12, 68, half, "Выберите зачарование для настройки.", () -> pick(false));
|
||||
button(draft.enabled(selected) ? "Разрешено правилами мода" : "Запрещено правилами мода", 20 + half, 68, half,
|
||||
"Разрешение здесь дополнительно ограничивается ванильной совместимостью и типом предмета.", () -> {
|
||||
draft.enchantment(selected, !draft.enabled(selected));
|
||||
rebuildWidgets();
|
||||
});
|
||||
labels.add(new Label("Максимальный уровень (пусто — ванильный)", 12, 100));
|
||||
var level = addRenderableWidget(new EditBox(font, 12, 112, contentWidth, 20, Component.literal("Максимальный уровень")));
|
||||
level.setMaxLength(5);
|
||||
level.setValue(levelText == null ? draft.text("", "enchantments", "maxLevels", selected) : levelText);
|
||||
level.setResponder(value -> {
|
||||
levelText = value;
|
||||
try {
|
||||
draft.number(value, true, 1, 255, "enchantments", "maxLevels", selected);
|
||||
levelError = "";
|
||||
status("Правило изменено в черновике.", false);
|
||||
} catch (IllegalArgumentException error) {
|
||||
levelError = error.getMessage(); status(levelError, true);
|
||||
}
|
||||
});
|
||||
int pairY = height >= 300 ? 158 : 142;
|
||||
button(shortId(partner), 12, pairY, half, "Выберите второе зачарование пары.", () -> pick(true));
|
||||
var conflict = button(draft.conflicts(selected, partner) ? "Пара несовместима" : "Добавить несовместимость", 20 + half, pairY, half,
|
||||
"Дополнительный запрет пары. Ванильные запреты нельзя отменить этим переключателем.", () -> {
|
||||
try {
|
||||
draft.conflict(selected, partner, !draft.conflicts(selected, partner));
|
||||
rebuildWidgets();
|
||||
} catch (IllegalArgumentException error) { status(error.getMessage(), true); }
|
||||
});
|
||||
conflict.active = !selected.equals(partner);
|
||||
if (height >= 300) {
|
||||
String conflicts = catalog.values("enchantments").stream().filter(id -> draft.conflicts(selected, id))
|
||||
.map(EnchantmentScreen::shortId).reduce((first, second) -> first + ", " + second).orElse("нет дополнительных пар");
|
||||
labels.add(new Label(font.plainSubstrByWidth("Конфликты: " + conflicts, width - 24), 12, pairY + 29));
|
||||
}
|
||||
button("Назад к определению", 12, height - 27, Math.min(210, width - 24), this::onClose);
|
||||
if (status.isBlank()) status("Правила дополнительно ограничивают ванильные. Сохраните всё определение после настройки.", false);
|
||||
}
|
||||
|
||||
private void pick(boolean second) {
|
||||
if (!levelError.isBlank()) { status("Исправьте максимальный уровень: " + levelError, true); return; }
|
||||
minecraft.gui.setScreen(new ChoiceScreen(this, second ? "Второе зачарование пары" : "Выберите зачарование", catalog.values("enchantments"), id -> {
|
||||
if (second) partner = id;
|
||||
else { selected = id; levelText = null; }
|
||||
}));
|
||||
}
|
||||
|
||||
@Override public void extractRenderState(GuiGraphicsExtractor graphics, int mouseX, int mouseY, float a) {
|
||||
super.extractRenderState(graphics, mouseX, mouseY, a);
|
||||
for (var label : labels) graphics.text(font, label.value, label.x, label.y, 0xFFB3C8D1);
|
||||
}
|
||||
|
||||
@Override public void onClose() {
|
||||
if (!levelError.isBlank()) { status("Исправьте максимальный уровень: " + levelError, true); return; }
|
||||
minecraft.gui.setScreen(parent);
|
||||
}
|
||||
|
||||
private static String shortId(String id) { return id.startsWith("minecraft:") ? id.substring(10) : id; }
|
||||
private record Label(String value, int x, int y) {}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package online.astradev.plus.editor.screen;
|
||||
|
||||
import net.minecraft.client.gui.components.MultiLineEditBox;
|
||||
import net.minecraft.client.gui.screens.Screen;
|
||||
import net.minecraft.client.input.CharacterEvent;
|
||||
import net.minecraft.client.input.KeyEvent;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import org.lwjgl.glfw.GLFW;
|
||||
|
||||
/** Scrollable full validation message; copying and navigation are available without editing the text. */
|
||||
public final class MessageScreen extends EditorScreen {
|
||||
private final Screen parent;
|
||||
private final String message;
|
||||
|
||||
public MessageScreen(Screen parent, String message) {
|
||||
super("AstraPlus: полное сообщение");
|
||||
this.parent = parent;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
@Override protected void init() {
|
||||
var text = addRenderableWidget(MultiLineEditBox.builder().setX(12).setY(39).setShowDecorations(false)
|
||||
.build(font, width - 24, Math.max(30, height - 110), Component.literal("Текст сообщения")));
|
||||
text.setCharacterLimit(Math.max(1, message.length()));
|
||||
text.setValue(message);
|
||||
setInitialFocus(text);
|
||||
button("Назад", 12, height - 27, 100, this::onClose);
|
||||
status("Прокручивайте текст. Ctrl+A и Ctrl+C — скопировать сообщение.", false);
|
||||
}
|
||||
|
||||
@Override public boolean charTyped(CharacterEvent event) { return false; }
|
||||
|
||||
@Override public boolean keyPressed(KeyEvent event) {
|
||||
return switch (event.key()) {
|
||||
case GLFW.GLFW_KEY_ESCAPE, GLFW.GLFW_KEY_TAB, GLFW.GLFW_KEY_LEFT, GLFW.GLFW_KEY_RIGHT,
|
||||
GLFW.GLFW_KEY_UP, GLFW.GLFW_KEY_DOWN, GLFW.GLFW_KEY_HOME, GLFW.GLFW_KEY_END,
|
||||
GLFW.GLFW_KEY_PAGE_UP, GLFW.GLFW_KEY_PAGE_DOWN, GLFW.GLFW_KEY_A, GLFW.GLFW_KEY_C -> super.keyPressed(event);
|
||||
default -> false;
|
||||
};
|
||||
}
|
||||
|
||||
@Override public void onClose() { minecraft.gui.setScreen(parent); }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
modLoader="javafml"
|
||||
loaderVersion="[11,)"
|
||||
license="All Rights Reserved"
|
||||
[[mods]]
|
||||
modId="astrapluseditor"
|
||||
version="${version}"
|
||||
displayName="AstraPlus Editor"
|
||||
description='''Optional administration client for AstraPlus. Edit server content through validated, permission-checked requests.'''
|
||||
[[dependencies.astrapluseditor]]
|
||||
modId="neoforge"
|
||||
type="required"
|
||||
versionRange="[26.2.0.79,26.3)"
|
||||
side="CLIENT"
|
||||
[[dependencies.astrapluseditor]]
|
||||
modId="minecraft"
|
||||
type="required"
|
||||
versionRange="[26.2,26.3)"
|
||||
side="CLIENT"
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"key.astrapluseditor.open": "Open AstraPlus Editor"
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"key.astrapluseditor.open": "Открыть редактор AstraPlus"
|
||||
}
|
||||
Reference in New Issue
Block a user