This commit is contained in:
@@ -1,13 +1,32 @@
|
||||
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.wrapper.ChatLogger;
|
||||
import com.aranroig.wrapper.WorldApi;
|
||||
import com.aranroig.payloads.ServerboundShellInputPayload;
|
||||
import com.aranroig.payloads.ServerboundShellResizePayload;
|
||||
import com.aranroig.payloads.ServerboundSpawnShellPayload;
|
||||
import com.aranroig.shell.ShellManager;
|
||||
import net.fabricmc.api.ModInitializer;
|
||||
|
||||
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
|
||||
@@ -19,8 +38,6 @@ import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.luaj.LuaJ;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -42,8 +59,37 @@ public class Codecraft implements ModInitializer {
|
||||
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();
|
||||
|
||||
// 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) -> {
|
||||
MinecraftServer server = context.player().level().getServer();
|
||||
@@ -53,8 +99,9 @@ public class Codecraft implements ModInitializer {
|
||||
List<EditorFile> files = savedData.getEditorFiles();
|
||||
|
||||
// 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()) {
|
||||
files.add(new EditorFile("main.lua", ""));
|
||||
files.add(new EditorFile(ProjectPath.ENTRYPOINT, ""));
|
||||
savedData.setEditorFiles(files);
|
||||
}
|
||||
|
||||
@@ -62,36 +109,56 @@ public class Codecraft implements ModInitializer {
|
||||
});
|
||||
|
||||
ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> {
|
||||
MinecraftServer server = context.player().level().getServer();
|
||||
if(server == null) return;
|
||||
|
||||
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = savedData.getEditorFiles();
|
||||
|
||||
EditorFile editorFile = payload.data();
|
||||
boolean existing = false;
|
||||
for(EditorFile file : files) {
|
||||
if(file.getName().equals(editorFile.getName())) {
|
||||
existing = true;
|
||||
file.setText(editorFile.getText());
|
||||
break;
|
||||
}
|
||||
}
|
||||
if(!existing) {
|
||||
files.add(editorFile);
|
||||
}
|
||||
|
||||
savedData.setEditorFiles(files);
|
||||
// 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());
|
||||
|
||||
// Push the change to every other client so their editors stay in sync.
|
||||
for(ServerPlayer player : server.getPlayerList().getPlayers()) {
|
||||
if(player != context.player()) {
|
||||
ServerPlayNetworking.send(player, new ClientboundSaveCodePayload(new EditorFile(editorFile.getName(), editorFile.getText())));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 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) -> {
|
||||
MinecraftServer server = context.player().level().getServer();
|
||||
if(server == null) return;
|
||||
@@ -104,12 +171,10 @@ public class Codecraft implements ModInitializer {
|
||||
String entrypoint = payload.data().getEntrypoint();
|
||||
LOGGER.info("Running entrypoint {}", entrypoint);
|
||||
|
||||
EditorFile target = null;
|
||||
for(EditorFile file : files) {
|
||||
if(file.getName().equals(entrypoint)) {
|
||||
target = file;
|
||||
break;
|
||||
}
|
||||
EditorFile target = findByName(files, entrypoint);
|
||||
if(target == null) {
|
||||
// Worlds seeded while names still carried the extension.
|
||||
target = findByName(files, entrypoint + ProjectPath.LEGACY_EXTENSION);
|
||||
}
|
||||
|
||||
if(target == null) {
|
||||
@@ -117,12 +182,12 @@ public class Codecraft implements ModInitializer {
|
||||
return;
|
||||
}
|
||||
|
||||
Lua lua = new LuaJ();
|
||||
lua.push(ChatLogger.print(player));
|
||||
lua.setGlobal("print");
|
||||
WorldApi.register(lua, player);
|
||||
// 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 {
|
||||
lua.run(target.getText());
|
||||
runtime.run(target.getText());
|
||||
} catch (Exception e) {
|
||||
LOGGER.warn("Error running " + entrypoint, e);
|
||||
player.sendSystemMessage(Component.literal("§ccodecraft error: " + e.getMessage()));
|
||||
@@ -130,6 +195,14 @@ public class Codecraft implements ModInitializer {
|
||||
});
|
||||
}
|
||||
|
||||
/** The project's file called {@code name}, or null when the project has none. */
|
||||
private static EditorFile findByName(List<EditorFile> files, String name) {
|
||||
for(EditorFile file : files) {
|
||||
if(file.getName().equals(name)) return file;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static Identifier id(String path) {
|
||||
return Identifier.fromNamespaceAndPath(MOD_ID, path);
|
||||
}
|
||||
|
||||
@@ -20,15 +20,34 @@ public class SavedProjectData extends SavedData {
|
||||
}
|
||||
|
||||
public SavedProjectData(List<EditorFile> editorFiles) {
|
||||
this.editorFiles = editorFiles;
|
||||
// What the codec decodes is an immutable list: writing the project back
|
||||
// out is fine with it, but while the server runs the project is added to
|
||||
// — a new file, or one that first appeared as a keystroke — and adding to
|
||||
// what the codec handed over throws. Keeping a copy of our own is what
|
||||
// makes `getEditorFiles().add(...)` mean anything.
|
||||
this.editorFiles = new ArrayList<>(editorFiles);
|
||||
}
|
||||
|
||||
/**
|
||||
* The project's files. The list itself is mutable, so a file can be added to
|
||||
* it; remember to {@link #setEditorFiles(List) set} it or at least
|
||||
* {@link #markDirty()} when its contents change, or nothing is written out.
|
||||
*/
|
||||
public List<EditorFile> getEditorFiles() {
|
||||
return editorFiles;
|
||||
}
|
||||
|
||||
public void setEditorFiles(List<EditorFile> editorFiles) {
|
||||
this.editorFiles = editorFiles;
|
||||
this.editorFiles = new ArrayList<>(editorFiles);
|
||||
setDirty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Flags the data for saving after a file's contents were changed in place.
|
||||
* Minecraft only writes it to disk periodically, so this is cheap enough to
|
||||
* call on every keystroke.
|
||||
*/
|
||||
public void markDirty() {
|
||||
setDirty();
|
||||
}
|
||||
|
||||
@@ -56,9 +75,9 @@ public class SavedProjectData extends SavedData {
|
||||
return new SavedProjectData(); // Return a new instance if the level is null.
|
||||
}
|
||||
|
||||
// The first time the following 'computeIfAbsent' function is called, it creates a new 'SavedBlockData'
|
||||
// The first time the following 'computeIfAbsent' function is called, it creates a new 'SavedProjectData'
|
||||
// instance and stores it inside the 'DimensionDataStorage'.
|
||||
// Subsequent calls to 'computeIfAbsent' returns the saved 'SavedBlockData' NBT on disk to the Codec in our type,
|
||||
// Subsequent calls to 'computeIfAbsent' returns the saved 'SavedProjectData' NBT on disk to the Codec in our type,
|
||||
// using the Codec to decode the NBT into our saved data.
|
||||
return level.getDataStorage().computeIfAbsent(TYPE);
|
||||
}
|
||||
|
||||
453
src/main/java/com/aranroig/collab/DocumentManager.java
Normal file
453
src/main/java/com/aranroig/collab/DocumentManager.java
Normal file
@@ -0,0 +1,453 @@
|
||||
package com.aranroig.collab;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.SavedProjectData;
|
||||
import com.aranroig.editor.Edit;
|
||||
import com.aranroig.editor.EditorFile;
|
||||
import com.aranroig.editor.EditorPresence;
|
||||
import com.aranroig.payloads.ClientboundDocumentEditPayload;
|
||||
import com.aranroig.payloads.ClientboundDocumentStatePayload;
|
||||
import com.aranroig.payloads.ClientboundEditAckPayload;
|
||||
import com.aranroig.payloads.ClientboundPresencePayload;
|
||||
import com.aranroig.payloads.ClientboundRenameFilePayload;
|
||||
import com.aranroig.payloads.ClientboundSaveCodePayload;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The server's copy of every document that players have open in the editor, and
|
||||
* the single authority on what they contain.
|
||||
*
|
||||
* <h2>Live editing</h2>
|
||||
*
|
||||
* <p>A player who opens the editor is put in a <em>session</em> for the file
|
||||
* they are looking at. Every keystroke they make arrives as an
|
||||
* {@link Edit} written against a known version of the document; this class
|
||||
* rebases it onto the current version — transforming it against the edits that
|
||||
* landed in the meantime, and never against the sender's own edits, which are
|
||||
* already in the buffer it was typed into — applies it, and hands it to the
|
||||
* other players in that file. That is what lets several people type in the same
|
||||
* file at once without losing each other's work.</p>
|
||||
*
|
||||
* <p>Each applied edit bumps the document's version, so every client can tell
|
||||
* which version it holds. The server keeps the last few edits per document so
|
||||
* an edit that arrives a little late can still be rebased; when one arrives
|
||||
* too late for that, its author is simply sent the authoritative document
|
||||
* again. The same thing happens whenever a client reports (through the ack
|
||||
* hash) that its copy stopped matching.</p>
|
||||
*
|
||||
* <p>Carets are tracked per session too, and every session gets the caret
|
||||
* positions of the other players, which is what lets the editor draw them.</p>
|
||||
*
|
||||
* <h2>Threading</h2>
|
||||
*
|
||||
* <p>All of this runs on the server thread: payload handlers and the connection
|
||||
* events below are dispatched there, so the maps need no locking.</p>
|
||||
*/
|
||||
public final class DocumentManager {
|
||||
|
||||
/** How many applied edits are kept per document for rebasing stale edits. */
|
||||
private static final int HISTORY_PER_DOCUMENT = 128;
|
||||
|
||||
/** Caret colours, picked by player id so a player looks the same everywhere. */
|
||||
private static final int[] PRESENCE_COLORS = {
|
||||
0xFF4FC3F7, // light blue
|
||||
0xFFFF8A65, // orange
|
||||
0xFFAED581, // green
|
||||
0xFFF06292, // pink
|
||||
0xFFBA68C8, // purple
|
||||
0xFFFFD54F, // amber
|
||||
0xFF4DB6AC, // teal
|
||||
0xFFE57373, // red
|
||||
0xFF90A4AE, // grey
|
||||
0xFFA1887F, // brown
|
||||
};
|
||||
|
||||
private static final Map<String, Document> DOCUMENTS = new HashMap<>();
|
||||
|
||||
/** One entry per player with the editor open, keyed by player id. */
|
||||
private static final Map<UUID, Session> SESSIONS = new HashMap<>();
|
||||
|
||||
private DocumentManager() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops players from their editing sessions when they disconnect and
|
||||
* throws the cached documents away when the world shuts down. Call once
|
||||
* from {@link com.aranroig.Codecraft#onInitialize()}.
|
||||
*/
|
||||
public static void install() {
|
||||
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> closeEditor(handler.player));
|
||||
|
||||
// Cached text must not outlive the world it came from.
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register(server -> {
|
||||
DOCUMENTS.clear();
|
||||
SESSIONS.clear();
|
||||
});
|
||||
}
|
||||
|
||||
// ── Sessions ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Puts {@code player} in the live session of {@code file} and replies with
|
||||
* its authoritative contents. Their previous file, if any, is dropped.
|
||||
*/
|
||||
public static void openDocument(ServerPlayer player, String file) {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
Session session = SESSIONS.computeIfAbsent(player.getUUID(), id -> new Session(player));
|
||||
if (!file.equals(session.file)) {
|
||||
session.file = file;
|
||||
session.cursor = 0;
|
||||
session.anchor = -1;
|
||||
}
|
||||
|
||||
Document document = document(server, file);
|
||||
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
|
||||
|
||||
broadcastPresence(server, file);
|
||||
sendPresenceSnapshot(player);
|
||||
}
|
||||
|
||||
/** Ends {@code player}'s editing session: called on close and on disconnect. */
|
||||
public static void closeEditor(ServerPlayer player) {
|
||||
Session session = SESSIONS.remove(player.getUUID());
|
||||
if (session == null) return;
|
||||
|
||||
MinecraftServer server = server(player);
|
||||
if (server != null && session.file != null) {
|
||||
broadcastPresence(server, session.file);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Document contents ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Applies one of {@code player}'s keystrokes. The edit was written against
|
||||
* version {@code baseVersion}; if the document moved on since then the edit
|
||||
* is rebased onto what happened in between first.
|
||||
*/
|
||||
public static void applyEdit(ServerPlayer player, String file, int baseVersion, Edit edit) {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
Document document = document(server, file);
|
||||
|
||||
// Never take the client's word for who wrote an edit: rebasing skips
|
||||
// the sender's own edits, so a spoofed author would apply one twice.
|
||||
Edit applied = new Edit(player.getUUID(), edit.seq(), edit.components());
|
||||
|
||||
if (baseVersion > document.version || baseVersion < document.oldestRebaseVersion()) {
|
||||
// Too far behind to rebase this edit without guessing: give the
|
||||
// player the real document and let them retype on top of it.
|
||||
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
|
||||
return;
|
||||
}
|
||||
|
||||
for (int version = baseVersion + 1; version <= document.version; version++) {
|
||||
Edit earlier = document.appliedAt(version);
|
||||
if (earlier == null) break;
|
||||
if (earlier.author().equals(player.getUUID())) continue;
|
||||
applied = applied.transformAgainst(earlier);
|
||||
}
|
||||
|
||||
document.apply(applied);
|
||||
boolean brandNew = persist(server, file, document.text);
|
||||
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
|
||||
broadcastEdit(server, player.getUUID(), file, document.version, applied);
|
||||
|
||||
// A file nobody had saved yet came into the project with this keystroke,
|
||||
// and the editors of it are the only ones the edit above reaches: tell
|
||||
// everybody else the project has one more file.
|
||||
if (brandNew) broadcastProjectFile(server, player, file, document.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@code text} over {@code file} as one edit (the explicit Save).
|
||||
* Going through an edit rather than storing the buffer directly is what
|
||||
* keeps the other editors converging instead of being clobbered, and it
|
||||
* trims the parts both versions agree on so the change stays small.
|
||||
*/
|
||||
public static void replaceDocument(ServerPlayer player, String file, String text) {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
Document document = document(server, file);
|
||||
String current = document.text;
|
||||
|
||||
if (current.equals(text)) {
|
||||
// Nothing changed, but the player asked to save: the file still
|
||||
// has to exist on disk (a brand-new file is saved before it has
|
||||
// any edits flowing), and confirm the version they are on so they
|
||||
// can check their copy against it.
|
||||
persist(server, file, current);
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length()));
|
||||
} else {
|
||||
int prefix = commonPrefix(current, text);
|
||||
int suffix = commonSuffix(current, text, prefix);
|
||||
Edit edit = Edit.replace(player.getUUID(), document.nextSequence(),
|
||||
prefix, current.length() - prefix - suffix, text.substring(prefix, text.length() - suffix));
|
||||
|
||||
// A whole-file save states what the file should contain, so it is
|
||||
// applied to the server's current text instead of being rebased.
|
||||
document.apply(edit);
|
||||
persist(server, file, document.text);
|
||||
|
||||
ServerPlayNetworking.send(player,
|
||||
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
|
||||
broadcastEdit(server, player.getUUID(), file, document.version, edit);
|
||||
}
|
||||
|
||||
// Saving is also how a file says it exists: the other editors add it to
|
||||
// their sidebars, and the ones not looking at it are not left holding a
|
||||
// copy a save behind.
|
||||
broadcastProjectFile(server, player, file, document.text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves {@code oldName} to {@code newName} everywhere the server knows it:
|
||||
* in the saved project, in the cached document and in the sessions of
|
||||
* everyone editing it — and the other editors' file lists are told. A name
|
||||
* the project already holds is refused.
|
||||
*/
|
||||
public static void renameFile(ServerPlayer player, String oldName, String newName) {
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null || oldName.equals(newName)) return;
|
||||
|
||||
SavedProjectData data = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = data.getEditorFiles();
|
||||
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(newName)) return; // the name is taken
|
||||
}
|
||||
|
||||
boolean onDisk = false;
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(oldName)) {
|
||||
editorFile.setName(newName);
|
||||
onDisk = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (onDisk) data.markDirty();
|
||||
|
||||
// The live document keeps its version history under the new name, so
|
||||
// the editors of the file can carry on without refetching anything.
|
||||
Document document = DOCUMENTS.remove(oldName);
|
||||
if (document != null) DOCUMENTS.put(newName, document);
|
||||
|
||||
for (Session session : SESSIONS.values()) {
|
||||
if (oldName.equals(session.file)) session.file = newName;
|
||||
}
|
||||
|
||||
// Nobody is in the old name any more, and the new one holds them all.
|
||||
broadcastPresence(server, oldName);
|
||||
broadcastPresence(server, newName);
|
||||
|
||||
for (ServerPlayer other : server.getPlayerList().getPlayers()) {
|
||||
if (other != player) {
|
||||
ServerPlayNetworking.send(other, new ClientboundRenameFilePayload(oldName, newName));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Carets ────────────────────────────────────────────────────────────
|
||||
|
||||
/** Records where {@code player}'s caret is in {@code file} and tells everyone. */
|
||||
public static void updateCursor(ServerPlayer player, String file, int cursor, int anchor) {
|
||||
Session session = SESSIONS.get(player.getUUID());
|
||||
if (session == null || !file.equals(session.file)) return;
|
||||
|
||||
MinecraftServer server = server(player);
|
||||
if (server == null) return;
|
||||
|
||||
session.cursor = Math.max(0, cursor);
|
||||
session.anchor = anchor;
|
||||
|
||||
broadcastPresence(server, file);
|
||||
}
|
||||
|
||||
// ── Internals ─────────────────────────────────────────────────────────
|
||||
|
||||
private static Document document(MinecraftServer server, String file) {
|
||||
Document document = DOCUMENTS.get(file);
|
||||
if (document == null) {
|
||||
String text = "";
|
||||
for (EditorFile editorFile : SavedProjectData.getSavedBlockData(server).getEditorFiles()) {
|
||||
if (editorFile.getName().equals(file)) {
|
||||
text = editorFile.getText();
|
||||
break;
|
||||
}
|
||||
}
|
||||
document = new Document(text);
|
||||
DOCUMENTS.put(file, document);
|
||||
}
|
||||
return document;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the live text back into the project's saved data, saying whether
|
||||
* that meant the project gained the file. The write itself is throttled by
|
||||
* {@code SavedData}, so marking it dirty per keystroke is cheap and means a
|
||||
* crash loses at most a second of typing.
|
||||
*/
|
||||
private static boolean persist(MinecraftServer server, String file, String text) {
|
||||
SavedProjectData data = SavedProjectData.getSavedBlockData(server);
|
||||
List<EditorFile> files = data.getEditorFiles();
|
||||
|
||||
for (EditorFile editorFile : files) {
|
||||
if (editorFile.getName().equals(file)) {
|
||||
editorFile.setText(text);
|
||||
data.markDirty();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
files.add(new EditorFile(file, text));
|
||||
data.setEditorFiles(files);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells every editor but {@code author} that the project holds {@code file}
|
||||
* with {@code text}. It is how one player's new file turns into a row in the
|
||||
* others' sidebars, and what keeps a client that is not looking at the file
|
||||
* from holding a copy a save behind.
|
||||
*/
|
||||
private static void broadcastProjectFile(MinecraftServer server, ServerPlayer author, String file, String text) {
|
||||
for (ServerPlayer other : server.getPlayerList().getPlayers()) {
|
||||
if (other == author) continue;
|
||||
ServerPlayNetworking.send(other, new ClientboundSaveCodePayload(new EditorFile(file, text)));
|
||||
}
|
||||
}
|
||||
|
||||
private static void broadcastEdit(MinecraftServer server, UUID author, String file, int version, Edit edit) {
|
||||
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
|
||||
if (entry.getKey().equals(author) || !file.equals(entry.getValue().file)) continue;
|
||||
ServerPlayNetworking.send(entry.getValue().player, new ClientboundDocumentEditPayload(file, version, edit));
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-sends the carets of everyone in {@code file} to every open editor. */
|
||||
private static void broadcastPresence(MinecraftServer server, String file) {
|
||||
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
|
||||
if (entry.getValue().file == null) continue;
|
||||
sendPresence(entry.getValue().player, file, presenceIn(file, entry.getKey()));
|
||||
}
|
||||
}
|
||||
|
||||
/** Brings a player up to date with everywhere somebody is already editing. */
|
||||
private static void sendPresenceSnapshot(ServerPlayer player) {
|
||||
UUID self = player.getUUID();
|
||||
List<String> files = new ArrayList<>();
|
||||
for (Session session : SESSIONS.values()) {
|
||||
if (session.file != null && !files.contains(session.file)) files.add(session.file);
|
||||
}
|
||||
for (String file : files) {
|
||||
sendPresence(player, file, presenceIn(file, self));
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendPresence(ServerPlayer to, String file, List<EditorPresence> editors) {
|
||||
ServerPlayNetworking.send(to, new ClientboundPresencePayload(file, editors));
|
||||
}
|
||||
|
||||
private static List<EditorPresence> presenceIn(String file, UUID exclude) {
|
||||
List<EditorPresence> editors = new ArrayList<>();
|
||||
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
|
||||
Session session = entry.getValue();
|
||||
if (entry.getKey().equals(exclude) || !file.equals(session.file)) continue;
|
||||
editors.add(new EditorPresence(entry.getKey(), session.player.getScoreboardName(),
|
||||
session.color, session.cursor, session.anchor));
|
||||
}
|
||||
return editors;
|
||||
}
|
||||
|
||||
private static MinecraftServer server(ServerPlayer player) {
|
||||
return player.level().getServer();
|
||||
}
|
||||
|
||||
private static int commonPrefix(String left, String right) {
|
||||
int max = Math.min(left.length(), right.length());
|
||||
int i = 0;
|
||||
while (i < max && left.charAt(i) == right.charAt(i)) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
private static int commonSuffix(String left, String right, int prefix) {
|
||||
int max = Math.min(left.length(), right.length()) - prefix;
|
||||
int i = 0;
|
||||
while (i < max && left.charAt(left.length() - 1 - i) == right.charAt(right.length() - 1 - i)) i++;
|
||||
return i;
|
||||
}
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────
|
||||
|
||||
/** The server's copy of one document, with the edits that produced it. */
|
||||
private static final class Document {
|
||||
private String text;
|
||||
private int version;
|
||||
|
||||
/** Applied edits, oldest first; {@code history.get(0)} is version {@code firstRetainedVersion}. */
|
||||
private final List<Edit> history = new ArrayList<>();
|
||||
private int firstRetainedVersion = 1;
|
||||
|
||||
private Document(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
private void apply(Edit edit) {
|
||||
text = edit.apply(text);
|
||||
version++;
|
||||
|
||||
if (history.size() == HISTORY_PER_DOCUMENT) {
|
||||
history.remove(0);
|
||||
firstRetainedVersion++;
|
||||
}
|
||||
history.add(edit);
|
||||
}
|
||||
|
||||
/** The edit that took the document to {@code targetVersion}, or null once forgotten. */
|
||||
private Edit appliedAt(int targetVersion) {
|
||||
int index = targetVersion - firstRetainedVersion;
|
||||
if (index < 0 || index >= history.size()) return null;
|
||||
return history.get(index);
|
||||
}
|
||||
|
||||
/** Oldest base version that can still be rebased onto this document. */
|
||||
private int oldestRebaseVersion() {
|
||||
return firstRetainedVersion - 1;
|
||||
}
|
||||
|
||||
private long nextSequence() {
|
||||
return version + 1L;
|
||||
}
|
||||
}
|
||||
|
||||
/** One player with the editor open, and where they are pointing. */
|
||||
private static final class Session {
|
||||
private final ServerPlayer player;
|
||||
private final int color;
|
||||
|
||||
private String file;
|
||||
private int cursor;
|
||||
private int anchor = -1;
|
||||
|
||||
private Session(ServerPlayer player) {
|
||||
this.player = player;
|
||||
this.color = PRESENCE_COLORS[Math.floorMod(player.getUUID().hashCode(), PRESENCE_COLORS.length)];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,142 +1,125 @@
|
||||
package com.aranroig.docs;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.google.gson.JsonArray;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The in-game reference for every Lua global this mod exposes to user scripts.
|
||||
*
|
||||
* <p>This is a hand-written catalog describing the functions registered by the
|
||||
* wrappers in {@code com.aranroig.wrapper} (currently {@code world} from
|
||||
* {@link com.aranroig.wrapper.WorldApi} and the {@code print} helper). The
|
||||
* client editor reads it to render the browsable documentation panel, so it is
|
||||
* the single source of truth shown to players.</p>
|
||||
* <p>The catalog is data, not code: it lives in
|
||||
* {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from
|
||||
* the mod resources on first access, so documentation can be edited (and, once
|
||||
* packed, overridden) without touching Java. It describes the functions
|
||||
* registered by the wrappers in {@code com.aranroig.wrapper} (currently
|
||||
* {@code world} and the {@code print} helper) and by
|
||||
* {@link com.aranroig.listeners.EventsApi} ({@code events}). The client editor
|
||||
* reads it to render the browsable documentation panel, so it is the single
|
||||
* source of truth shown to players.</p>
|
||||
*
|
||||
* <p>Keep it in sync with the wrapper implementations and {@code docs/lua-api.md}.</p>
|
||||
*/
|
||||
public final class LuaApiDocs {
|
||||
|
||||
/** Location of the catalog inside the mod resources. */
|
||||
private static final String RESOURCE = "/data/codecraft/docs/lua-api.json";
|
||||
|
||||
private static List<Topic> cache;
|
||||
|
||||
private LuaApiDocs() {
|
||||
}
|
||||
|
||||
// ── world.* — block access ────────────────────────────────────────────
|
||||
|
||||
private static final FunctionDoc SET_BLOCK = new FunctionDoc(
|
||||
"world.set_block",
|
||||
"world.set_block(x, y, z, block)",
|
||||
"Places a block and updates neighbours and clients, like /setblock does.",
|
||||
List.of(
|
||||
new ParamDoc("x", "number", false, "Absolute world x coordinate (F3 to read your own)."),
|
||||
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||
new ParamDoc("z", "number", false, "Absolute world z coordinate."),
|
||||
new ParamDoc("block", "string", false,
|
||||
"Block id, with or without the minecraft: namespace, optionally with block states.")
|
||||
),
|
||||
"true on success, or false followed by a reason string.",
|
||||
List.of(
|
||||
"Coordinates are absolute, never relative to the player.",
|
||||
"A block that cannot survive where it is put (a torch without a wall, a flower without ground) drops itself again and the call reports failure.",
|
||||
"Replacing a block that holds items, such as a chest, drops its contents."
|
||||
),
|
||||
List.of(
|
||||
new ExampleDoc("Namespace is optional; states are allowed",
|
||||
"world.set_block(10, 64, -3, \"minecraft:stone\")\n"
|
||||
+ "world.set_block(10, 65, -3, \"gold_block\")\n"
|
||||
+ "world.set_block(10, 66, -3, \"minecraft:oak_stairs[facing=north]\")"),
|
||||
new ExampleDoc("Check whether it worked",
|
||||
"local ok, reason = world.set_block(10, 64, -3, \"minecraft:stone\")\n"
|
||||
+ "if not ok then\n"
|
||||
+ " print(\"could not place the block: \" .. reason)\n"
|
||||
+ "end")
|
||||
)
|
||||
);
|
||||
|
||||
private static final FunctionDoc REMOVE_BLOCK = new FunctionDoc(
|
||||
"world.remove_block",
|
||||
"world.remove_block(x, y, z [, drops])",
|
||||
"Removes the block at the given position.",
|
||||
List.of(
|
||||
new ParamDoc("x", "number", false, "Absolute world x coordinate."),
|
||||
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||
new ParamDoc("z", "number", false, "Absolute world z coordinate."),
|
||||
new ParamDoc("drops", "boolean", true,
|
||||
"Pass true to break the block the way a player would (items, sound, particles).")
|
||||
),
|
||||
"true on success, or false followed by a reason string.",
|
||||
List.of(
|
||||
"Without drops the block just vanishes, silently and without items.",
|
||||
"Fails with \"there is nothing to remove\" if the target is already air."
|
||||
),
|
||||
List.of(
|
||||
new ExampleDoc("Vanish versus break",
|
||||
"world.remove_block(10, 64, -3) -- vanish\n"
|
||||
+ "world.remove_block(10, 65, -3, true) -- break it, dropping items")
|
||||
)
|
||||
);
|
||||
|
||||
private static final FunctionDoc GET_BLOCK = new FunctionDoc(
|
||||
"world.get_block",
|
||||
"world.get_block(x, y, z)",
|
||||
"Returns the block id at that position, including its block states.",
|
||||
List.of(
|
||||
new ParamDoc("x", "number", false, "Absolute world x coordinate."),
|
||||
new ParamDoc("y", "number", false, "Absolute world y coordinate."),
|
||||
new ParamDoc("z", "number", false, "Absolute world z coordinate.")
|
||||
),
|
||||
"The block id string (ready to hand to set_block), or nil followed by a reason string.",
|
||||
List.of(
|
||||
"Air is the string \"minecraft:air\", and every string is truthy in Lua — compare against the id rather than testing the value.",
|
||||
"The result carries block states, e.g. minecraft:grass_block[snowy=false]."
|
||||
),
|
||||
List.of(
|
||||
new ExampleDoc("Compare against the id, not the value",
|
||||
"local block = world.get_block(10, 64, -3)\n"
|
||||
+ "if block ~= \"minecraft:air\" then\n"
|
||||
+ " print(\"something is there: \" .. block)\n"
|
||||
+ "end"),
|
||||
new ExampleDoc("Copy one place to another",
|
||||
"local block = world.get_block(10, 64, -3)\n"
|
||||
+ "if block then\n"
|
||||
+ " world.set_block(20, 70, 5, block)\n"
|
||||
+ "end")
|
||||
)
|
||||
);
|
||||
|
||||
// ── print — chat output ───────────────────────────────────────────────
|
||||
|
||||
private static final FunctionDoc PRINT = new FunctionDoc(
|
||||
"print",
|
||||
"print(...)",
|
||||
"Writes to the chat of the player who ran the script, tab-separated.",
|
||||
List.of(),
|
||||
"nothing",
|
||||
List.of(
|
||||
"Whole numbers go through the Lua wrapper and are printed as 12.0; concatenate them into a string to drop the decimal.",
|
||||
"Runs on the server, so output appears in the running player's chat."
|
||||
),
|
||||
List.of(
|
||||
new ExampleDoc("Print to chat",
|
||||
"print(\"blocks placed:\", 12)"),
|
||||
new ExampleDoc("Drop the trailing .0",
|
||||
"print(\"blocks placed: \" .. 12) -- -> blocks placed: 12")
|
||||
)
|
||||
);
|
||||
|
||||
// ── The full table ────────────────────────────────────────────────────
|
||||
|
||||
private static final List<Topic> TOPICS = List.of(
|
||||
new Topic("world", "Read and write blocks in the running player's dimension.",
|
||||
List.of(SET_BLOCK, REMOVE_BLOCK, GET_BLOCK)),
|
||||
new Topic("print", "Send text to the chat of the player running the script.",
|
||||
List.of(PRINT))
|
||||
);
|
||||
|
||||
/** All documented topics, in display order. */
|
||||
public static List<Topic> topics() {
|
||||
return TOPICS;
|
||||
public static synchronized List<Topic> topics() {
|
||||
if (cache == null) {
|
||||
cache = load();
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
/** Flattened list of every documented function, across all topics. */
|
||||
public static List<FunctionDoc> functions() {
|
||||
return TOPICS.stream().flatMap(t -> t.functions().stream()).toList();
|
||||
return topics().stream().flatMap(t -> t.functions().stream()).toList();
|
||||
}
|
||||
|
||||
// ── Loading ───────────────────────────────────────────────────────────
|
||||
|
||||
private static List<Topic> load() {
|
||||
try (InputStream in = LuaApiDocs.class.getResourceAsStream(RESOURCE)) {
|
||||
if (in == null) {
|
||||
Codecraft.LOGGER.error("Lua API docs resource not found at {}", RESOURCE);
|
||||
return List.of();
|
||||
}
|
||||
return parse(JsonParser.parseReader(
|
||||
new InputStreamReader(in, StandardCharsets.UTF_8)).getAsJsonObject());
|
||||
} catch (Exception e) {
|
||||
Codecraft.LOGGER.error("Failed to load Lua API docs from {}", RESOURCE, e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private static List<Topic> parse(JsonObject root) {
|
||||
List<Topic> topics = new ArrayList<>();
|
||||
for (JsonElement t : optArray(root, "topics")) {
|
||||
JsonObject topic = t.getAsJsonObject();
|
||||
List<FunctionDoc> functions = new ArrayList<>();
|
||||
for (JsonElement f : optArray(topic, "functions")) {
|
||||
functions.add(readFunction(f.getAsJsonObject()));
|
||||
}
|
||||
topics.add(new Topic(
|
||||
str(topic, "title"),
|
||||
str(topic, "blurb"),
|
||||
List.copyOf(functions)));
|
||||
}
|
||||
return List.copyOf(topics);
|
||||
}
|
||||
|
||||
private static FunctionDoc readFunction(JsonObject f) {
|
||||
List<ParamDoc> params = new ArrayList<>();
|
||||
for (JsonElement p : optArray(f, "params")) {
|
||||
JsonObject param = p.getAsJsonObject();
|
||||
params.add(new ParamDoc(
|
||||
str(param, "name"),
|
||||
str(param, "type"),
|
||||
param.has("optional") && param.get("optional").getAsBoolean(),
|
||||
str(param, "description")));
|
||||
}
|
||||
List<String> notes = new ArrayList<>();
|
||||
for (JsonElement n : optArray(f, "notes")) {
|
||||
notes.add(n.getAsString());
|
||||
}
|
||||
List<ExampleDoc> examples = new ArrayList<>();
|
||||
for (JsonElement e : optArray(f, "examples")) {
|
||||
JsonObject example = e.getAsJsonObject();
|
||||
examples.add(new ExampleDoc(
|
||||
str(example, "title"),
|
||||
str(example, "code")));
|
||||
}
|
||||
return new FunctionDoc(
|
||||
str(f, "name"),
|
||||
str(f, "signature"),
|
||||
str(f, "summary"),
|
||||
List.copyOf(params),
|
||||
str(f, "returns"),
|
||||
List.copyOf(notes),
|
||||
List.copyOf(examples));
|
||||
}
|
||||
|
||||
private static String str(JsonObject object, String key) {
|
||||
JsonElement value = object.get(key);
|
||||
return value == null || value.isJsonNull() ? "" : value.getAsString();
|
||||
}
|
||||
|
||||
private static JsonArray optArray(JsonObject object, String key) {
|
||||
JsonElement value = object.get(key);
|
||||
return value != null && value.isJsonArray() ? value.getAsJsonArray() : new JsonArray();
|
||||
}
|
||||
}
|
||||
|
||||
338
src/main/java/com/aranroig/editor/Edit.java
Normal file
338
src/main/java/com/aranroig/editor/Edit.java
Normal file
@@ -0,0 +1,338 @@
|
||||
package com.aranroig.editor;
|
||||
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Deque;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* A character-level change to a document: a walk over the text saying which
|
||||
* characters to keep ({@link Retain}), which to remove ({@link Delete}) and what
|
||||
* to write ({@link Insert}). Anything the walk does not mention is left alone.
|
||||
*
|
||||
* <p>Describing a change this way, instead of as one "replace this range with
|
||||
* that text", is what makes shared editing possible. Two players can write
|
||||
* against the same version of a file at the same time; before such a change is
|
||||
* used anywhere other than where it was written it is <em>transformed</em>
|
||||
* against the changes that went in first ({@link #transformAgainst(Edit)},
|
||||
* {@link #transformPair(Edit, Edit)}), which re-expresses it against the text it
|
||||
* is about to meet. Deleting around somebody else's freshly typed text, typing
|
||||
* inside a selection they are throwing away, both merge instead of one of the
|
||||
* two losing.</p>
|
||||
*
|
||||
* <p>{@code author} and {@code seq} survive every transform. They give two
|
||||
* inserts at the same offset a total order, so every player ends up with the
|
||||
* characters in the same sequence, and they tell the server which edits came
|
||||
* from the sender itself (those are already in the buffer the sender typed
|
||||
* into, so the server must not apply them twice).</p>
|
||||
*/
|
||||
public record Edit(UUID author, long seq, List<Edit.Component> components) {
|
||||
|
||||
/** One step of the walk over a document. */
|
||||
public sealed interface Component permits Retain, Insert, Delete {
|
||||
}
|
||||
|
||||
/** Keep {@code count} characters of the document as they are. */
|
||||
public record Retain(int count) implements Component {
|
||||
}
|
||||
|
||||
/** Write {@code text} at this point of the document. */
|
||||
public record Insert(String text) implements Component {
|
||||
}
|
||||
|
||||
/** Remove {@code count} characters from the document. */
|
||||
public record Delete(int count) implements Component {
|
||||
}
|
||||
|
||||
private static final StreamCodec<RegistryFriendlyByteBuf, Component> COMPONENT_CODEC = new StreamCodec<>() {
|
||||
@Override
|
||||
public Component decode(RegistryFriendlyByteBuf buf) {
|
||||
return switch (buf.readByte()) {
|
||||
case 1 -> new Insert(ByteBufCodecs.STRING_UTF8.decode(buf));
|
||||
case 2 -> new Delete(ByteBufCodecs.VAR_INT.decode(buf));
|
||||
default -> new Retain(ByteBufCodecs.VAR_INT.decode(buf));
|
||||
};
|
||||
}
|
||||
|
||||
@Override
|
||||
public void encode(RegistryFriendlyByteBuf buf, Component component) {
|
||||
if (component instanceof Insert insert) {
|
||||
buf.writeByte(1);
|
||||
ByteBufCodecs.STRING_UTF8.encode(buf, insert.text());
|
||||
} else if (component instanceof Delete delete) {
|
||||
buf.writeByte(2);
|
||||
ByteBufCodecs.VAR_INT.encode(buf, delete.count());
|
||||
} else {
|
||||
buf.writeByte(0);
|
||||
ByteBufCodecs.VAR_INT.encode(buf, ((Retain) component).count());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, Edit> STREAM_CODEC =
|
||||
StreamCodec.composite(
|
||||
UUIDUtil.STREAM_CODEC,
|
||||
Edit::author,
|
||||
|
||||
ByteBufCodecs.VAR_LONG,
|
||||
Edit::seq,
|
||||
|
||||
COMPONENT_CODEC.apply(ByteBufCodecs.list()),
|
||||
Edit::components,
|
||||
|
||||
Edit::new
|
||||
);
|
||||
|
||||
// ── Building edits ────────────────────────────────────────────────────
|
||||
|
||||
/** A change that leaves the document as it is. */
|
||||
public static Edit none(UUID author, long seq) {
|
||||
return new Edit(author, seq, List.of());
|
||||
}
|
||||
|
||||
/** {@code text} written at {@code position}, nothing removed. */
|
||||
public static Edit insertion(UUID author, long seq, int position, String text) {
|
||||
return replace(author, seq, position, 0, text);
|
||||
}
|
||||
|
||||
/** {@code count} characters removed at {@code position}, nothing written back. */
|
||||
public static Edit deletion(UUID author, long seq, int position, int count) {
|
||||
return replace(author, seq, position, count, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape the text editor produces with every keystroke: remove
|
||||
* {@code deleteLength} characters at {@code position} and write
|
||||
* {@code insert} there.
|
||||
*/
|
||||
public static Edit replace(UUID author, long seq, int position, int deleteLength, String insert) {
|
||||
List<Component> components = new ArrayList<>(3);
|
||||
if (position > 0) components.add(new Retain(position));
|
||||
if (deleteLength > 0) components.add(new Delete(deleteLength));
|
||||
if (!insert.isEmpty()) components.add(new Insert(insert));
|
||||
return new Edit(author, seq, components);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
for (Component component : components) {
|
||||
if (component instanceof Insert || component instanceof Delete) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** How many characters of the document this edit reads; 0 for a pure insert. */
|
||||
public int baseLength() {
|
||||
int total = 0;
|
||||
for (Component component : components) {
|
||||
if (component instanceof Retain retain) total += retain.count();
|
||||
else if (component instanceof Delete delete) total += delete.count();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// ── Applying ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Runs this edit over {@code base}. Counts that do not fit the text are
|
||||
* clamped rather than thrown at: a document that stopped matching its
|
||||
* version is repaired by resyncing, not by crashing the editor.
|
||||
*/
|
||||
public String apply(String base) {
|
||||
if (isEmpty()) return base;
|
||||
|
||||
StringBuilder result = new StringBuilder(base.length());
|
||||
int index = 0;
|
||||
|
||||
for (Component component : components) {
|
||||
if (component instanceof Retain retain) {
|
||||
int count = Math.min(retain.count(), base.length() - index);
|
||||
if (count <= 0) break;
|
||||
result.append(base, index, index + count);
|
||||
index += count;
|
||||
} else if (component instanceof Delete delete) {
|
||||
int count = Math.min(delete.count(), base.length() - index);
|
||||
if (count <= 0) break;
|
||||
index += count;
|
||||
} else if (component instanceof Insert insert) {
|
||||
result.append(insert.text());
|
||||
}
|
||||
}
|
||||
if (index < base.length()) result.append(base, index, base.length());
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a caret at {@code caret} ends up once this edit is applied: text
|
||||
* inserted before it pushes it along, text deleted around it collapses it
|
||||
* onto the deletion point. Text inserted at the caret's own offset goes in
|
||||
* front of it, which is where the editor expects its own typing to land.
|
||||
*/
|
||||
public int shiftPosition(int caret) {
|
||||
int read = 0; // how far into the base document the walk has got
|
||||
int written = 0;
|
||||
|
||||
for (Component component : components) {
|
||||
if (read >= caret) break;
|
||||
|
||||
if (component instanceof Retain retain) {
|
||||
int count = Math.min(retain.count(), caret - read);
|
||||
read += count;
|
||||
written += count;
|
||||
} else if (component instanceof Delete delete) {
|
||||
read += Math.min(delete.count(), caret - read);
|
||||
// written does not move: the caret collapses onto the deletion
|
||||
} else if (component instanceof Insert insert) {
|
||||
written += insert.text().length();
|
||||
}
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
// ── Transforming ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* This edit re-expressed against a document that already contains
|
||||
* {@code other}. Both are assumed to have been written against the same
|
||||
* base document; applying the result after {@code other} has the effect this
|
||||
* edit was meant to have there.
|
||||
*/
|
||||
public Edit transformAgainst(Edit other) {
|
||||
return transformPair(this, other)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Both edits expressed against each other's result: returns
|
||||
* {@code [this↑other, other↑this]}. Applying {@code this↑other} after
|
||||
* {@code other} gives the same document as applying {@code other↑this}
|
||||
* after {@code this}, which is what every player's copy converging on
|
||||
* rests upon.
|
||||
*/
|
||||
public static Edit[] transformPair(Edit left, Edit right) {
|
||||
List<Component> leftResult = new ArrayList<>();
|
||||
List<Component> rightResult = new ArrayList<>();
|
||||
|
||||
Deque<Component> leftOp = new ArrayDeque<>(left.components());
|
||||
Deque<Component> rightOp = new ArrayDeque<>(right.components());
|
||||
|
||||
while (!leftOp.isEmpty() || !rightOp.isEmpty()) {
|
||||
// Whichever edit ran out says nothing about what is left of the
|
||||
// document, which is the same as keeping it.
|
||||
Component l = leftOp.peekFirst();
|
||||
Component r = rightOp.peekFirst();
|
||||
boolean lVirtual = l == null;
|
||||
boolean rVirtual = r == null;
|
||||
if (l == null) l = new Retain(remaining(r));
|
||||
if (r == null) r = new Retain(remaining(l));
|
||||
|
||||
if (l instanceof Insert lInsert && !(r instanceof Insert)) {
|
||||
// Our text goes in before whatever the other edit does next. An
|
||||
// insert is never swallowed by a concurrent deletion.
|
||||
add(leftResult, lInsert);
|
||||
add(rightResult, new Retain(lInsert.text().length()));
|
||||
leftOp.pollFirst();
|
||||
continue;
|
||||
}
|
||||
if (r instanceof Insert rInsert && !(l instanceof Insert)) {
|
||||
add(rightResult, rInsert);
|
||||
add(leftResult, new Retain(rInsert.text().length()));
|
||||
rightOp.pollFirst();
|
||||
continue;
|
||||
}
|
||||
if (l instanceof Insert lInsert && r instanceof Insert rInsert) {
|
||||
// Two players typed at the same offset: authorship decides who
|
||||
// ends up in front, the same way round in both directions.
|
||||
if (left.precedes(right)) {
|
||||
add(leftResult, lInsert);
|
||||
add(rightResult, new Retain(lInsert.text().length()));
|
||||
leftOp.pollFirst();
|
||||
} else {
|
||||
add(rightResult, rInsert);
|
||||
add(leftResult, new Retain(rInsert.text().length()));
|
||||
rightOp.pollFirst();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Neither side writes text here: both steps cover the same stretch
|
||||
// of the original document.
|
||||
int count = Math.min(remaining(l), remaining(r));
|
||||
boolean lDeletes = l instanceof Delete;
|
||||
boolean rDeletes = r instanceof Delete;
|
||||
|
||||
if (lDeletes && !rDeletes) add(leftResult, new Delete(count)); // they deleted it; we still want it gone
|
||||
else if (rDeletes && !lDeletes) add(rightResult, new Delete(count));
|
||||
else if (!lDeletes && !rDeletes) {
|
||||
add(leftResult, new Retain(count));
|
||||
add(rightResult, new Retain(count));
|
||||
}
|
||||
// Both deleting: the characters are gone either way, nothing to say.
|
||||
|
||||
consume(leftOp, count, lVirtual);
|
||||
consume(rightOp, count, rVirtual);
|
||||
}
|
||||
|
||||
return new Edit[]{
|
||||
new Edit(left.author, left.seq, leftResult),
|
||||
new Edit(right.author, right.seq, rightResult),
|
||||
};
|
||||
}
|
||||
|
||||
/** Collects a component, merging it into the previous one where possible. */
|
||||
private static void add(List<Component> components, Component component) {
|
||||
if (component instanceof Retain retain && retain.count() == 0) return;
|
||||
if (component instanceof Delete delete && delete.count() == 0) return;
|
||||
if (component instanceof Insert insert && insert.text().isEmpty()) return;
|
||||
|
||||
int last = components.size() - 1;
|
||||
if (last >= 0) {
|
||||
Component previous = components.get(last);
|
||||
if (previous instanceof Retain a && component instanceof Retain b) {
|
||||
components.set(last, new Retain(a.count() + b.count()));
|
||||
return;
|
||||
}
|
||||
if (previous instanceof Delete a && component instanceof Delete b) {
|
||||
components.set(last, new Delete(a.count() + b.count()));
|
||||
return;
|
||||
}
|
||||
if (previous instanceof Insert a && component instanceof Insert b) {
|
||||
components.set(last, new Insert(a.text() + b.text()));
|
||||
return;
|
||||
}
|
||||
}
|
||||
components.add(component);
|
||||
}
|
||||
|
||||
/** Characters a step covers: for inserts, the length of the text written. */
|
||||
private static int remaining(Component component) {
|
||||
if (component instanceof Retain retain) return retain.count();
|
||||
if (component instanceof Delete delete) return delete.count();
|
||||
return ((Insert) component).text().length();
|
||||
}
|
||||
|
||||
/** Advances a walk by {@code count} characters, splitting the step it lands in. */
|
||||
private static void consume(Deque<Component> components, int count, boolean virtual) {
|
||||
if (virtual) return; // nothing there to advance; it is re-derived next round
|
||||
Component head = components.pollFirst();
|
||||
int left = remaining(head) - count;
|
||||
if (left > 0) {
|
||||
components.addFirst(head instanceof Retain ? new Retain(left) : new Delete(left));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Total order over two edits, used only to decide which of two inserts at
|
||||
* the same offset comes first. It deliberately ignores positions, so it
|
||||
* still says the same thing after both have been transformed.
|
||||
*/
|
||||
public boolean precedes(Edit other) {
|
||||
int byAuthor = author.compareTo(other.author);
|
||||
if (byAuthor != 0) return byAuthor < 0;
|
||||
return seq < other.seq;
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,10 @@ public class EditorFile {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
43
src/main/java/com/aranroig/editor/EditorPresence.java
Normal file
43
src/main/java/com/aranroig/editor/EditorPresence.java
Normal file
@@ -0,0 +1,43 @@
|
||||
package com.aranroig.editor;
|
||||
|
||||
import net.minecraft.core.UUIDUtil;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* Where one player is pointing inside a document they have open in the editor.
|
||||
*
|
||||
* <p>Offsets are character offsets into the document, the same coordinates the
|
||||
* text editor uses for its own caret ({@code EditorFileView#cursorPos}), so a
|
||||
* remote caret can be drawn with the same offset-to-pixel maths as the local
|
||||
* one. {@code anchor} is {@code -1} when nothing is selected.</p>
|
||||
*/
|
||||
public record EditorPresence(UUID playerId, String name, int color, int cursor, int anchor) {
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, EditorPresence> STREAM_CODEC =
|
||||
StreamCodec.composite(
|
||||
UUIDUtil.STREAM_CODEC,
|
||||
EditorPresence::playerId,
|
||||
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
EditorPresence::name,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
EditorPresence::color,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
EditorPresence::cursor,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
EditorPresence::anchor,
|
||||
|
||||
EditorPresence::new
|
||||
);
|
||||
|
||||
public boolean hasSelection() {
|
||||
return anchor >= 0 && anchor != cursor;
|
||||
}
|
||||
}
|
||||
55
src/main/java/com/aranroig/editor/ProjectPath.java
Normal file
55
src/main/java/com/aranroig/editor/ProjectPath.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package com.aranroig.editor;
|
||||
|
||||
/**
|
||||
* The name of a project file is the path it lives at: {@code lib/gui/theme},
|
||||
* with '/' between the folders and no extension on the end. Nothing else has to
|
||||
* know how a name is spelled — to the server it is only a key — so the sidebar
|
||||
* can read the folders straight out of it instead of keeping a second structure
|
||||
* that could end up disagreeing with the files it shows.
|
||||
*/
|
||||
public final class ProjectPath {
|
||||
|
||||
public static final char SEPARATOR = '/';
|
||||
|
||||
/** The file a run executes: the one called {@code main}, at the root of the project. */
|
||||
public static final String ENTRYPOINT = "main";
|
||||
|
||||
/** Names written before files dropped the extension are still shown without it. */
|
||||
public static final String LEGACY_EXTENSION = ".lua";
|
||||
|
||||
private ProjectPath() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The folders in front of the file, without a trailing slash. Empty when the
|
||||
* file sits at the root of the project, which is the same folder key the
|
||||
* sidebar uses for everything not inside a folder.
|
||||
*/
|
||||
public static String folderOf(String path) {
|
||||
int separator = path.lastIndexOf(SEPARATOR);
|
||||
return separator < 0 ? "" : path.substring(0, separator);
|
||||
}
|
||||
|
||||
/** The last segment of a path: the name of the file or folder itself. */
|
||||
public static String nameOf(String path) {
|
||||
int separator = path.lastIndexOf(SEPARATOR);
|
||||
return separator < 0 ? path : path.substring(separator + 1);
|
||||
}
|
||||
|
||||
/** The last segment without its extension: what the sidebar shows as a label. */
|
||||
public static String displayNameOf(String path) {
|
||||
return withoutExtension(nameOf(path));
|
||||
}
|
||||
|
||||
/** Drops a trailing {@code .lua}. New names are written without one. */
|
||||
public static String withoutExtension(String name) {
|
||||
return name.endsWith(LEGACY_EXTENSION)
|
||||
? name.substring(0, name.length() - LEGACY_EXTENSION.length())
|
||||
: name;
|
||||
}
|
||||
|
||||
/** Joins a folder and a name into a path. The folder may be the project root. */
|
||||
public static String resolve(String folder, String name) {
|
||||
return folder.isEmpty() ? name : folder + SEPARATOR + name;
|
||||
}
|
||||
}
|
||||
55
src/main/java/com/aranroig/listeners/EventsApi.java
Normal file
55
src/main/java/com/aranroig/listeners/EventsApi.java
Normal file
@@ -0,0 +1,55 @@
|
||||
package com.aranroig.listeners;
|
||||
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
/**
|
||||
* The {@code events} table given to user scripts for registering listeners.
|
||||
*
|
||||
* <p>Registers one {@code events.on_<name>(callback)} function per
|
||||
* {@link GameEvent} onto a script's {@link Lua} state. Calling one stores the
|
||||
* callback on the owning {@link ScriptRuntime}; it then fires whenever the game
|
||||
* event happens, until the script is rerun (which resets the runtime) or the
|
||||
* player disconnects.</p>
|
||||
*
|
||||
* <p>The argument handling mirrors {@link com.aranroig.wrapper.WorldApi}:
|
||||
* misuse returns {@code false} followed by a reason so callers can write
|
||||
* {@code if not events.on_...(...) then ... end}. A passed function value is
|
||||
* captured directly — luajava pops JFunction arguments with {@link Lua#get()},
|
||||
* which for a function yields a registry reference that stays valid while the
|
||||
* state is open, so it can be called after the script has finished running.</p>
|
||||
*/
|
||||
public final class EventsApi {
|
||||
|
||||
private EventsApi() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the global {@code events} table on the script's Lua state.
|
||||
*
|
||||
* @param lua state to register on
|
||||
* @param runtime the runtime that owns the state and stores the callbacks
|
||||
*/
|
||||
public static void register(Lua lua, ScriptRuntime runtime) {
|
||||
lua.newTable();
|
||||
int events = lua.getTop();
|
||||
|
||||
for (GameEvent event : GameEvent.values()) {
|
||||
registerOne(lua, events, runtime, event);
|
||||
}
|
||||
|
||||
lua.setGlobal("events");
|
||||
}
|
||||
|
||||
private static void registerOne(Lua lua, int table, ScriptRuntime runtime, GameEvent event) {
|
||||
String function = event.luaFunction();
|
||||
lua.push((L, args) -> {
|
||||
if (args.length < 1 || args[0].type() != Lua.LuaType.FUNCTION) {
|
||||
return new LuaValue[]{ lua.from(false), lua.from("usage: events." + function + "(callback)") };
|
||||
}
|
||||
runtime.addListener(event, args[0]);
|
||||
return new LuaValue[]{ lua.from(true) };
|
||||
});
|
||||
lua.setField(table, function);
|
||||
}
|
||||
}
|
||||
49
src/main/java/com/aranroig/listeners/GameEvent.java
Normal file
49
src/main/java/com/aranroig/listeners/GameEvent.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.aranroig.listeners;
|
||||
|
||||
/**
|
||||
* The game events a Lua script can subscribe to with the {@code events} table.
|
||||
*
|
||||
* <p>The enum name is turned into the Lua registration function by
|
||||
* {@link EventsApi}: {@link #USE_ITEM} becomes {@code events.on_use_item(fn)}
|
||||
* and is the key a callback is stored under in {@link ScriptRuntime}. Keeping
|
||||
* the names here means {@link EventsApi} (which registers the Lua functions)
|
||||
* and {@link ScriptRuntimeManager} (which fires them from Fabric hooks) cannot
|
||||
* drift apart.</p>
|
||||
*/
|
||||
public enum GameEvent {
|
||||
|
||||
/** Fires when a player right-clicks to use the item in their hand. */
|
||||
USE_ITEM("use_item"),
|
||||
|
||||
/** Fires after a player has broken a block. */
|
||||
BREAK_BLOCK("break_block"),
|
||||
|
||||
/** Fires when a player sends a chat message. */
|
||||
CHAT("chat"),
|
||||
|
||||
/** Fires when a player finishes joining the game. */
|
||||
PLAYER_JOIN("player_join"),
|
||||
|
||||
/** Fires when a player leaves the game. */
|
||||
PLAYER_LEAVE("player_leave"),
|
||||
|
||||
/** Fires once per server tick, at the end of the tick. */
|
||||
TICK("tick");
|
||||
|
||||
/** Suffix used after {@code on_} for the Lua-facing function name. */
|
||||
private final String key;
|
||||
|
||||
GameEvent(String key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
/** {@code "use_item"} for {@link #USE_ITEM}; used as the listener-map key. */
|
||||
public String key() {
|
||||
return key;
|
||||
}
|
||||
|
||||
/** The Lua function a player writes to subscribe, e.g. {@code on_use_item}. */
|
||||
public String luaFunction() {
|
||||
return "on_" + key;
|
||||
}
|
||||
}
|
||||
119
src/main/java/com/aranroig/listeners/ScriptRuntime.java
Normal file
119
src/main/java/com/aranroig/listeners/ScriptRuntime.java
Normal file
@@ -0,0 +1,119 @@
|
||||
package com.aranroig.listeners;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.chat.Component;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.value.LuaValue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.EnumMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* One running Lua script and the game-event listeners it registered.
|
||||
*
|
||||
* <p>A runtime is created fresh every time a player presses <em>Run Script</em>
|
||||
* (see {@link ScriptRuntimeManager#startRun(ServerPlayer)}) and lives until the
|
||||
* player runs the script again — which replaces it — or disconnects. It owns the
|
||||
* {@link Lua} state that {@code events.on_*(fn)} callbacks close over, so those
|
||||
* callbacks are only valid while this runtime is alive; {@link #stop()} closes
|
||||
* the state and releases them.</p>
|
||||
*
|
||||
* <h2>Why callbacks survive the script finishing</h2>
|
||||
*
|
||||
* <p>When Lua calls a Java function, luajava pops each argument with
|
||||
* {@link Lua#get()}; for a function argument that returns a registry-backed
|
||||
* {@link LuaValue} ({@code RefLuaValue}). Holding a strong Java reference to it
|
||||
* (which the listener list below does) keeps it alive, and calling it later with
|
||||
* {@link LuaValue#call(Object...)} re-pushes it from the registry and
|
||||
* {@code pcall}s it. That reference dies as soon as the {@link Lua} state is
|
||||
* closed, which is exactly the reset behaviour we want on a rerun.</p>
|
||||
*
|
||||
* <p>All methods run on the server thread — payload handling and every game
|
||||
* event this bridges are server-thread — so there is no locking.</p>
|
||||
*/
|
||||
public final class ScriptRuntime {
|
||||
|
||||
private final Lua lua;
|
||||
private final ServerPlayer owner;
|
||||
private final Map<GameEvent, List<LuaValue>> listeners = new EnumMap<>(GameEvent.class);
|
||||
|
||||
ScriptRuntime(Lua lua, ServerPlayer owner) {
|
||||
this.lua = lua;
|
||||
this.owner = owner;
|
||||
}
|
||||
|
||||
/** The Lua state to run the entrypoint on; globals are already registered. */
|
||||
public Lua lua() {
|
||||
return lua;
|
||||
}
|
||||
|
||||
/** Runs the entrypoint. Errors are left to the caller to report to the player. */
|
||||
public void run(String script) {
|
||||
lua.run(script);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers one Lua callback for an event.
|
||||
*
|
||||
* <p>The value must be a function; the caller ({@link EventsApi}) checks
|
||||
* that before handing it over. The reference is stored as-is and stays valid
|
||||
* until {@link #stop()} closes the state.</p>
|
||||
*/
|
||||
void addListener(GameEvent event, LuaValue callback) {
|
||||
listeners.computeIfAbsent(event, e -> new ArrayList<>()).add(callback);
|
||||
}
|
||||
|
||||
/** Whether any script under this runtime listens for {@code event}. */
|
||||
boolean hasListeners(GameEvent event) {
|
||||
List<LuaValue> list = listeners.get(event);
|
||||
return list != null && !list.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires every callback registered for {@code event}, passing {@code args}
|
||||
* (Java strings/numbers converted to Lua scalars) positionally.
|
||||
*
|
||||
* <p>Iterates a snapshot so a callback may itself call {@code events.on_*}
|
||||
* without disturbing this loop. A callback that throws is reported to the
|
||||
* owner and logged, and the remaining callbacks still run — one bad listener
|
||||
* never breaks the game loop or the others.</p>
|
||||
*/
|
||||
void dispatch(GameEvent event, Object... args) {
|
||||
List<LuaValue> list = listeners.get(event);
|
||||
if (list == null || list.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
for (LuaValue callback : List.copyOf(list)) {
|
||||
try {
|
||||
callback.call(args);
|
||||
} catch (Throwable t) {
|
||||
Codecraft.LOGGER.warn("Error in events." + event.luaFunction() + " callback", t);
|
||||
reportError("events." + event.luaFunction() + ": " + t.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends an error line to the owner's chat, if they are still connected. */
|
||||
void reportError(String message) {
|
||||
if (owner != null && !owner.hasDisconnected()) {
|
||||
owner.sendSystemMessage(Component.literal("§ccodecraft error: " + message));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the script: empties the listener list and closes the Lua state,
|
||||
* which invalidates every callback that was stored. Called on rerun (before
|
||||
* the replacement runtime is installed) and on disconnect.
|
||||
*/
|
||||
void stop() {
|
||||
listeners.clear();
|
||||
try {
|
||||
lua.close();
|
||||
} catch (RuntimeException e) {
|
||||
Codecraft.LOGGER.warn("Error closing Lua state", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
186
src/main/java/com/aranroig/listeners/ScriptRuntimeManager.java
Normal file
186
src/main/java/com/aranroig/listeners/ScriptRuntimeManager.java
Normal file
@@ -0,0 +1,186 @@
|
||||
package com.aranroig.listeners;
|
||||
|
||||
import com.aranroig.wrapper.ChatLogger;
|
||||
import com.aranroig.wrapper.WorldApi;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
|
||||
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
|
||||
import net.fabricmc.fabric.api.event.player.UseItemCallback;
|
||||
import net.fabricmc.fabric.api.message.v1.ServerMessageEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.network.chat.PlayerChatMessage;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.world.InteractionHand;
|
||||
import net.minecraft.world.InteractionResult;
|
||||
import net.minecraft.world.entity.player.Player;
|
||||
import net.minecraft.world.item.ItemStack;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import party.iroiro.luajava.Lua;
|
||||
import party.iroiro.luajava.luaj.LuaJ;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* The server-side owner of every running script and of the {@code events}
|
||||
* listeners they register.
|
||||
*
|
||||
* <p>There is one {@link ScriptRuntime} per player who has run the script. The
|
||||
* Fabric hooks that turn game activity into Lua callbacks are installed
|
||||
* <em>once</em>, in {@link #install()}; each hook simply dispatches to whichever
|
||||
* runtime is currently registered. That keeps reset cheap and complete:
|
||||
* {@link #startRun(ServerPlayer)} stops the player's previous runtime (closing
|
||||
* its Lua state, which drops its callbacks) and installs a fresh one, so
|
||||
* re-running the script always starts from no listeners.</p>
|
||||
*
|
||||
* <h2>Threading</h2>
|
||||
*
|
||||
* <p>All state here is touched only on the server thread: run requests arrive on
|
||||
* it, and every hooked game event (item use, block break, chat, join/leave,
|
||||
* tick) fires on it. A script's {@code Lua} state is therefore never touched
|
||||
* concurrently, and the disconnect hook is careful to drop a runtime that a
|
||||
* later dispatch might otherwise reach.</p>
|
||||
*/
|
||||
public final class ScriptRuntimeManager {
|
||||
|
||||
private static final Map<UUID, ScriptRuntime> ACTIVE = new HashMap<>();
|
||||
|
||||
private ScriptRuntimeManager() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Wires the Fabric game events to the dispatcher. Call once from
|
||||
* {@link com.aranroig.Codecraft#onInitialize()}.
|
||||
*/
|
||||
public static void install() {
|
||||
UseItemCallback.EVENT.register((player, level, hand) -> {
|
||||
onUseItem(player, hand);
|
||||
return InteractionResult.PASS;
|
||||
});
|
||||
|
||||
PlayerBlockBreakEvents.AFTER.register((level, player, pos, state, blockEntity) ->
|
||||
onBreakBlock(player, pos, state));
|
||||
|
||||
ServerMessageEvents.CHAT_MESSAGE.register((message, sender, params) ->
|
||||
onChat(sender, message));
|
||||
|
||||
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) ->
|
||||
onPlayerJoin(handler.player));
|
||||
|
||||
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> {
|
||||
onPlayerLeave(handler.player);
|
||||
// Free the leaving player's runtime; their callbacks can no longer
|
||||
// act on a disconnected owner.
|
||||
stop(handler.player);
|
||||
});
|
||||
|
||||
ServerTickEvents.END_SERVER_TICK.register(ScriptRuntimeManager::onTick);
|
||||
|
||||
// Safety net: never leave Lua states open across a server shutdown.
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register(server -> stopAll());
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces {@code player}'s running script with a brand-new runtime and
|
||||
* returns it, ready for the entrypoint to be {@linkplain ScriptRuntime#run
|
||||
* run}. Any listeners the player registered previously are dropped.
|
||||
*
|
||||
* @param player the player who pressed <em>Run Script</em>
|
||||
* @return the fresh runtime with {@code print}, {@code world} and
|
||||
* {@code events} already registered on its Lua state
|
||||
*/
|
||||
public static ScriptRuntime startRun(ServerPlayer player) {
|
||||
stop(player);
|
||||
ScriptRuntime runtime = newRuntime(player);
|
||||
ACTIVE.put(player.getUUID(), runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private static ScriptRuntime newRuntime(ServerPlayer player) {
|
||||
Lua lua = new LuaJ();
|
||||
ScriptRuntime runtime = new ScriptRuntime(lua, player);
|
||||
lua.push(ChatLogger.print(player));
|
||||
lua.setGlobal("print");
|
||||
WorldApi.register(lua, player);
|
||||
EventsApi.register(lua, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
// ── Dispatch ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void onUseItem(Player player, InteractionHand hand) {
|
||||
if (!(player instanceof ServerPlayer)) {
|
||||
return;
|
||||
}
|
||||
ItemStack stack = player.getItemInHand(hand);
|
||||
if (stack.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String item = BuiltInRegistries.ITEM.getKey(stack.getItem()).toString();
|
||||
String handName = hand == InteractionHand.OFF_HAND ? "off" : "main";
|
||||
dispatch(GameEvent.USE_ITEM, player.getScoreboardName(), item, (long) stack.getCount(), handName);
|
||||
}
|
||||
|
||||
private static void onBreakBlock(Player player, BlockPos pos, BlockState state) {
|
||||
if (!(player instanceof ServerPlayer)) {
|
||||
return;
|
||||
}
|
||||
String block = BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString();
|
||||
dispatch(GameEvent.BREAK_BLOCK, player.getScoreboardName(),
|
||||
(long) pos.getX(), (long) pos.getY(), (long) pos.getZ(), block);
|
||||
}
|
||||
|
||||
private static void onChat(ServerPlayer player, PlayerChatMessage message) {
|
||||
dispatch(GameEvent.CHAT, player.getScoreboardName(), message.signedContent());
|
||||
}
|
||||
|
||||
private static void onPlayerJoin(ServerPlayer player) {
|
||||
dispatch(GameEvent.PLAYER_JOIN, player.getScoreboardName());
|
||||
}
|
||||
|
||||
private static void onPlayerLeave(ServerPlayer player) {
|
||||
dispatch(GameEvent.PLAYER_LEAVE, player.getScoreboardName());
|
||||
}
|
||||
|
||||
private static void onTick(MinecraftServer server) {
|
||||
dispatch(GameEvent.TICK, (long) server.getTickCount());
|
||||
}
|
||||
|
||||
/**
|
||||
* Fires {@code event} on every runtime that listens for it. A runtime with
|
||||
* no listener for the event is skipped, so idle scripts cost nothing per
|
||||
* hook.
|
||||
*/
|
||||
private static void dispatch(GameEvent event, Object... args) {
|
||||
if (ACTIVE.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
// Copy values so a callback that reruns or a disconnect during the loop
|
||||
// cannot mutate the map while we iterate.
|
||||
for (ScriptRuntime runtime : Map.copyOf(ACTIVE).values()) {
|
||||
if (runtime.hasListeners(event)) {
|
||||
runtime.dispatch(event, args);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Teardown ──────────────────────────────────────────────────────────
|
||||
|
||||
private static void stop(ServerPlayer player) {
|
||||
ScriptRuntime runtime = ACTIVE.remove(player.getUUID());
|
||||
if (runtime != null) {
|
||||
runtime.stop();
|
||||
}
|
||||
}
|
||||
|
||||
private static void stopAll() {
|
||||
for (ScriptRuntime runtime : ACTIVE.values()) {
|
||||
runtime.stop();
|
||||
}
|
||||
ACTIVE.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.editor.Edit;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Someone else's edit of {@code file}, already rebased by the server. The file
|
||||
* is now at {@code version}. The player who wrote the edit does not get this:
|
||||
* their copy already has it, they get an {@link ClientboundEditAckPayload}
|
||||
* instead.
|
||||
*/
|
||||
public record ClientboundDocumentEditPayload(String file, int version, Edit edit) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier DOCUMENT_EDIT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "document_edit");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundDocumentEditPayload> TYPE = new CustomPacketPayload.Type<>(DOCUMENT_EDIT_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundDocumentEditPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundDocumentEditPayload::file,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ClientboundDocumentEditPayload::version,
|
||||
|
||||
Edit.STREAM_CODEC,
|
||||
ClientboundDocumentEditPayload::edit,
|
||||
|
||||
ClientboundDocumentEditPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* The authoritative contents of {@code file} at {@code version}. Sent in reply
|
||||
* to {@link ServerboundOpenDocumentPayload}, and again whenever the server
|
||||
* finds that a client's copy is too old to be rebased onto the live one.
|
||||
*/
|
||||
public record ClientboundDocumentStatePayload(String file, String text, int version) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier DOCUMENT_STATE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "document_state");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundDocumentStatePayload> TYPE = new CustomPacketPayload.Type<>(DOCUMENT_STATE_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundDocumentStatePayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundDocumentStatePayload::file,
|
||||
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundDocumentStatePayload::text,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ClientboundDocumentStatePayload::version,
|
||||
|
||||
ClientboundDocumentStatePayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Confirms that the server applied one of the player's own edits: the document
|
||||
* is now at {@code version}, whose contents have length {@code textLength} and
|
||||
* hash {@code textHash}. Once the player has no edits in flight any more, they
|
||||
* compare those two against their own buffer; a mismatch means the copies
|
||||
* drifted apart and the file is fetched again.
|
||||
*/
|
||||
public record ClientboundEditAckPayload(String file, int version, int textHash, int textLength) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier EDIT_ACK_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "edit_ack");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundEditAckPayload> TYPE = new CustomPacketPayload.Type<>(EDIT_ACK_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundEditAckPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundEditAckPayload::file,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ClientboundEditAckPayload::version,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ClientboundEditAckPayload::textHash,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ClientboundEditAckPayload::textLength,
|
||||
|
||||
ClientboundEditAckPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.editor.EditorPresence;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Who else has {@code file} open in their editor right now, and where their
|
||||
* carets are. Everyone with the editor open gets this for every file somebody
|
||||
* joins, leaves or moves in, minus themselves.
|
||||
*/
|
||||
public record ClientboundPresencePayload(String file, List<EditorPresence> editors) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier PRESENCE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "presence");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundPresencePayload> TYPE = new CustomPacketPayload.Type<>(PRESENCE_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundPresencePayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundPresencePayload::file,
|
||||
|
||||
EditorPresence.STREAM_CODEC.apply(ByteBufCodecs.list()),
|
||||
ClientboundPresencePayload::editors,
|
||||
|
||||
ClientboundPresencePayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Tells the client that a project file was renamed by somebody else, so its
|
||||
* name in the file list and all live-editing bookkeeping keyed by the old name
|
||||
* follow it.
|
||||
*/
|
||||
public record ClientboundRenameFilePayload(String oldName, String newName) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier RENAME_FILE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "rename_file");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundRenameFilePayload> TYPE = new CustomPacketPayload.Type<>(RENAME_FILE_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundRenameFilePayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundRenameFilePayload::oldName,
|
||||
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundRenameFilePayload::newName,
|
||||
|
||||
ClientboundRenameFilePayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* The shell is gone — it exited on its own or could not be started — and says
|
||||
* why, which the terminal pane prints as a dim note.
|
||||
*/
|
||||
public record ClientboundShellClosedPayload(String reason) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier SHELL_CLOSED_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_closed");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundShellClosedPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_CLOSED_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundShellClosedPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundShellClosedPayload::reason,
|
||||
ClientboundShellClosedPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Everything the shell printed, in order — stdout and stderr merged, line
|
||||
* endings already normalised to {@code \n}. A message can hold any number of
|
||||
* lines and can stop in the middle of one: the pane just appends it.
|
||||
*/
|
||||
public record ClientboundShellOutputPayload(String text) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier SHELL_OUTPUT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_output");
|
||||
|
||||
public static final CustomPacketPayload.Type<ClientboundShellOutputPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_OUTPUT_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundShellOutputPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ClientboundShellOutputPayload::text,
|
||||
ClientboundShellOutputPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* The player closed the editor: drop them from every live editing session, so
|
||||
* their caret disappears from everyone else's screen and their keystrokes are
|
||||
* no longer streamed to them.
|
||||
*/
|
||||
public record ServerboundCloseEditorPayload() implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier CLOSE_EDITOR_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "close_editor");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundCloseEditorPayload> TYPE = new CustomPacketPayload.Type<>(CLOSE_EDITOR_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCloseEditorPayload> CODEC =
|
||||
StreamCodec.unit(new ServerboundCloseEditorPayload());
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* The player closed the terminal pane: kill the shell it was attached to.
|
||||
* Nothing about it is saved — closing the pane means closing the shell.
|
||||
*/
|
||||
public record ServerboundCloseShellPayload() implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier CLOSE_SHELL_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "close_shell");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundCloseShellPayload> TYPE = new CustomPacketPayload.Type<>(CLOSE_SHELL_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCloseShellPayload> CODEC =
|
||||
StreamCodec.unit(new ServerboundCloseShellPayload());
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Moves the player's caret (and selection) inside {@code file}, to be shown on
|
||||
* everyone else's screen.
|
||||
*/
|
||||
public record ServerboundCursorPayload(String file, int cursor, int anchor) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier CURSOR_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "cursor");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundCursorPayload> TYPE = new CustomPacketPayload.Type<>(CURSOR_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCursorPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundCursorPayload::file,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundCursorPayload::cursor,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundCursorPayload::anchor,
|
||||
|
||||
ServerboundCursorPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.editor.Edit;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* One keystroke's worth of changes to {@code file}, made against version
|
||||
* {@code baseVersion} of it. The server rebases the edit onto the current
|
||||
* version, applies it, and hands it to everyone else editing the file.
|
||||
*/
|
||||
public record ServerboundEditPayload(String file, int baseVersion, Edit edit) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier EDIT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "edit");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundEditPayload> TYPE = new CustomPacketPayload.Type<>(EDIT_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundEditPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundEditPayload::file,
|
||||
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundEditPayload::baseVersion,
|
||||
|
||||
Edit.STREAM_CODEC,
|
||||
ServerboundEditPayload::edit,
|
||||
|
||||
ServerboundEditPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Asks the server to put the player into the live editing session of
|
||||
* {@code file} and to reply with its authoritative contents
|
||||
* ({@link ClientboundDocumentStatePayload}). Sent when the editor opens and
|
||||
* every time the player switches file; the server then streams that file's
|
||||
* edits and carets to the player.
|
||||
*/
|
||||
public record ServerboundOpenDocumentPayload(String file) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier OPEN_DOCUMENT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "open_document");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundOpenDocumentPayload> TYPE = new CustomPacketPayload.Type<>(OPEN_DOCUMENT_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundOpenDocumentPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundOpenDocumentPayload::file,
|
||||
|
||||
ServerboundOpenDocumentPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Asks the server to rename a project file: its copy in the saved project and
|
||||
* its live document move to the new name, the sessions of everyone editing it
|
||||
* follow, and the other editors are told
|
||||
* ({@link ClientboundRenameFilePayload}).
|
||||
*/
|
||||
public record ServerboundRenameFilePayload(String oldName, String newName) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier RENAME_FILE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "rename_file");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundRenameFilePayload> TYPE = new CustomPacketPayload.Type<>(RENAME_FILE_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundRenameFilePayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundRenameFilePayload::oldName,
|
||||
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundRenameFilePayload::newName,
|
||||
|
||||
ServerboundRenameFilePayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* What the terminal pane's keyboard produces, written to the pseudo-terminal
|
||||
* exactly as it is: a keystroke, a Tab, the {@code \u0003} Ctrl-C becomes, an
|
||||
* arrow key's escape sequence, a status report the emulator owes the shell.
|
||||
* On the pty those bytes are not text but signals and edits — SIGINT, an
|
||||
* echoed backspace, vim moving its cursor — so nothing here interprets them.
|
||||
*/
|
||||
public record ServerboundShellInputPayload(String bytes) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier SHELL_INPUT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_input");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundShellInputPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_INPUT_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundShellInputPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.STRING_UTF8,
|
||||
ServerboundShellInputPayload::bytes,
|
||||
ServerboundShellInputPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* The terminal pane's grid changed size. Not keystrokes — the shell's input
|
||||
* is left alone: the server resizes the pseudo-terminal itself, and the
|
||||
* kernel signals whatever runs in it the way it signals a real window's
|
||||
* resize. That is what lets a full-screen program reflow while it holds the
|
||||
* screen, which a typed {@code stty} at a prompt that is not there could
|
||||
* never do.
|
||||
*/
|
||||
public record ServerboundShellResizePayload(int rows, int cols) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier SHELL_RESIZE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_resize");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundShellResizePayload> TYPE = new CustomPacketPayload.Type<>(SHELL_RESIZE_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundShellResizePayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundShellResizePayload::rows,
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundShellResizePayload::cols,
|
||||
ServerboundShellResizePayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.aranroig.payloads;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import net.minecraft.network.RegistryFriendlyByteBuf;
|
||||
import net.minecraft.network.codec.ByteBufCodecs;
|
||||
import net.minecraft.network.codec.StreamCodec;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.resources.Identifier;
|
||||
|
||||
/**
|
||||
* Ask for a shell. The size of the terminal pane that asked comes along: a
|
||||
* terminal opens at the size of its window, and 0 means the client could not
|
||||
* tell it yet, which leaves the shell on its own defaults.
|
||||
*/
|
||||
public record ServerboundSpawnShellPayload(int rows, int cols) implements CustomPacketPayload {
|
||||
|
||||
public static final Identifier SPAWN_SHELL_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "spawn_shell");
|
||||
|
||||
public static final CustomPacketPayload.Type<ServerboundSpawnShellPayload> TYPE = new CustomPacketPayload.Type<>(SPAWN_SHELL_PAYLOAD_ID);
|
||||
|
||||
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundSpawnShellPayload> CODEC =
|
||||
StreamCodec.composite(
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundSpawnShellPayload::rows,
|
||||
ByteBufCodecs.VAR_INT,
|
||||
ServerboundSpawnShellPayload::cols,
|
||||
ServerboundSpawnShellPayload::new
|
||||
);
|
||||
|
||||
@Override
|
||||
public Type<? extends CustomPacketPayload> type() {
|
||||
return TYPE;
|
||||
}
|
||||
}
|
||||
115
src/main/java/com/aranroig/shell/ShellManager.java
Normal file
115
src/main/java/com/aranroig/shell/ShellManager.java
Normal file
@@ -0,0 +1,115 @@
|
||||
package com.aranroig.shell;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.payloads.ClientboundShellClosedPayload;
|
||||
import com.aranroig.payloads.ClientboundShellOutputPayload;
|
||||
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.server.MinecraftServer;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* The server half of the editor's terminal: at most one {@link ShellSession}
|
||||
* per player, spawned when they press the terminal button and killed when they
|
||||
* close the pane, leave, or the server stops.
|
||||
*
|
||||
* <p><b>This hands out a real shell on the machine the server runs on, to
|
||||
* anyone who can open the editor.</b> Commands run as the server's user, in
|
||||
* the server's files, with everything that implies. That is fine on a
|
||||
* single-player game or a server among friends who all get the keys to the
|
||||
* box; it is emphatically not something to leave open to strangers.</p>
|
||||
*
|
||||
* <p>Payload handlers run on the server thread, so spawning, submitting and
|
||||
* closing need no locking; only the output threads report back from outside,
|
||||
* through {@link #sessionEnded}, hence the concurrent map.</p>
|
||||
*/
|
||||
public final class ShellManager {
|
||||
|
||||
private static final Map<UUID, ShellSession> SESSIONS = new ConcurrentHashMap<>();
|
||||
|
||||
private ShellManager() {
|
||||
}
|
||||
|
||||
/** Kills every shell when its player leaves or the server goes down. */
|
||||
public static void install() {
|
||||
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> close(handler.player));
|
||||
ServerLifecycleEvents.SERVER_STOPPING.register(ShellManager::closeAll);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives {@code player} a shell, opening it at the size of the terminal
|
||||
* pane that asked ({@code rows}/{@code cols} of 0: the shell's own
|
||||
* defaults). Pressing the button with one already running does not
|
||||
* disturb it: the pane keeps its scrollback, so the same session is
|
||||
* simply attached again and told so.
|
||||
*/
|
||||
public static void spawn(ServerPlayer player, int rows, int cols) {
|
||||
ShellSession existing = SESSIONS.get(player.getUUID());
|
||||
if (existing != null && existing.isAlive()) {
|
||||
send(player, new ClientboundShellOutputPayload("shell already running — this pane is attached to it\r\n"));
|
||||
return;
|
||||
}
|
||||
if (existing != null) existing.close();
|
||||
|
||||
ShellSession session = new ShellSession(player);
|
||||
try {
|
||||
session.start(rows, cols);
|
||||
SESSIONS.put(player.getUUID(), session);
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not spawn a shell for {}", player.getName().getString(), e);
|
||||
send(player, new ClientboundShellOutputPayload("could not start a shell: " + e.getMessage() + "\r\n"));
|
||||
send(player, new ClientboundShellClosedPayload("could not start a shell"));
|
||||
}
|
||||
}
|
||||
|
||||
/** Forwards what the pane's keyboard produced, as it is, to that player's shell. */
|
||||
public static void submit(ServerPlayer player, String bytes) {
|
||||
ShellSession session = SESSIONS.get(player.getUUID());
|
||||
if (session == null || !session.isAlive()) {
|
||||
send(player, new ClientboundShellOutputPayload("no shell running — open one with the Shell button\r\n"));
|
||||
return;
|
||||
}
|
||||
session.submitInput(bytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the pty behind that player's shell to the size their terminal
|
||||
* pane now has. Nothing is said when there is no live shell to size: the
|
||||
* next spawn opens at whatever size asks anyway.
|
||||
*/
|
||||
public static void resize(ServerPlayer player, int rows, int cols) {
|
||||
ShellSession session = SESSIONS.get(player.getUUID());
|
||||
if (session != null && session.isAlive()) session.resize(rows, cols);
|
||||
}
|
||||
|
||||
/** Kills the shell a player was attached to, if they had one. */
|
||||
public static void close(ServerPlayer player) {
|
||||
ShellSession session = SESSIONS.remove(player.getUUID());
|
||||
if (session != null) session.close();
|
||||
}
|
||||
|
||||
/** Called by a session's output thread once the process is done with. */
|
||||
static void sessionEnded(ShellSession session) {
|
||||
SESSIONS.values().removeIf(alive -> alive == session);
|
||||
}
|
||||
|
||||
private static void closeAll(MinecraftServer server) {
|
||||
for (ShellSession session : SESSIONS.values()) session.close();
|
||||
SESSIONS.clear();
|
||||
}
|
||||
|
||||
private static void send(ServerPlayer player, CustomPacketPayload payload) {
|
||||
try {
|
||||
ServerPlayNetworking.send(player, payload);
|
||||
} catch (RuntimeException e) {
|
||||
// The player is leaving; nobody is there to read this.
|
||||
}
|
||||
}
|
||||
}
|
||||
535
src/main/java/com/aranroig/shell/ShellSession.java
Normal file
535
src/main/java/com/aranroig/shell/ShellSession.java
Normal file
@@ -0,0 +1,535 @@
|
||||
package com.aranroig.shell;
|
||||
|
||||
import com.aranroig.Codecraft;
|
||||
import com.aranroig.payloads.ClientboundShellClosedPayload;
|
||||
import com.aranroig.payloads.ClientboundShellOutputPayload;
|
||||
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
|
||||
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.io.Reader;
|
||||
import java.lang.ProcessBuilder.Redirect;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayDeque;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/**
|
||||
* One interactive bash session on the server, wired to one player's terminal
|
||||
* pane: what it prints is forwarded to the pane as
|
||||
* {@link ClientboundShellOutputPayload}s, and every byte the player types is
|
||||
* written to its input.
|
||||
*
|
||||
* <h2>A real terminal, not a pipe</h2>
|
||||
*
|
||||
* <p>Bash is fully interactive ({@code -i}, readline and all) and runs on a
|
||||
* pseudo-terminal allocated through {@code script} (util-linux), so everything
|
||||
* a real terminal does happens here: the tty echoes what arrives, readline
|
||||
* redraws the line while it is edited, programs see a tty — {@code tty} says
|
||||
* {@code /dev/pts/…}, {@code ls --color=auto} colours, {@code sudo} prompts,
|
||||
* {@code vim} takes over the screen — and {@code TERM} is
|
||||
* {@code xterm-256color} to match. Drawing all of that, cursor and all, is the
|
||||
* pane's job: it is the emulator, this is only the machine behind it. Where
|
||||
* {@code script} is not available, it falls back to plain non-interactive
|
||||
* bash over pipes, which still runs commands and keeps state, but without any
|
||||
* of the tty behaviours.</p>
|
||||
*
|
||||
* <p>The pane tells the shell how big the "window" is the way a real terminal
|
||||
* emulator sizes one: the pty's window is moved from out here — {@code stty}
|
||||
* run against the session's {@code /dev/pts} device, which makes the kernel
|
||||
* resize the terminal and signal the programs in the foreground that it did,
|
||||
* so a full-screen program reflows mid-resize — and nothing is ever typed
|
||||
* into the shell to say so.</p>
|
||||
*
|
||||
* <h2>Threading</h2>
|
||||
*
|
||||
* <p>The process' output is read on its own thread — a command that prints
|
||||
* for a minute must not stop the server from ticking — and handed straight to
|
||||
* the player's connection, which netty accepts from any thread. Input goes
|
||||
* the other way from the server thread, written through as it arrives.</p>
|
||||
*/
|
||||
public final class ShellSession {
|
||||
|
||||
/**
|
||||
* The shell the pseudo-terminal runs: the server user's plain interactive
|
||||
* bash, so — exactly like a terminal opened on the machine itself — it
|
||||
* sources their startup files, {@code /etc/bash.bashrc} and
|
||||
* {@code ~/.bashrc}, before the first prompt.
|
||||
*/
|
||||
private static final String SHELL_COMMAND = "bash -i";
|
||||
|
||||
/** Allocates the pty that lets bash be interactive. Tried in order. */
|
||||
private static final String[] PTY_LAUNCHERS = { "/usr/bin/script", "/bin/script", "script" };
|
||||
|
||||
/** Tried in order when no pty launcher could be started; first one that starts wins. */
|
||||
private static final String[] PLAIN_SHELLS = { "/bin/bash", "/usr/bin/bash", "bash" };
|
||||
|
||||
/**
|
||||
* Sizes the pty's window through its {@code /dev/pts} device; tried in
|
||||
* order like everything else. {@code stty} does nothing but the one ioctl
|
||||
* on its standard input, which the kernel turns into a new window size
|
||||
* and — when it changed — a SIGWINCH for the terminal's foreground group.
|
||||
*/
|
||||
private static final String[] STTY_COMMANDS = { "/bin/stty", "/usr/bin/stty", "stty" };
|
||||
|
||||
/** How long the shell may take to appear under {@code script} before the pty device search gives up. */
|
||||
private static final long PTS_SEARCH_BUDGET_MS = 5_000;
|
||||
private static final long PTS_SEARCH_RETRY_MS = 200;
|
||||
|
||||
/** How long one {@code stty} may take to size a window before it is not believed. */
|
||||
private static final long STTY_TIMEOUT_MS = 2_000;
|
||||
|
||||
/** How much of the shell's output is read — and sent — at once. */
|
||||
private static final int CHUNK_SIZE = 4096;
|
||||
|
||||
private final ServerPlayer player;
|
||||
|
||||
private Process process;
|
||||
private OutputStream stdin;
|
||||
private volatile boolean alive;
|
||||
|
||||
/** Whether the shell sits on a real pty (programs see a terminal) or on pipes. */
|
||||
private boolean interactive;
|
||||
|
||||
/** Set when we killed it ourselves, so its exit is not announced as news. */
|
||||
private volatile boolean closing;
|
||||
|
||||
/**
|
||||
* Guards the wanted and applied window sizes, and the wait between the
|
||||
* pane wanting one and the resize worker getting it: the pane's sizes
|
||||
* arrive on the server thread with its payloads, and the {@code stty}
|
||||
* runs that turn them into kernel calls must not keep the server ticking.
|
||||
*/
|
||||
private final Object resizeLock = new Object();
|
||||
|
||||
/** The size the pane last wanted, and the last one actually applied; guarded by {@link #resizeLock}. */
|
||||
private int wantRows, wantCols, appliedRows, appliedCols;
|
||||
|
||||
/** Whether the worker that applies sizes has been started; guarded by {@link #resizeLock}. */
|
||||
private boolean resizeLoopStarted;
|
||||
|
||||
/**
|
||||
* This session's {@code /dev/pts} device, found once by following the
|
||||
* process tree down from {@code script}: whoever runs under it has the
|
||||
* pty on its standard input, and the link there is the device. Written
|
||||
* only by the resize worker.
|
||||
*/
|
||||
private String ptsDevice;
|
||||
|
||||
/** Whether the device above was given up on; guarded by {@link #resizeLock}, read by the worker. */
|
||||
private boolean ptsSearchFailed;
|
||||
|
||||
ShellSession(ServerPlayer player) {
|
||||
this.player = player;
|
||||
}
|
||||
|
||||
/**
|
||||
* Spawns the shell and starts forwarding its output to the player. A
|
||||
* pseudo-terminal through {@code script} if one can be had, plain bash
|
||||
* over pipes otherwise. {@code rows}/{@code cols} (when positive) are the
|
||||
* size of the pane that asked: on the pty the window is set to them as
|
||||
* soon as its device can be found (see {@link #resize}), the same call a
|
||||
* real window resize makes; only the pipe fallback, which has no terminal
|
||||
* at all to size, is given them as {@code LINES}/{@code COLUMNS} instead.
|
||||
*
|
||||
* @throws IOException no shell could be started on this machine
|
||||
*/
|
||||
public void start(int rows, int cols) throws IOException {
|
||||
IOException lastFailure = null;
|
||||
|
||||
for (String launcher : PTY_LAUNCHERS) {
|
||||
try {
|
||||
process = ptyBuilderFor(launcher).start();
|
||||
// `script` starting is not running it: an older one that does
|
||||
// not know these options exits at once, and that is found out
|
||||
// by giving it the moment it needs, no more.
|
||||
if (startedAndStayedUp()) {
|
||||
interactive = true;
|
||||
break;
|
||||
}
|
||||
process = null;
|
||||
} catch (IOException e) {
|
||||
lastFailure = e;
|
||||
process = null;
|
||||
}
|
||||
}
|
||||
if (process == null) {
|
||||
for (String shell : PLAIN_SHELLS) {
|
||||
try {
|
||||
process = plainBuilderFor(shell, rows, cols).start();
|
||||
break;
|
||||
} catch (IOException e) {
|
||||
lastFailure = e;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (process == null) {
|
||||
throw lastFailure != null ? lastFailure
|
||||
: new IOException("no bash found on this server");
|
||||
}
|
||||
|
||||
stdin = process.getOutputStream();
|
||||
alive = true;
|
||||
Codecraft.LOGGER.info("Spawned a {} shell for {} in {}",
|
||||
interactive ? "pty-backed" : "plain",
|
||||
player.getName().getString(), System.getProperty("user.dir"));
|
||||
|
||||
// A terminal opens at the size of the window that asked: `script`
|
||||
// cannot be told, so its pty starts at the kernel's default and the
|
||||
// worker corrects it to the pane's grid a moment later, as soon as
|
||||
// the device behind it is findable — well before bash prints much.
|
||||
synchronized (resizeLock) {
|
||||
wantRows = rows;
|
||||
wantCols = cols;
|
||||
if (interactive) startResizeLoop();
|
||||
}
|
||||
|
||||
Thread.ofVirtual()
|
||||
.name("codecraft-shell-" + player.getName().getString())
|
||||
.start(this::pumpOutput);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the process made it past the moment an unusable launcher takes
|
||||
* to argue with its own command line and give up.
|
||||
*/
|
||||
private boolean startedAndStayedUp() {
|
||||
try {
|
||||
return !process.waitFor(250, TimeUnit.MILLISECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private static ProcessBuilder ptyBuilderFor(String script) {
|
||||
ProcessBuilder builder = new ProcessBuilder(
|
||||
// -q quiet, -f flush every write (output must not wait for the
|
||||
// shell to exit), -e exit with the child's code. The tty's
|
||||
// echo stays on: the pane shows what was typed exactly the
|
||||
// way it arrives back, as any terminal does, so readline can
|
||||
// redraw the line and nothing is ever shown twice.
|
||||
script, "-q", "-f", "-e",
|
||||
"-c", SHELL_COMMAND,
|
||||
// No typescript file: the scrollback in the pane is the record.
|
||||
"/dev/null");
|
||||
// A real terminal on a real tty, not the dumb one a pipe implies. The
|
||||
// prompt stays bash's own — it is part of what the pane draws. And no
|
||||
// LINES/COLUMNS in the environment: those make programs trust the
|
||||
// numbers over the terminal they are on, and the numbers here must be
|
||||
// the pty's own window, kept true by the resize machinery below.
|
||||
builder.environment().put("TERM", "xterm-256color");
|
||||
return builder;
|
||||
}
|
||||
|
||||
private static ProcessBuilder plainBuilderFor(String shell, int rows, int cols) {
|
||||
ProcessBuilder builder = new ProcessBuilder(shell, "--noediting");
|
||||
// A non-interactive bash reads no rc files at all, so BASH_ENV is the
|
||||
// way to have this path source the same ~/.bashrc (expanded by bash
|
||||
// itself, against the server process' HOME) that the pty path gets.
|
||||
builder.environment().put("BASH_ENV", "~/.bashrc");
|
||||
// Without the pty, stdout and stderr are merged here instead.
|
||||
builder.redirectErrorStream(true);
|
||||
return configurePipeEnv(builder, rows, cols);
|
||||
}
|
||||
|
||||
/** The environment of the pipe fallback: a terminal it does not really have, sized only by env. */
|
||||
private static ProcessBuilder configurePipeEnv(ProcessBuilder builder, int rows, int cols) {
|
||||
Map<String, String> env = builder.environment();
|
||||
env.put("TERM", "xterm-256color");
|
||||
// There is no terminal to size on this path, so LINES/COLUMNS are the
|
||||
// only way a program here can be told anything at all.
|
||||
if (rows > 0 && cols > 0) {
|
||||
env.put("LINES", String.valueOf(rows));
|
||||
env.put("COLUMNS", String.valueOf(cols));
|
||||
}
|
||||
return builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes what the pane typed straight to the pseudo-terminal: keystrokes,
|
||||
* tabs, Ctrl-C's {@code \u0003}, an arrow key's escape sequence, an
|
||||
* emulator's answer to a status query. Nothing is interpreted on the way —
|
||||
* on the pty those bytes are edits and signals, not text, and the shell
|
||||
* and its programs read them exactly as they would from a real terminal.
|
||||
*/
|
||||
public void submitInput(String bytes) {
|
||||
if (!alive || stdin == null) return;
|
||||
try {
|
||||
stdin.write(bytes.getBytes(StandardCharsets.UTF_8));
|
||||
stdin.flush();
|
||||
} catch (IOException e) {
|
||||
Codecraft.LOGGER.warn("Could not write to the shell of {}", player.getName().getString(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resizes the pty's window to a new size of the pane, from the outside:
|
||||
* nothing is written to the shell's input, so a full-screen program in
|
||||
* the foreground is signalled mid-run — SIGWINCH, and it redraws —
|
||||
* instead of waiting for a typed {@code stty} it would only read as
|
||||
* keystrokes. The newest size wins while an older one is still being
|
||||
* applied, so dragging a sash across the screen converges on where it
|
||||
* was let go rather than queueing a resize per frame.
|
||||
*/
|
||||
public void resize(int rows, int cols) {
|
||||
if (rows <= 0 || cols <= 0) return;
|
||||
synchronized (resizeLock) {
|
||||
if (!alive) return;
|
||||
wantRows = rows;
|
||||
wantCols = cols;
|
||||
resizeLock.notifyAll();
|
||||
if (interactive) startResizeLoop();
|
||||
}
|
||||
}
|
||||
|
||||
/** Hands the pending sizes to a worker; the caller holds {@link #resizeLock}. */
|
||||
private void startResizeLoop() {
|
||||
if (resizeLoopStarted) return;
|
||||
resizeLoopStarted = true;
|
||||
Thread.ofVirtual()
|
||||
.name("codecraft-shell-resize-" + player.getName().getString())
|
||||
.start(this::applySizes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for the pane to want a window of a different size and applies it,
|
||||
* one wanted size at a time: whatever arrived meanwhile is simply the
|
||||
* next thing asked for.
|
||||
*/
|
||||
private void applySizes() {
|
||||
while (true) {
|
||||
int rows, cols;
|
||||
synchronized (resizeLock) {
|
||||
while (alive && !sizeWantedLocked()) {
|
||||
try {
|
||||
resizeLock.wait();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!alive) return;
|
||||
rows = wantRows;
|
||||
cols = wantCols;
|
||||
}
|
||||
|
||||
applyWindowSize(rows, cols);
|
||||
synchronized (resizeLock) {
|
||||
appliedRows = rows;
|
||||
appliedCols = cols;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a real size is wanted and not applied yet; the caller holds {@link #resizeLock}. */
|
||||
private boolean sizeWantedLocked() {
|
||||
return wantRows > 0 && wantCols > 0 && (wantRows != appliedRows || wantCols != appliedCols);
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves the pty's window to {@code rows} x {@code cols} by sizing its
|
||||
* device — the same ioctl a real terminal emulator makes, and the kernel
|
||||
* signals the terminal's foreground the way it signals any resize.
|
||||
*/
|
||||
private void applyWindowSize(int rows, int cols) {
|
||||
String device = findPtsDevice();
|
||||
if (device != null && runSttyAt(device, rows, cols)) return;
|
||||
|
||||
// No device to size from — no /proc to find it, no stty to size it,
|
||||
// or it went away mid-session. Typed at the prompt is the only way
|
||||
// left to tell a size at all: echoed, blind to whatever holds the
|
||||
// screen, and the old behaviour, but better here than a window stuck
|
||||
// at whatever it was.
|
||||
Codecraft.LOGGER.warn("Could not size the pty of {}'s shell from its device; "
|
||||
+ "resizing falls back to typing at the prompt", player.getName().getString());
|
||||
ptsDevice = null;
|
||||
submitInput("export LINES=" + rows + " COLUMNS=" + cols
|
||||
+ "; stty rows " + rows + " cols " + cols + "\r");
|
||||
}
|
||||
|
||||
/** Sizes the terminal at {@code device} by handing it, as standard input, to {@code stty}. */
|
||||
private boolean runSttyAt(String device, int rows, int cols) {
|
||||
for (String stty : STTY_COMMANDS) {
|
||||
Process resized = null;
|
||||
try {
|
||||
resized = new ProcessBuilder(stty, "rows", String.valueOf(rows), "cols", String.valueOf(cols))
|
||||
.redirectInput(new File(device))
|
||||
.redirectOutput(Redirect.DISCARD)
|
||||
.redirectError(Redirect.DISCARD)
|
||||
.start();
|
||||
if (resized.waitFor(STTY_TIMEOUT_MS, TimeUnit.MILLISECONDS) && resized.exitValue() == 0) return true;
|
||||
} catch (IOException e) {
|
||||
// This stty is not here; the next one may be.
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
} finally {
|
||||
if (resized != null && resized.isAlive()) resized.destroyForcibly();
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* This session's pty device, searched for on first need and kept after.
|
||||
* The shell appears under {@code script} a moment after the spawn, so the
|
||||
* search retries quietly for a little while before giving up — from then
|
||||
* on this session is known to have no findable device.
|
||||
*/
|
||||
private String findPtsDevice() {
|
||||
synchronized (resizeLock) {
|
||||
if (ptsDevice != null) return ptsDevice;
|
||||
if (ptsSearchFailed) return null;
|
||||
}
|
||||
|
||||
long deadline = System.currentTimeMillis() + PTS_SEARCH_BUDGET_MS;
|
||||
do {
|
||||
try {
|
||||
String device = searchPtsDevice();
|
||||
ptsDevice = device;
|
||||
return device;
|
||||
} catch (IOException e) {
|
||||
try {
|
||||
Thread.sleep(PTS_SEARCH_RETRY_MS);
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
} while (alive && System.currentTimeMillis() < deadline);
|
||||
|
||||
synchronized (resizeLock) {
|
||||
ptsSearchFailed = true;
|
||||
}
|
||||
Codecraft.LOGGER.warn("No /dev/pts under {}'s shell process tree; the pty window cannot be sized from here",
|
||||
player.getName().getString());
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows the process tree down from {@code script}: whoever runs under
|
||||
* it has the pty on its standard input, and the {@code /proc} link there
|
||||
* names the device. Throws when the tree holds nobody yet, which is how
|
||||
* the search knows to look again in a moment.
|
||||
*/
|
||||
private String searchPtsDevice() throws IOException {
|
||||
ArrayDeque<Long> queue = new ArrayDeque<>();
|
||||
queue.add(process.pid());
|
||||
for (int visited = 0; !queue.isEmpty() && visited < 64; visited++) {
|
||||
for (long child : childrenOf(queue.poll())) {
|
||||
String standardInput = fdTarget(child, 0);
|
||||
if (standardInput != null && standardInput.startsWith("/dev/pts/")) return standardInput;
|
||||
queue.add(child);
|
||||
}
|
||||
}
|
||||
throw new IOException("no /dev/pts within pid " + process.pid() + "'s tree");
|
||||
}
|
||||
|
||||
/** The pids {@code pid} spawned, as {@code /proc} reports them. */
|
||||
private static List<Long> childrenOf(long pid) {
|
||||
List<Long> children = new ArrayList<>();
|
||||
try {
|
||||
String line = Files.readString(
|
||||
Path.of("/proc", Long.toString(pid), "task", Long.toString(pid), "children"));
|
||||
for (String token : line.split(" ")) {
|
||||
if (!token.isBlank()) children.add(Long.parseLong(token));
|
||||
}
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
// No /proc to ask, or the process is gone already: nobody is under there.
|
||||
}
|
||||
return children;
|
||||
}
|
||||
|
||||
/** What fd {@code fd} of {@code pid} points at, or null when {@code /proc} will not say. */
|
||||
private static String fdTarget(long pid, int fd) {
|
||||
try {
|
||||
return Files.readSymbolicLink(
|
||||
Path.of("/proc", Long.toString(pid), "fd", Integer.toString(fd))).toString();
|
||||
} catch (IOException | SecurityException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean isAlive() {
|
||||
return alive;
|
||||
}
|
||||
|
||||
/** Kills the shell; its output thread then ends by itself, quietly. */
|
||||
public void close() {
|
||||
closing = true;
|
||||
alive = false;
|
||||
synchronized (resizeLock) {
|
||||
resizeLock.notifyAll();
|
||||
}
|
||||
if (process == null) return;
|
||||
|
||||
process.destroy();
|
||||
try {
|
||||
if (!process.waitFor(500, TimeUnit.MILLISECONDS)) process.destroyForcibly();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
process.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the shell's merged output until it closes, forwarding every chunk.
|
||||
*
|
||||
* <p>Reading characters through a decoder rather than raw bytes is what
|
||||
* keeps a multibyte character that arrives split over two reads intact.
|
||||
* Nothing else is done to the stream: the pane interprets it character by
|
||||
* character — escape sequences and chunk boundaries rarely agree with each
|
||||
* other, and the emulator is built knowing that.</p>
|
||||
*/
|
||||
private void pumpOutput() {
|
||||
char[] buffer = new char[CHUNK_SIZE];
|
||||
|
||||
try (Reader output = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)) {
|
||||
int read;
|
||||
while ((read = output.read(buffer)) > 0) {
|
||||
send(new ClientboundShellOutputPayload(new String(buffer, 0, read)));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
if (!closing) {
|
||||
Codecraft.LOGGER.warn("Shell output for {} broke: {}", player.getName().getString(), e.toString());
|
||||
}
|
||||
} finally {
|
||||
alive = false;
|
||||
synchronized (resizeLock) {
|
||||
resizeLock.notifyAll();
|
||||
}
|
||||
ShellManager.sessionEnded(this);
|
||||
if (!closing) {
|
||||
int code = exitCode();
|
||||
send(new ClientboundShellClosedPayload(
|
||||
code >= 0 ? "shell exited (code " + code + ")" : "shell stopped"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int exitCode() {
|
||||
try {
|
||||
return process.exitValue();
|
||||
} catch (IllegalStateException e) {
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends one message to the player, surviving the moment they are leaving. */
|
||||
private void send(CustomPacketPayload payload) {
|
||||
try {
|
||||
ServerPlayNetworking.send(player, payload);
|
||||
} catch (RuntimeException e) {
|
||||
// The connection is gone; there is nobody left to print this to.
|
||||
}
|
||||
}
|
||||
}
|
||||
322
src/main/resources/data/codecraft/docs/lua-api.json
Normal file
322
src/main/resources/data/codecraft/docs/lua-api.json
Normal file
@@ -0,0 +1,322 @@
|
||||
{
|
||||
"topics": [
|
||||
{
|
||||
"title": "world",
|
||||
"blurb": "Read and write blocks in the running player's dimension.",
|
||||
"functions": [
|
||||
{
|
||||
"name": "world.set_block",
|
||||
"signature": "world.set_block(x, y, z, block)",
|
||||
"summary": "Places a block and updates neighbours and clients, like /setblock does.",
|
||||
"params": [
|
||||
{
|
||||
"name": "x",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world x coordinate (F3 to read your own)."
|
||||
},
|
||||
{
|
||||
"name": "y",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world y coordinate."
|
||||
},
|
||||
{
|
||||
"name": "z",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world z coordinate."
|
||||
},
|
||||
{
|
||||
"name": "block",
|
||||
"type": "string",
|
||||
"optional": false,
|
||||
"description": "Block id, with or without the minecraft: namespace, optionally with block states."
|
||||
}
|
||||
],
|
||||
"returns": "true on success, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"Coordinates are absolute, never relative to the player.",
|
||||
"A block that cannot survive where it is put (a torch without a wall, a flower without ground) drops itself again and the call reports failure.",
|
||||
"Replacing a block that holds items, such as a chest, drops its contents."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Namespace is optional; states are allowed",
|
||||
"code": "world.set_block(10, 64, -3, \"minecraft:stone\")\nworld.set_block(10, 65, -3, \"gold_block\")\nworld.set_block(10, 66, -3, \"minecraft:oak_stairs[facing=north]\")"
|
||||
},
|
||||
{
|
||||
"title": "Check whether it worked",
|
||||
"code": "local ok, reason = world.set_block(10, 64, -3, \"minecraft:stone\")\nif not ok then\n print(\"could not place the block: \" .. reason)\nend"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "world.remove_block",
|
||||
"signature": "world.remove_block(x, y, z [, drops])",
|
||||
"summary": "Removes the block at the given position.",
|
||||
"params": [
|
||||
{
|
||||
"name": "x",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world x coordinate."
|
||||
},
|
||||
{
|
||||
"name": "y",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world y coordinate."
|
||||
},
|
||||
{
|
||||
"name": "z",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world z coordinate."
|
||||
},
|
||||
{
|
||||
"name": "drops",
|
||||
"type": "boolean",
|
||||
"optional": true,
|
||||
"description": "Pass true to break the block the way a player would (items, sound, particles)."
|
||||
}
|
||||
],
|
||||
"returns": "true on success, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"Without drops the block just vanishes, silently and without items.",
|
||||
"Fails with \"there is nothing to remove\" if the target is already air."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Vanish versus break",
|
||||
"code": "world.remove_block(10, 64, -3) -- vanish\nworld.remove_block(10, 65, -3, true) -- break it, dropping items"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "world.get_block",
|
||||
"signature": "world.get_block(x, y, z)",
|
||||
"summary": "Returns the block id at that position, including its block states.",
|
||||
"params": [
|
||||
{
|
||||
"name": "x",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world x coordinate."
|
||||
},
|
||||
{
|
||||
"name": "y",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world y coordinate."
|
||||
},
|
||||
{
|
||||
"name": "z",
|
||||
"type": "number",
|
||||
"optional": false,
|
||||
"description": "Absolute world z coordinate."
|
||||
}
|
||||
],
|
||||
"returns": "The block id string (ready to hand to set_block), or nil followed by a reason string.",
|
||||
"notes": [
|
||||
"Air is the string \"minecraft:air\", and every string is truthy in Lua — compare against the id rather than testing the value.",
|
||||
"The result carries block states, e.g. minecraft:grass_block[snowy=false]."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Compare against the id, not the value",
|
||||
"code": "local block = world.get_block(10, 64, -3)\nif block ~= \"minecraft:air\" then\n print(\"something is there: \" .. block)\nend"
|
||||
},
|
||||
{
|
||||
"title": "Copy one place to another",
|
||||
"code": "local block = world.get_block(10, 64, -3)\nif block then\n world.set_block(20, 70, 5, block)\nend"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "events",
|
||||
"blurb": "Run a function when something happens in the game. Listeners keep firing after the script has finished running, and reset when the script runs again.",
|
||||
"functions": [
|
||||
{
|
||||
"name": "events.on_use_item",
|
||||
"signature": "events.on_use_item(callback)",
|
||||
"summary": "Calls callback whenever a player right-clicks to use the item in their hand.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the player name, the item id, the stack size and the hand: \"main\" or \"off\".",
|
||||
"It fires alongside the game, never instead of it: the click still does whatever it would have done.",
|
||||
"An empty hand does not fire the event.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Notice stick waves",
|
||||
"code": "events.on_use_item(function(player, item, count, hand)\n if item == \"minecraft:stick\" then\n print(player .. \" waved a stick (\" .. hand .. \" hand)\")\n end\nend)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events.on_break_block",
|
||||
"signature": "events.on_break_block(callback)",
|
||||
"summary": "Calls callback after a player has broken a block.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the player name, the x, y and z coordinates of the broken block and its block id.",
|
||||
"It fires after the block is already gone — the coordinates now hold air.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Count broken ore",
|
||||
"code": "broken = 0\nevents.on_break_block(function(player, x, y, z, block)\n if block == \"minecraft:diamond_ore\" then\n broken = broken + 1\n print(player .. \" broke a diamond ore (\" .. broken .. \" total)\")\n end\nend)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events.on_chat",
|
||||
"signature": "events.on_chat(callback)",
|
||||
"summary": "Calls callback when a player sends a chat message.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the player name and the plain text of the message.",
|
||||
"The message is still sent to chat as usual — the callback only observes it.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Reply to a keyword",
|
||||
"code": "events.on_chat(function(player, message)\n if message == \"help\" then\n print(player .. \" asked for help\")\n end\nend)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events.on_player_join",
|
||||
"signature": "events.on_player_join(callback)",
|
||||
"summary": "Calls callback when a player finishes joining the game.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the name of the player who just joined, including the running player themselves.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Welcome everyone",
|
||||
"code": "events.on_player_join(function(player)\n print(\"welcome, \" .. player .. \"!\")\nend)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events.on_player_leave",
|
||||
"signature": "events.on_player_leave(callback)",
|
||||
"summary": "Calls callback when a player leaves the game.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the name of the player who left.",
|
||||
"When the running player themselves disconnects, their script stops with them, so a script cannot outlive its owner.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Track who is online",
|
||||
"code": "events.on_player_leave(function(player)\n print(player .. \" left the game\")\nend)"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "events.on_tick",
|
||||
"signature": "events.on_tick(callback)",
|
||||
"summary": "Calls callback once per server tick, at the end of each tick.",
|
||||
"params": [
|
||||
{
|
||||
"name": "callback",
|
||||
"type": "function",
|
||||
"optional": false,
|
||||
"description": "Lua function to call every time the event happens."
|
||||
}
|
||||
],
|
||||
"returns": "true once the listener is registered, or false followed by a reason string.",
|
||||
"notes": [
|
||||
"The callback is given the tick counter, a whole number that increases by one every tick (20 ticks per second).",
|
||||
"Keep tick callbacks cheap: they run twenty times a second, and a slow one lags the whole server.",
|
||||
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Do something every five seconds",
|
||||
"code": "events.on_tick(function(tick)\n if tick % 100 == 0 then\n print(\"still running at tick \" .. tick)\n end\nend)"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"title": "print",
|
||||
"blurb": "Send text to the chat of the player running the script.",
|
||||
"functions": [
|
||||
{
|
||||
"name": "print",
|
||||
"signature": "print(...)",
|
||||
"summary": "Writes to the chat of the player who ran the script, tab-separated.",
|
||||
"params": [],
|
||||
"returns": "nothing",
|
||||
"notes": [
|
||||
"Whole numbers go through the Lua wrapper and are printed as 12.0; concatenate them into a string to drop the decimal.",
|
||||
"Runs on the server, so output appears in the running player's chat."
|
||||
],
|
||||
"examples": [
|
||||
{
|
||||
"title": "Print to chat",
|
||||
"code": "print(\"blocks placed:\", 12)"
|
||||
},
|
||||
{
|
||||
"title": "Drop the trailing .0",
|
||||
"code": "print(\"blocks placed: \" .. 12) -- -> blocks placed: 12"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
Reference in New Issue
Block a user