Files
codecraft/src/main/java/com/aranroig/Codecraft.java
Aran Roig b7e416d335
Some checks failed
build / build (push) Failing after 52s
Mes coses divertides
2026-10-08 01:54:02 +02:00

200 lines
11 KiB
Java

package com.aranroig;
import com.aranroig.collab.DocumentManager;
import com.aranroig.editor.EditorFile;
import com.aranroig.editor.ProjectPath;
import com.aranroig.listeners.ScriptRuntime;
import com.aranroig.listeners.ScriptRuntimeManager;
import com.aranroig.payloads.ClientboundDocumentEditPayload;
import com.aranroig.payloads.ClientboundDocumentStatePayload;
import com.aranroig.payloads.ClientboundEditAckPayload;
import com.aranroig.payloads.ClientboundPresencePayload;
import com.aranroig.payloads.ClientboundProjectFilesPayload;
import com.aranroig.payloads.ClientboundRenameFilePayload;
import com.aranroig.payloads.ClientboundSaveCodePayload;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import com.aranroig.payloads.ServerboundCloseEditorPayload;
import com.aranroig.payloads.ServerboundCloseShellPayload;
import com.aranroig.payloads.ServerboundCursorPayload;
import com.aranroig.payloads.ServerboundEditPayload;
import com.aranroig.payloads.ServerboundOpenDocumentPayload;
import com.aranroig.payloads.ServerboundRenameFilePayload;
import com.aranroig.payloads.ServerboundRequestProjectPayload;
import com.aranroig.payloads.ServerboundRunCodePayload;
import com.aranroig.payloads.ServerboundSaveCodePayload;
import com.aranroig.payloads.ServerboundShellInputPayload;
import com.aranroig.payloads.ServerboundShellResizePayload;
import com.aranroig.payloads.ServerboundSpawnShellPayload;
import com.aranroig.project.ProjectStore;
import com.aranroig.shell.ShellManager;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class Codecraft implements ModInitializer {
public static final String MOD_ID = "codecraft";
// This logger is used to write text to the console and the log file.
// It is considered best practice to use your mod id as the logger's name.
// That way, it's clear which mod wrote info, warnings, and errors.
public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);
@Override
public void onInitialize() {
// This code runs as soon as Minecraft is in a mod-load-ready state.
// However, some things (like resources) may still be uninitialized.
// Proceed with mild caution.
LOGGER.info("Hello Fabric world!");
PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRunCodePayload.TYPE, ServerboundRunCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRequestProjectPayload.TYPE, ServerboundRequestProjectPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundOpenDocumentPayload.TYPE, ServerboundOpenDocumentPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundCloseEditorPayload.TYPE, ServerboundCloseEditorPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundEditPayload.TYPE, ServerboundEditPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundCursorPayload.TYPE, ServerboundCursorPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRenameFilePayload.TYPE, ServerboundRenameFilePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundSpawnShellPayload.TYPE, ServerboundSpawnShellPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundShellInputPayload.TYPE, ServerboundShellInputPayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundShellResizePayload.TYPE, ServerboundShellResizePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundCloseShellPayload.TYPE, ServerboundCloseShellPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundSaveCodePayload.TYPE, ClientboundSaveCodePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundProjectFilesPayload.TYPE, ClientboundProjectFilesPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundDocumentStatePayload.TYPE, ClientboundDocumentStatePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundDocumentEditPayload.TYPE, ClientboundDocumentEditPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundEditAckPayload.TYPE, ClientboundEditAckPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundPresencePayload.TYPE, ClientboundPresencePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundRenameFilePayload.TYPE, ClientboundRenameFilePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundShellOutputPayload.TYPE, ClientboundShellOutputPayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundShellClosedPayload.TYPE, ClientboundShellClosedPayload.CODEC);
// Bridge game activity (item use, block break, chat, join/leave, tick) to
// the Lua listeners scripts register. Registered once; dispatching to the
// currently running script happens per event.
ScriptRuntimeManager.install();
// The project now lives as plain .lua files under config/codecraft:
// move a world's scripts out of its saved data the first time a
// server starts, and drain the queued keystroke writes to disk before
// it stops.
ProjectStore.install();
// Drop players from their live editing sessions when they leave, and
// throw the cached documents away when the world stops.
DocumentManager.install();
// Same for the shells the terminal pane spawns: nobody leaks when the
// player disconnects or the server stops.
ShellManager.install();
ServerPlayNetworking.registerGlobalReceiver(ServerboundRequestProjectPayload.TYPE, (payload, context) -> {
// Read fresh from disk every time the editor opens: scripts edited
// with an external editor in the meantime are in here too.
List<EditorFile> files = ProjectStore.loadAll();
// Seed a default entrypoint so the client always has at least one file.
// Names carry no extension: the sidebar shows them as they are.
if(files.isEmpty()) {
ProjectStore.write(ProjectPath.ENTRYPOINT, "");
files = List.of(new EditorFile(ProjectPath.ENTRYPOINT, ""));
}
ServerPlayNetworking.send(context.player(), new ClientboundProjectFilesPayload(List.copyOf(files)));
});
ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> {
EditorFile editorFile = payload.data();
// The live document is what the other editors are looking at, so the
// save goes through it: the new text reaches them as one edit they
// can merge, instead of clobbering whatever they typed meanwhile —
// and it is from there that the rest of them hear the file exists.
DocumentManager.replaceDocument(context.player(), editorFile.getName(), editorFile.getText());
LOGGER.info("Successfully saved file {}", editorFile.getName());
});
// Renaming a file moves it in the saved project and its live document,
// and the other editors' lists follow.
ServerPlayNetworking.registerGlobalReceiver(ServerboundRenameFilePayload.TYPE, (payload, context) ->
DocumentManager.renameFile(context.player(), payload.oldName(), payload.newName()));
// ── Live editing ────────────────────────────────────────────────────
// A player opening the editor, or switching file, joins that document's
// session and gets its authoritative contents back.
ServerPlayNetworking.registerGlobalReceiver(ServerboundOpenDocumentPayload.TYPE, (payload, context) ->
DocumentManager.openDocument(context.player(), payload.file()));
// One keystroke's worth of changes, rebased and passed to the others.
ServerPlayNetworking.registerGlobalReceiver(ServerboundEditPayload.TYPE, (payload, context) ->
DocumentManager.applyEdit(context.player(), payload.file(), payload.baseVersion(), payload.edit()));
// Where the player's caret is, for the other editors to draw.
ServerPlayNetworking.registerGlobalReceiver(ServerboundCursorPayload.TYPE, (payload, context) ->
DocumentManager.updateCursor(context.player(), payload.file(), payload.cursor(), payload.anchor()));
// Closing the editor ends the session; disconnecting does it too.
ServerPlayNetworking.registerGlobalReceiver(ServerboundCloseEditorPayload.TYPE, (payload, context) ->
DocumentManager.closeEditor(context.player()));
// ── The terminal pane ───────────────────────────────────────────────
// The button spawns a bash on this machine, every line typed in the
// pane is a command for it, and closing the pane kills it.
ServerPlayNetworking.registerGlobalReceiver(ServerboundSpawnShellPayload.TYPE, (payload, context) ->
ShellManager.spawn(context.player(), payload.rows(), payload.cols()));
ServerPlayNetworking.registerGlobalReceiver(ServerboundShellInputPayload.TYPE, (payload, context) ->
ShellManager.submit(context.player(), payload.bytes()));
// A resize of the pane moves the pty's window on this side: the shell's
// input is not touched, and full-screen programs are signalled live.
ServerPlayNetworking.registerGlobalReceiver(ServerboundShellResizePayload.TYPE, (payload, context) ->
ShellManager.resize(context.player(), payload.rows(), payload.cols()));
ServerPlayNetworking.registerGlobalReceiver(ServerboundCloseShellPayload.TYPE, (payload, context) ->
ShellManager.close(context.player()));
ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> {
ServerPlayer player = context.player();
String entrypoint = payload.data().getEntrypoint();
LOGGER.info("Running entrypoint {}", entrypoint);
String code = ProjectStore.read(entrypoint);
if(code == null) {
// Worlds seeded while names still carried the extension.
code = ProjectStore.read(entrypoint + ProjectPath.LEGACY_EXTENSION);
}
if(code == null) {
player.sendSystemMessage(Component.literal("§ccodecraft: entrypoint not found: " + entrypoint));
return;
}
// Fresh runtime per run: this drops the listeners the player
// registered last time (reset-on-rerun) and registers print/world/
// events on a brand-new Lua state.
ScriptRuntime runtime = ScriptRuntimeManager.startRun(player);
try {
runtime.run(code);
} catch (Exception e) {
LOGGER.warn("Error running " + entrypoint, e);
player.sendSystemMessage(Component.literal("§ccodecraft error: " + e.getMessage()));
}
});
}
public static Identifier id(String path) {
return Identifier.fromNamespaceAndPath(MOD_ID, path);
}
}