Shell and folders
Some checks failed
build / build (push) Failing after 1m37s

This commit is contained in:
2026-10-07 19:13:25 +02:00
parent 7a115445ab
commit 5897870725
53 changed files with 6626 additions and 450 deletions

View File

@@ -28,13 +28,14 @@ Flow: client editor → custom payloads → server → persisted project.
- **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`. - **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`.
- **Persistence** (`SavedProjectData`): a `SavedData` stored in the overworld (`saved_project_data`). Holds the list of `EditorFile`s that make up the user's project. - **Persistence** (`SavedProjectData`): a `SavedData` stored in the overworld (`saved_project_data`). Holds the list of `EditorFile`s that make up the user's project.
- **Editor UI** (`com.aranroig.client.editor`): a custom immediate-mode-ish GUI system, not vanilla widgets. `EditorScreen` routes key/mouse input to `Widget`s by hit-testing (`inside()`) and z-index. `EditorManager` owns the widgets and editor actions (save/run/etc.); `EditorFileTree`, `EditorTopBar`, `EditorFileView` are the three panels. `EditorFileView` is the actual text editor; `LuaHighlighter` tokenizes lines into colored `Span`s and `CompletionProvider` handles autocomplete. - **Editor UI** (`com.aranroig.client.editor`): a custom immediate-mode-ish GUI system, not vanilla widgets. `EditorScreen` routes key/mouse input to `Widget`s by hit-testing (`inside()`) and z-index; scrolling goes to the widget under the mouse. `EditorManager` owns the widgets and editor actions (save/run/etc.); `EditorFileTree`, `EditorTopBar`, `EditorPaneContainer` are the three panels. `EditorPaneContainer` tiles the editing area into one or more `EditorFileView` panes (split right/below from the pane headers, the View menu, or Ctrl+\ / Ctrl+Shift+\), each header naming its file; the sashes between panes drag to resize them, and the "active pane" (last pane clicked) is where files from the tree open and where saving applies. `EditorFileView` is the actual text editor; `LuaHighlighter` tokenizes lines into colored `Span`s and `CompletionProvider` handles autocomplete.
- **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload` with the entrypoint name; the server handler in `Codecraft.java` is a TODO (currently just prints). Example of embedding: `Lua l = new LuaJ(); l.register("print", Logger.print()); l.run(code);` — `com.aranroig.client.wrapper.Logger` adapts a `LuaFunction` to print into the player chat. Decide carefully whether Lua runs client- or server-side; server-side is the apparent direction. - **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload` with the entrypoint name; the server handler in `Codecraft.java` is a TODO (currently just prints). Example of embedding: `Lua l = new LuaJ(); l.register("print", Logger.print()); l.run(code);` — `com.aranroig.client.wrapper.Logger` adapts a `LuaFunction` to print into the player chat. Decide carefully whether Lua runs client- or server-side; server-side is the apparent direction.
## Conventions ## Conventions
- Use `Codecraft.id(path)` / `Identifier.fromNamespaceAndPath(MOD_ID, path)` for all ids, and the `Codecraft.LOGGER` (slf4j) instead of `System.out.println` for new logging. - Use `Codecraft.id(path)` / `Identifier.fromNamespaceAndPath(MOD_ID, path)` for all ids, and the `Codecraft.LOGGER` (slf4j) instead of `System.out.println` for new logging.
- Data classes that cross both persistence and network layers (see `EditorFile`) carry both a Mojang `Codec` and a `StreamCodec`; `RunInfo` currently only has a stream codec. - Data classes that cross both persistence and network layers (see `EditorFile`) carry both a Mojang `Codec` and a `StreamCodec`; `RunInfo` currently only has a stream codec.
- A file's name is the **path** it lives at: `lib/gui/theme`, `/`-separated, no extension. `com.aranroig.editor.ProjectPath` is the only thing that reads one; to the server and to the live-document map a name is still an opaque unique key. `EditorFileTree` groups by the folders in those names (folders exist while something is in them, and folding one is client-side view state on `EditorManager`), and `ProjectPath.ENTRYPOINT` (`main`) is what a run executes.
- Records are used for payloads/simple data; match the style of the file you're editing (entrypoint classes from the Fabric template use tabs, editor code uses 4 spaces). - Records are used for payloads/simple data; match the style of the file you're editing (entrypoint classes from the Fabric template use tabs, editor code uses 4 spaces).
- Translation keys follow `key.codecraft.*` / `key.category.codecraft.*`. - Translation keys follow `key.codecraft.*` / `key.category.codecraft.*`.
- Mixin configs: `codecraft.mixins.json` (common, package `com.aranroig.mixin`) and `codecraft.client.mixins.json` (client). `ExampleMixin` / `ExampleClientMixin` are template leftovers. - Mixin configs: `codecraft.mixins.json` (common, package `com.aranroig.mixin`) and `codecraft.client.mixins.json` (client). `ExampleMixin` / `ExampleClientMixin` are template leftovers.

View File

@@ -9,7 +9,8 @@ This same documentation is browsable in-game from the editor:
Because a script runs on the server thread from start to finish, everything it does Because a script runs on the server thread from start to finish, everything it does
happens at once and the game waits for it to finish. Loops that place millions of happens at once and the game waits for it to finish. Loops that place millions of
blocks will freeze the server, so keep them reasonable. blocks will freeze the server, so keep them reasonable. A script can also keep
listening *after* it has finished, with [events](#events).
```lua ```lua
print("hello, player!") print("hello, player!")
@@ -91,6 +92,67 @@ if block ~= "minecraft:air" then
end end
``` ```
## Events
Listeners let a script react to the game *after* it has finished running. Register one
with `events.on_<event>(callback)`; from then on the callback runs whenever the event
happens.
| Registration | Callback signature |
| ----------------------------------- | ----------------------------------------------------------- |
| `events.on_use_item(cb)` | `cb(player, item, count, hand)` |
| `events.on_break_block(cb)` | `cb(player, x, y, z, block)` |
| `events.on_chat(cb)` | `cb(player, message)` |
| `events.on_player_join(cb)` | `cb(player)` |
| `events.on_player_leave(cb)` | `cb(player)` |
| `events.on_tick(cb)` | `cb(tick)` |
`player` is always the name of the player who caused the event. Other values depend on
the event:
- **on_use_item** — fires when a player right-clicks to use the item in their hand:
`item` is the item id (`"minecraft:stick"`), `count` the stack size, and `hand`
`"main"` or `"off"`. An empty hand does not fire. The click still does whatever it
would normally do — the listener only observes it.
- **on_break_block** — fires *after* the block is broken (`x, y, z` now hold air),
with the id of the block that was there.
- **on_chat** — fires with the plain text of the message. The message is sent to chat
as usual.
- **on_player_join / on_player_leave** — fire when a player joins or leaves, including
the running player themselves.
- **on_tick** — fires at the end of every server tick with the tick counter, a whole
number that grows 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.
Callbacks run on the server thread and have the same powers as the script that
registered them — they can call `print` and the `world` functions. An error inside a
callback is printed to the owner's chat; it never stops the game or the other
listeners.
```lua
events.on_use_item(function(player, item, count, hand)
if item == "minecraft:stick" then
print(player .. " waved a stick (" .. hand .. " hand)")
end
end)
events.on_break_block(function(player, x, y, z, block)
if block == "minecraft:diamond_ore" then
print(player .. " struck diamond at " .. x .. ", " .. y .. ", " .. z)
end
end)
```
### Listening resets
Pressing **Run Script** replaces the previous run completely: all listeners from the
previous run are dropped, and only the ones the new run registers are active. If a run
registers none, the old listeners go quiet. Likewise, when the running player
disconnects their script stops with them — a script cannot outlive its owner.
If you run the same script twice, its listeners are *not* doubled — each run starts
from a clean slate.
## Examples ## Examples
A pillar four blocks tall: A pillar four blocks tall:

View File

@@ -2,8 +2,15 @@ package com.aranroig.client;
import com.aranroig.Codecraft; import com.aranroig.Codecraft;
import com.aranroig.client.editor.EditorManager; import com.aranroig.client.editor.EditorManager;
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.ClientboundProjectFilesPayload;
import com.aranroig.payloads.ClientboundRenameFilePayload;
import com.aranroig.payloads.ClientboundSaveCodePayload; import com.aranroig.payloads.ClientboundSaveCodePayload;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import com.mojang.blaze3d.platform.InputConstants; import com.mojang.blaze3d.platform.InputConstants;
import net.fabricmc.api.ClientModInitializer; import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents; import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
@@ -44,6 +51,31 @@ public class CodecraftClient implements ClientModInitializer {
ClientPlayNetworking.registerGlobalReceiver(ClientboundSaveCodePayload.TYPE, (payload, context) -> ClientPlayNetworking.registerGlobalReceiver(ClientboundSaveCodePayload.TYPE, (payload, context) ->
editorOverlay.upsertFile(payload.data())); editorOverlay.upsertFile(payload.data()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundRenameFilePayload.TYPE, (payload, context) ->
editorOverlay.applyFileRename(payload.oldName(), payload.newName()));
// Live editing: the server's copy of a file, other players' edits, the
// ack of our own, and who else is in the file with us.
ClientPlayNetworking.registerGlobalReceiver(ClientboundDocumentStatePayload.TYPE, (payload, context) ->
editorOverlay.applyDocumentState(payload.file(), payload.text(), payload.version()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundDocumentEditPayload.TYPE, (payload, context) ->
editorOverlay.applyRemoteDocumentEdit(payload.file(), payload.version(), payload.edit()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundEditAckPayload.TYPE, (payload, context) ->
editorOverlay.applyEditAck(payload.file(), payload.version(), payload.textHash(), payload.textLength()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundPresencePayload.TYPE, (payload, context) ->
editorOverlay.applyPresence(payload.file(), payload.editors()));
// The terminal pane: what the server's shell printed, and the news
// that it stopped.
ClientPlayNetworking.registerGlobalReceiver(ClientboundShellOutputPayload.TYPE, (payload, context) ->
editorOverlay.applyShellOutput(payload.text()));
ClientPlayNetworking.registerGlobalReceiver(ClientboundShellClosedPayload.TYPE, (payload, context) ->
editorOverlay.applyShellClosed(payload.reason()));
ClientTickEvents.END_CLIENT_TICK.register(client -> { ClientTickEvents.END_CLIENT_TICK.register(client -> {
while(openEditor.consumeClick()){ while(openEditor.consumeClick()){
if(client.player != null) { if(client.player != null) {

View File

@@ -8,9 +8,11 @@ import java.util.regex.Pattern;
* Generates autocomplete suggestions for Lua code given the current text * Generates autocomplete suggestions for Lua code given the current text
* buffer and cursor position. The provider combines: * buffer and cursor position. The provider combines:
* <ol> * <ol>
* <li>A static list of Lua keywords, built-in globals, and standard library members.</li> * <li>A static list of Lua keywords, built-in globals, and
* {@link LuaSnippets snippets}.</li>
* <li>Words already present in the buffer (user-defined functions/variables).</li> * <li>Words already present in the buffer (user-defined functions/variables).</li>
* <li>Library member completion after a "." or ":" trigger.</li> * <li>Library member completion after a "." or ":" trigger, backed by the
* {@link LuaLibrary} instances loaded in {@link #registerLibraries()}.</li>
* </ol> * </ol>
* *
* None of this requires a real LSP – it is "good-enough" IDE-lite completion * None of this requires a real LSP – it is "good-enough" IDE-lite completion
@@ -48,194 +50,33 @@ public class CompletionProvider {
// ── Built-in global tables (as types) ──────────────────────────── // ── Built-in global tables (as types) ────────────────────────────
for (String lib : new String[]{ for (String lib : new String[]{
"string", "table", "math", "io", "os", "coroutine", "string", "table", "math", "io", "os", "coroutine",
"package", "utf8", "debug", "_G", "_VERSION", "world" "package", "utf8", "debug", "_G", "_VERSION", "world", "events"
}) items.add(CompletionItem.type(lib)); }) items.add(CompletionItem.type(lib));
// ── Common snippets ─────────────────────────────────────────────── // ── Common snippets ───────────────────────────────────────────────
items.add(CompletionItem.snippet("fun", items.addAll(LuaSnippets.all());
"function ()\n \nend",
"anonymous function"));
items.add(CompletionItem.snippet("function",
"function name()\n \nend",
"named function"));
items.add(CompletionItem.snippet("lfun",
"local function name()\n \nend",
"local function"));
items.add(CompletionItem.snippet("if",
"if then\n \nend",
"if block"));
items.add(CompletionItem.snippet("ifel",
"if then\n \nelse\n \nend",
"if / else"));
items.add(CompletionItem.snippet("ifelseif",
"if then\n \nelseif then\n \nelse\n \nend",
"if / elseif / else"));
items.add(CompletionItem.snippet("for",
"for i = 1, do\n \nend",
"numeric for"));
items.add(CompletionItem.snippet("forin",
"for k, v in pairs() do\n \nend",
"generic for (pairs)"));
items.add(CompletionItem.snippet("fori",
"for i, v in ipairs() do\n \nend",
"generic for (ipairs)"));
items.add(CompletionItem.snippet("while",
"while do\n \nend",
"while loop"));
items.add(CompletionItem.snippet("repeat",
"repeat\n \nuntil ",
"repeat / until"));
items.add(CompletionItem.snippet("pcall",
"local ok, err = pcall(function()\n \nend)",
"protected call"));
items.add(CompletionItem.snippet("class",
"local ClassName = {}\nClassName.__index = ClassName\n\nfunction ClassName.new()\n local self = setmetatable({}, ClassName)\n return self\nend\n\nreturn ClassName",
"OOP class template"));
items.add(CompletionItem.snippet("require",
"local = require(\"\")",
"require module"));
items.add(CompletionItem.snippet("print",
"print()",
"print(…)"));
items.add(CompletionItem.snippet("setblock",
"world.set_block(, , , \"minecraft:stone\")",
"world.set_block(…)"));
items.add(CompletionItem.snippet("removeblock",
"world.remove_block(, , )",
"world.remove_block(…)"));
items.add(CompletionItem.snippet("getblock",
"local block = world.get_block(, , )",
"world.get_block(…)"));
items.add(CompletionItem.snippet("local",
"local = ",
"local variable"));
items.add(CompletionItem.snippet("return",
"return ",
"return statement"));
STATIC_ITEMS = Collections.unmodifiableList(items); STATIC_ITEMS = Collections.unmodifiableList(items);
// ── Library member tables ───────────────────────────────────────── LIBRARY_MEMBERS = Collections.unmodifiableMap(registerLibraries());
Map<String, List<CompletionItem>> libs = new LinkedHashMap<>(); }
// string.* /**
List<CompletionItem> stringLib = new ArrayList<>(); * Loads the libraries whose members are offered after a dot or colon.
for (String[] m : new String[][]{ * To expose a new codecraft-provided table in the autocomplete popup,
{"byte", "byte(", "string.byte(s [,i [,j]])"}, * implement {@link LuaLibrary} and add an instance here.
{"char", "char(", "string.char(…)"}, */
{"dump", "dump(", "string.dump(func)"}, private static Map<String, List<CompletionItem>> registerLibraries() {
{"find", "find(", "string.find(s, pattern [,init])"}, List<LuaLibrary> libraries = new ArrayList<>();
{"format", "format(", "string.format(fmt, …)"}, libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library
{"gmatch", "gmatch(", "string.gmatch(s, pattern)"}, libraries.add(new WorldLibrary()); // block access provided by codecraft
{"gsub", "gsub(", "string.gsub(s, pattern, repl)"}, libraries.add(new EventsLibrary()); // game event listeners provided by codecraft
{"len", "len(", "string.len(s)"},
{"lower", "lower(", "string.lower(s)"},
{"match", "match(", "string.match(s, pattern [,init])"},
{"rep", "rep(", "string.rep(s, n [,sep])"},
{"reverse", "reverse(", "string.reverse(s)"},
{"sub", "sub(", "string.sub(s, i [,j])"},
{"upper", "upper(", "string.upper(s)"},
}) stringLib.add(CompletionItem.method(m[0] + "(", m[1]));
libs.put("string", stringLib);
// table.* Map<String, List<CompletionItem>> members = new LinkedHashMap<>();
List<CompletionItem> tableLib = new ArrayList<>(); for (LuaLibrary library : libraries) {
for (String[] m : new String[][]{ members.put(library.name(), library.members());
{"concat", "concat(", "table.concat(t [,sep [,i [,j]]])"}, }
{"insert", "insert(", "table.insert(t [,pos], value)"}, return members;
{"move", "move(", "table.move(a1, f, e, t [,a2])"},
{"pack", "pack(", "table.pack(…)"},
{"remove", "remove(", "table.remove(t [,pos])"},
{"sort", "sort(", "table.sort(t [,comp])"},
{"unpack", "unpack(", "table.unpack(t [,i [,j]])"},
}) tableLib.add(CompletionItem.method(m[0] + "(", m[1]));
libs.put("table", tableLib);
// math.*
List<CompletionItem> mathLib = new ArrayList<>();
for (String[] m : new String[][]{
{"abs", "abs(", "math.abs(x)"},
{"ceil", "ceil(", "math.ceil(x)"},
{"cos", "cos(", "math.cos(x)"},
{"exp", "exp(", "math.exp(x)"},
{"floor", "floor(", "math.floor(x)"},
{"fmod", "fmod(", "math.fmod(x, y)"},
{"log", "log(", "math.log(x [,base])"},
{"max", "max(", "math.max(x, …)"},
{"min", "min(", "math.min(x, …)"},
{"modf", "modf(", "math.modf(x)"},
{"pow", "pow(", "math.pow(x, y)"},
{"random", "random(", "math.random([m [,n]])"},
{"randomseed", "randomseed(", "math.randomseed(x)"},
{"sin", "sin(", "math.sin(x)"},
{"sqrt", "sqrt(", "math.sqrt(x)"},
{"tan", "tan(", "math.tan(x)"},
{"tointeger", "tointeger(", "math.tointeger(x)"},
{"type", "type(", "math.type(x)"},
{"huge", "huge", "math.huge (∞)"},
{"pi", "pi", "math.pi"},
{"maxinteger", "maxinteger", "math.maxinteger"},
{"mininteger", "mininteger", "math.mininteger"},
}) mathLib.add(CompletionItem.method(m[0], m[1]));
libs.put("math", mathLib);
// io.*
List<CompletionItem> ioLib = new ArrayList<>();
for (String[] m : new String[][]{
{"close", "close(", "io.close([file])"},
{"flush", "flush()", "io.flush()"},
{"input", "input(", "io.input([file])"},
{"lines", "lines(", "io.lines([filename])"},
{"open", "open(", "io.open(filename [,mode])"},
{"output", "output(", "io.output([file])"},
{"popen", "popen(", "io.popen(prog [,mode])"},
{"read", "read(", "io.read(…)"},
{"tmpfile", "tmpfile()", "io.tmpfile()"},
{"type", "type(", "io.type(obj)"},
{"write", "write(", "io.write(…)"},
}) ioLib.add(CompletionItem.method(m[0], m[1]));
libs.put("io", ioLib);
// os.*
List<CompletionItem> osLib = new ArrayList<>();
for (String[] m : new String[][]{
{"clock", "clock()", "os.clock()"},
{"date", "date(", "os.date([format [,time]])"},
{"difftime", "difftime(", "os.difftime(t2, t1)"},
{"execute", "execute(", "os.execute([command])"},
{"exit", "exit(", "os.exit([code])"},
{"getenv", "getenv(", "os.getenv(varname)"},
{"remove", "remove(", "os.remove(filename)"},
{"rename", "rename(", "os.rename(oldname, newname)"},
{"setlocale","setlocale(","os.setlocale(locale [,category])"},
{"time", "time(", "os.time([table])"},
{"tmpname", "tmpname()", "os.tmpname()"},
}) osLib.add(CompletionItem.method(m[0], m[1]));
libs.put("os", osLib);
// coroutine.*
List<CompletionItem> coLib = new ArrayList<>();
for (String[] m : new String[][]{
{"create", "create(", "coroutine.create(f)"},
{"isyieldable", "isyieldable()", "coroutine.isyieldable()"},
{"resume", "resume(", "coroutine.resume(co [,…])"},
{"running", "running()", "coroutine.running()"},
{"status", "status(", "coroutine.status(co)"},
{"wrap", "wrap(", "coroutine.wrap(f)"},
{"yield", "yield(", "coroutine.yield(…)"},
}) coLib.add(CompletionItem.method(m[0], m[1]));
libs.put("coroutine", coLib);
// world.* — block access provided by codecraft itself
List<CompletionItem> worldLib = new ArrayList<>();
for (String[] m : new String[][]{
{"set_block", "set_block(", "world.set_block(x, y, z, \"minecraft:stone\")"},
{"remove_block", "remove_block(", "world.remove_block(x, y, z [,drops])"},
{"get_block", "get_block(", "world.get_block(x, y, z)"},
}) worldLib.add(CompletionItem.method(m[0], m[1]));
libs.put("world", worldLib);
LIBRARY_MEMBERS = Collections.unmodifiableMap(libs);
} }
// Lua identifier chars (no $ unlike Java) // Lua identifier chars (no $ unlike Java)

View File

@@ -442,7 +442,7 @@ public class EditorDocsPanel extends Widget {
// ── Input handling ──────────────────────────────────────────────────── // ── Input handling ────────────────────────────────────────────────────
@Override @Override
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (!visible) return false; if (!visible) return false;
int mx = (int) event.x(); int mx = (int) event.x();
int my = (int) event.y(); int my = (int) event.y();

View File

@@ -1,57 +1,400 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence;
import com.aranroig.editor.ProjectPath;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent; import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent; import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.util.Mth;
import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
/**
* The sidebar: the project's files, grouped into the folders their names carry.
* A folder folds away with a click on its row, a file opens with a click on its
* own, and double-clicking a file renames it where it is listed.
*/
public class EditorFileTree extends Widget { public class EditorFileTree extends Widget {
private static final int COLOR_TEXT = 0xFFFFFFFF; private static final int COLOR_TEXT = 0xFFFFFFFF;
private static final int COLOR_BACKGROUND = 0xFF202020; private static final int COLOR_BACKGROUND = 0xFF202020;
private static final int COLOR_RENAME_BG = 0xFF3A3A3A;
private static final int COLOR_ROW_OPEN = 0xFF2E2E2E;
private static final int COLOR_ROW_FOLDER = 0xFF2A3138;
// Folder amber, file paper-grey; the darker shade draws the lines of both.
private static final int COLOR_FOLDER = 0xFFC79A55;
private static final int COLOR_FOLDER_OPEN = 0xFFE8BC6E;
private static final int COLOR_FOLDER_SEAM = 0xFF8A683A;
private static final int COLOR_FILE = 0xFFA9BCCB;
private static final int COLOR_FILE_LINES = 0xFF5F7484;
private static final int COLOR_CHEVRON = 0xFFB4B4B4;
private static final int MAX_NAME_LENGTH = 64;
private static final int PADDING_X = 3;
private static final int INDENT = 8;
private static final int ICON_WIDTH = 8;
private static final int ICON_GAP = 5;
private static final int CHEVRON_WIDTH = 7;
private static final int CHEVRON_GAP = 2;
private static final int PRESENCE_GUTTER = 6;
private static final int SCROLL_STEP = 3;
// ── Icons ─────────────────────────────────────────────────────────────
// Pixel patterns rather than textures: '#' is the icon's colour, '-' a
// darker line of it, '.' nothing. They are a screen pixel each, so they stay
// sharp at any GUI scale.
private static final String[] ICON_FILE = {
".######.",
".#----#.",
".######.",
".#----#.",
".######.",
".#----#.",
".######.",
};
/** A folder: tab on the left, lid just under the top edge. */
private static final String[] ICON_FOLDER = {
"###.....",
"########",
"#------#",
"########",
".######.",
};
/** Pointing right: the folder is folded. */
private static final String[] ICON_COLLAPSED = {
"#...",
".#..",
"..#.",
"...#",
"..#.",
".#..",
"#...",
};
/** Pointing down: the folder is unfolded and what is in it is listed. */
private static final String[] ICON_EXPANDED = {
"#.....#",
".#...#.",
"..#.#..",
"...#...",
};
/** Siblings of the same folder, alphabetically whatever their case is. */
private static final Comparator<String> BY_NAME = (a, b) -> {
int order = a.compareToIgnoreCase(b);
return order != 0 ? order : a.compareTo(b);
};
public EditorFileTree(EditorManager editorManager) { public EditorFileTree(EditorManager editorManager) {
super(editorManager); super(editorManager);
} }
// ── The tree as rows ──────────────────────────────────────────────────
/**
* One line of the sidebar: a folder, or a file with its {@code file} next to
* it. {@code path} is the file's path or the folder's, and it is the key the
* fold state, the presence stripes and the rename field all work with.
* A row marked {@code creating} is the field a new folder is being typed into,
* which is drawn as a text field and stands for no file or folder of its own.
*/
private record Row(String path, String label, int depth, EditorFile file, boolean creating) {
boolean isFolder() {
return file == null;
}
}
/** What the sidebar looks like right now, top to bottom, folded folders left out. */
private List<Row> rows = List.of();
/** Pixels of content scrolled out of view at the top. */
private int scroll;
/**
* Groups the files by the folder in their name and walks that structure into
* the rows to draw: the folders of a folder first, then its files, each in
* alphabetical order. A folded folder stops the walk there, so what is hidden
* is not even a row to click on.
*/
private List<Row> buildRows() {
Map<String, List<EditorFile>> filesByFolder = new HashMap<>();
Map<String, Set<String>> childrenByFolder = new HashMap<>();
for (EditorFile file : editorManager.getFiles()) {
String folder = ProjectPath.folderOf(file.getName());
filesByFolder.computeIfAbsent(folder, key -> new ArrayList<>()).add(file);
// Register that folder with every folder above it: a folder holding
// nothing but folders is a folder all the same.
registerWithAncestors(folder, childrenByFolder);
}
// Folders made from the sidebar that nothing lives in yet: they carry no
// file to spell their path, so they are added here and read back out of
// {@link EditorManager} every rebuild, which keeps them in place across
// an editor close and open.
for (String folder : editorManager.getCustomFolders()) {
registerWithAncestors(folder, childrenByFolder);
}
rows = new ArrayList<>();
appendContents("", 0, rows, filesByFolder, childrenByFolder);
clampScroll(rows);
return rows;
}
/** Lists {@code folder} (and each folder above it) among its parent's children. */
private static void registerWithAncestors(String folder, Map<String, Set<String>> childrenByFolder) {
for (String current = folder; !current.isEmpty(); current = ProjectPath.folderOf(current)) {
childrenByFolder
.computeIfAbsent(ProjectPath.folderOf(current), key -> new TreeSet<>(BY_NAME))
.add(current);
}
}
private void appendContents(String folder, int depth, List<Row> rows,
Map<String, List<EditorFile>> filesByFolder,
Map<String, Set<String>> childrenByFolder) {
// A new folder is typed in right at the top of the folder it is being
// made in, as its first child.
if (creatingFolder && folder.equals(newFolderParent)) {
rows.add(new Row("", "", depth, null, true));
}
for (String child : childrenByFolder.getOrDefault(folder, Set.of())) {
rows.add(new Row(child, ProjectPath.displayNameOf(child), depth, null, false));
if (!editorManager.isFolderFolded(child)) {
appendContents(child, depth + 1, rows, filesByFolder, childrenByFolder);
}
}
List<EditorFile> files = filesByFolder.get(folder);
if (files == null) return;
files.sort(Comparator.comparing((EditorFile file) -> ProjectPath.displayNameOf(file.getName()), BY_NAME));
for (EditorFile file : files) {
rows.add(new Row(file.getName(), ProjectPath.displayNameOf(file.getName()), depth, file, false));
}
}
// ── Drawing ───────────────────────────────────────────────────────────
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND);
Font font = editorScreen.getFont(); Font font = editorScreen.getFont();
int lineH = font.lineHeight; int lineH = font.lineHeight;
List<EditorFile> files = editorManager.getFiles();
for(int i = 0; i < files.size(); i++) { graphics.enableScissor(getStartX(), getStartY(), getEndX(), getEndY());
graphics.text(font, files.get(i).getName(), getStartX(), getStartY() + i * lineH, COLOR_TEXT, true); int y = getStartY() - scroll;
for (Row row : buildRows()) {
if (y >= getEndY()) break; // the rest of the list is scrolled below
drawRow(graphics, font, row, y, lineH);
y += lineH;
}
graphics.disableScissor();
}
private void drawRow(GuiGraphicsExtractor graphics, Font font, Row row, int y, int lineH) {
// A new folder being named takes the whole row for itself, like a rename.
if (row.creating()) {
int textX = getStartX() + PADDING_X + INDENT * row.depth();
drawField(graphics, font, newFolderText, textX, y, lineH);
return;
}
EditorFile openFile = editorManager.getCurrentFile();
// Compared by name, not by object: the list the server sent holds its own
// copy of the file the view is editing.
boolean isOpenFile = row.file != null && openFile != null && row.file.getName().equals(openFile.getName());
if (isOpenFile) graphics.fill(getStartX(), y, getEndX(), y + lineH, COLOR_ROW_OPEN);
else if (row.isFolder() && editorManager.getSelectedFolder().equals(row.path()))
graphics.fill(getStartX(), y, getEndX(), y + lineH, COLOR_ROW_FOLDER);
// A coloured stripe beside a file means somebody else has it open.
// Up to three of them fit; more than that just keeps the first.
List<EditorPresence> editors = row.isFolder() ? List.of() : editorManager.presenceFor(row.path());
// Where the label of the row starts, worked out before anything is drawn:
// the field of a name being renamed lines up with it. The presence gutter
// is reserved for every file, edited or not, so all file names line up
// whether or not somebody has one open (an empty gutter stands in for the
// stripes). The icon always reserves it too, so the label must match.
int textX = getStartX() + PADDING_X + INDENT * row.depth();
if (!row.isFolder()) textX += PRESENCE_GUTTER;
if (row.isFolder()) textX += CHEVRON_WIDTH + CHEVRON_GAP;
textX += ICON_WIDTH + ICON_GAP;
// A name being typed takes the whole row for itself: the field covers the
// icon, so nothing is drawn under the text. Only while a rename is open —
// folder rows have no file, and null would match the null of "not
// renaming" and draw every folder as a stale text field.
if (renamingFile != null && row.file == renamingFile) {
drawField(graphics, font, renameText, textX, y, lineH);
return;
}
int x = getStartX() + PADDING_X + INDENT * row.depth();
if (row.isFolder()) {
boolean folded = editorManager.isFolderFolded(row.path());
drawIcon(graphics, folded ? ICON_COLLAPSED : ICON_EXPANDED, x, y, lineH, COLOR_CHEVRON, COLOR_CHEVRON);
x += CHEVRON_WIDTH + CHEVRON_GAP;
drawIcon(graphics, ICON_FOLDER, x, y, lineH,
folded ? COLOR_FOLDER : COLOR_FOLDER_OPEN, COLOR_FOLDER_SEAM);
} else {
for (int c = 0; c < Math.min(3, editors.size()); c++) {
graphics.fill(x + c, y + 2, x + c + 1, y + lineH - 2, editors.get(c).color());
}
x += PRESENCE_GUTTER;
drawIcon(graphics, ICON_FILE, x, y, lineH, COLOR_FILE, COLOR_FILE_LINES);
}
graphics.text(font, row.label(), textX, y, COLOR_TEXT, true);
}
/** Centres a glyph in the row and paints it pixel by pixel. */
private static void drawIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int lineH,
int colour, int lineColour) {
y += (lineH - glyph.length) / 2;
for (int row = 0; row < glyph.length; row++) {
String pixels = glyph[row];
for (int column = 0; column < pixels.length(); column++) {
char pixel = pixels.charAt(column);
if (pixel == '.') continue;
int pixelColour = pixel == '#' ? colour : lineColour;
graphics.fill(x + column, y + row, x + column + 1, y + row + 1, pixelColour);
}
} }
} }
/**
* A row turned into a text field: it fills the panel, and the caret sits at
* the end of what is typed. Used both to rename a file and to name a new
* folder, so the text is passed in rather than read from one fixed field.
*/
private void drawField(GuiGraphicsExtractor graphics, Font font, CharSequence text, int textX, int y, int lineH) {
graphics.fill(getStartX(), y, getEndX(), y + lineH, COLOR_RENAME_BG);
// As the name grows, keep its end inside the panel like a real field does.
String shown = text + "|";
int maxWidth = getEndX() - textX - 2;
int from = 0;
while (from < shown.length() - 1 && font.width(shown.substring(from)) > maxWidth) from++;
graphics.text(font, shown.substring(from), textX, y, COLOR_TEXT, false);
}
// ── Input ─────────────────────────────────────────────────────────────
@Override @Override
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
if (renamingFile != null) {
switch (event.key()) {
case 256 -> renamingFile = null; // Escape — discard the rename
case 257 -> commitRename(); // Enter
case 259 -> { // Backspace
if (!renameText.isEmpty()) renameText.deleteCharAt(renameText.length() - 1);
}
}
// While a name is being typed, every key belongs to the name field.
return true;
}
if (creatingFolder) {
switch (event.key()) {
case 256 -> creatingFolder = false; // Escape — discard the folder
case 257 -> commitNewFolder(); // Enter
case 259 -> { // Backspace
if (!newFolderText.isEmpty()) newFolderText.deleteCharAt(newFolderText.length() - 1);
}
}
return true;
}
return false; return false;
} }
@Override @Override
public boolean handleCharTyped(CharacterEvent event) { public boolean handleCharTyped(CharacterEvent event) {
return false; StringBuilder into = renamingFile != null ? renameText : (creatingFolder ? newFolderText : null);
if (into == null) return false;
int codePoint = event.codepoint();
// Printable characters go into the name. A '/' goes in too: it names the
// folders to nest inside, which is how a folder comes to exist.
if (codePoint >= 32 && codePoint != 127 && codePoint != '\\'
&& into.length() < MAX_NAME_LENGTH) {
into.appendCodePoint(codePoint);
}
return true;
} }
@Override @Override
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
Font font = editorScreen.getFont(); // Clicking anything applies the name being typed first, and that click is
int index = (int) ((event.y() - getStartY()) / font.lineHeight); // spent on applying it: like a file explorer, one click closes the field
List<EditorFile> files = editorManager.getFiles(); // and the next one opens whatever is under the mouse.
if (renamingFile != null) {
if (index >= 0 && index < files.size()) { commitRename();
editorManager.openFile(files.get(index));
return true; return true;
} }
return false; if (creatingFolder) {
commitNewFolder();
return true;
}
Font font = editorScreen.getFont();
int index = (int) ((event.y() - getStartY() + scroll) / font.lineHeight);
if (event.y() < getStartY() || index < 0 || index >= rows.size()) return false;
Row row = rows.get(index);
if (row.isFolder()) {
// Where new files go, and which folder is being talked about: the
// click that says so also folds it or unfolds it.
editorManager.setSelectedFolder(row.path());
editorManager.toggleFolderFolded(row.path());
return true;
}
editorManager.setSelectedFolder(ProjectPath.folderOf(row.path()));
if (doubleClick) {
startRename(row.file());
return true;
}
editorManager.openFile(row.file());
return true;
}
@Override
public void handleFocusLost() {
if (renamingFile != null) commitRename();
if (creatingFolder) commitNewFolder();
} }
@Override @Override
@@ -66,6 +409,152 @@ public class EditorFileTree extends Widget {
@Override @Override
public boolean handleMouseScrolled(double scrollY) { public boolean handleMouseScrolled(double scrollY) {
int content = rows.size() * editorScreen.getFont().lineHeight;
int visible = getEndY() - getStartY();
if (content <= visible) return false;
scroll = Mth.clamp((int) (scroll - scrollY * SCROLL_STEP), 0, content - visible);
return true;
}
/** Stops the list from being scrolled past either end after the files changed. */
private void clampScroll(List<Row> rows) {
int content = rows.size() * editorScreen.getFont().lineHeight;
scroll = Mth.clamp(scroll, 0, Math.max(0, content - (getEndY() - getStartY())));
}
// ── Inline rename ─────────────────────────────────────────────────────
// Double-click a file to rename it right where it is listed: what is typed
// replaces its name. Enter or clicking anywhere applies it, like a file
// explorer applying on focus loss; Escape discards it.
//
// What is typed is a path, so it also says where the file ends up: that is
// how a folder is made, since a folder is nothing but files whose name runs
// through it.
/** The file whose name is being edited right now (null = not renaming). */
private EditorFile renamingFile;
private StringBuilder renameText = new StringBuilder();
private void startRename(EditorFile file) {
renamingFile = file;
renameText = new StringBuilder(ProjectPath.displayNameOf(file.getName()));
}
private void commitRename() {
EditorFile file = renamingFile;
renamingFile = null;
// Only a file still in the project can be renamed: if the list was
// refreshed from the server meanwhile, what is typed simply goes away.
if (file == null || !editorManager.getFiles().contains(file)) return;
String typed = renameText.toString().trim();
if (typed.isEmpty()) return;
// A leading '/' counts from the root of the project, anything else from
// the folder the file is in. A trailing one keeps the name and only moves
// the file into the folders in front of it, and doubled slashes read as
// one. So `lib/net` moves `main` to `lib/main`.
String folder = typed.startsWith("/") ? "" : ProjectPath.folderOf(file.getName());
if (typed.endsWith("/")) typed += ProjectPath.displayNameOf(file.getName());
String newName = resolveSegments(folder, typed);
if (newName.isEmpty()) return;
editorManager.renameFile(file, newName);
// The file the player just moved or named stays where they can see it,
// even when it landed in a folder that was folded.
editorManager.unfoldFolder(ProjectPath.folderOf(newName));
}
/**
* Joins what was typed onto {@code folder} into one clean path: empty pieces
* (leading, doubled or trailing slashes) drop out, and {@code folder} may be
* the project root. Returns the empty string when nothing is left to name.
*/
private static String resolveSegments(String folder, String typed) {
StringBuilder path = new StringBuilder();
for (String segment : typed.split("/")) {
String trimmed = segment.trim();
if (trimmed.isEmpty()) continue;
if (!path.isEmpty()) path.append(ProjectPath.SEPARATOR);
path.append(trimmed);
}
return path.isEmpty() ? "" : ProjectPath.resolve(folder, path.toString());
}
// ── New folders ───────────────────────────────────────────────────────
// A folder is a folder whether or not anything lives in it, but the project
// only stores file paths — an empty folder has no file to spell its name with.
// So a folder made from the sidebar is kept as this player's view of the
// project, alongside the fold state, and reads back into the tree every
// rebuild. Once a file lands in it the path carries the folder on its own.
/** True while a new folder is being named in the sidebar. */
private boolean creatingFolder;
/** The folder the new one is being made inside ("" = the project root). */
private String newFolderParent = "";
private StringBuilder newFolderText = new StringBuilder();
/**
* Opens a field for a new folder inside the folder the sidebar has picked
* (the project root when none is). It is prefilled with a name the project
* does not use yet, and every folder above that one is unfolded so the field
* is not drawn hidden inside a folded parent.
*/
public void startNewFolder() {
renamingFile = null;
creatingFolder = true;
newFolderParent = editorManager.getSelectedFolder();
for (String folder = newFolderParent; !folder.isEmpty(); folder = ProjectPath.folderOf(folder)) {
editorManager.unfoldFolder(folder);
}
newFolderText = new StringBuilder(uniqueFolderName(newFolderParent));
}
/** A leaf name for a new folder inside {@code parent} that nobody has taken. */
private String uniqueFolderName(String parent) {
String path = ProjectPath.resolve(parent, "new-folder");
for (int i = 2; folderTaken(path); i++) {
path = ProjectPath.resolve(parent, "new-folder-" + i);
}
return ProjectPath.displayNameOf(path);
}
/** Whether {@code path} already names a folder, or a file lives in it. */
private boolean folderTaken(String path) {
if (editorManager.getCustomFolders().contains(path)) return true;
String inside = path + ProjectPath.SEPARATOR;
for (EditorFile file : editorManager.getFiles()) {
if (ProjectPath.folderOf(file.getName()).equals(path) || file.getName().startsWith(inside)) return true;
}
for (String folder : editorManager.getCustomFolders()) {
if (folder.startsWith(inside)) return true;
}
return false; return false;
} }
private void commitNewFolder() {
creatingFolder = false;
String typed = newFolderText.toString().trim();
if (typed.isEmpty()) return;
// A leading '/' names from the root; anything else nests inside the folder
// that was picked.
String folder = typed.startsWith("/") ? "" : newFolderParent;
String path = resolveSegments(folder, typed);
if (path.isEmpty()) return;
editorManager.createFolder(path);
// The new folder is where new files go, and it is shown open. Naming one
// that already exists just points at it: the tree keeps no duplicates.
editorManager.setSelectedFolder(path);
editorManager.unfoldFolder(path);
}
} }

View File

@@ -1,8 +1,8 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.payloads.ServerboundSaveCodePayload; import com.aranroig.editor.EditorPresence;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.GuiGraphicsExtractor;
@@ -14,7 +14,7 @@ import org.jspecify.annotations.NonNull;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
public class EditorFileView extends Widget { public class EditorFileView extends EditorPane {
private StringBuilder text = new StringBuilder(); private StringBuilder text = new StringBuilder();
@@ -29,6 +29,13 @@ public class EditorFileView extends Widget {
super(editorManager); super(editorManager);
} }
/** The header shows the name of the file this pane is editing. */
@Override
public String paneTitle() {
EditorFile file = getCurrentEditorFile();
return file == null ? "(no file)" : file.getName();
}
// ── Scroll state ────────────────────────────────────────────────────── // ── Scroll state ──────────────────────────────────────────────────────
private int scrollX = 0; private int scrollX = 0;
private int scrollY = 0; private int scrollY = 0;
@@ -45,6 +52,7 @@ public class EditorFileView extends Widget {
// ── Colors ──────────────────────────────────────────────────────────── // ── Colors ────────────────────────────────────────────────────────────
private static final int COLOR_TEXT = 0xFFFFFFFF; private static final int COLOR_TEXT = 0xFFFFFFFF;
private static final int COLOR_CURSOR = 0xFFFFFFFF; private static final int COLOR_CURSOR = 0xFFFFFFFF;
private static final int COLOR_CURSOR_DIM = 0x66FFFFFF;
private static final int COLOR_SELECTION = 0x664466FF; private static final int COLOR_SELECTION = 0x664466FF;
private static final int COLOR_GUTTER_BG = 0xFF252525; private static final int COLOR_GUTTER_BG = 0xFF252525;
private static final int COLOR_GUTTER_TEXT = 0xFF888888; private static final int COLOR_GUTTER_TEXT = 0xFF888888;
@@ -198,11 +206,88 @@ public class EditorFileView extends Widget {
if (selectionAnchor < 0) return; if (selectionAnchor < 0) return;
int lo = Math.min(selectionAnchor, cursorPos); int lo = Math.min(selectionAnchor, cursorPos);
int hi = Math.max(selectionAnchor, cursorPos); int hi = Math.max(selectionAnchor, cursorPos);
text.delete(lo, hi); applyLocalEdit(lo, hi - lo, "");
cursorPos = lo; cursorPos = lo;
selectionAnchor = -1; selectionAnchor = -1;
} }
// ── Live editing ──────────────────────────────────────────────────────
/**
* The only place the buffer changes because the local player asked for it:
* applies the change here and reports it to {@link EditorManager}, which
* forwards it to the server so everyone else editing this file sees it.
* Every keystroke goes through this, so the shared copy of the file stays
* complete without waiting for a save.
*/
private void applyLocalEdit(int position, int deleteLength, String insert) {
int start = Math.max(0, Math.min(position, text.length()));
int end = Math.max(start, Math.min(start + deleteLength, text.length()));
text.replace(start, end, insert);
if (currentEditorFile != null) {
editorManager.submitEdit(currentEditorFile, text.toString(), start, end - start, insert);
}
}
/**
* Applies an edit another player made to this pane's file. The edit is
* already merged with the edits of our own that were still in flight (see
* {@link EditorManager#applyRemoteDocumentEdit}); our caret and selection
* ride along with the text around them so typing next to someone does not
* yank the caret away. The same merged edit may land in several panes at
* once when the same file is open twice.
*/
public void applyIntegratedRemoteEdit(Edit edit) {
if (edit.baseLength() > text.length() + 1) {
// The edit reaches past the end of our copy: the two documents have
// drifted apart. Ask for the real text.
editorManager.requestDocumentSync(currentEditorFile);
}
int newCursor = edit.shiftPosition(cursorPos);
if (selectionAnchor >= 0) selectionAnchor = edit.shiftPosition(selectionAnchor);
text = new StringBuilder(edit.apply(text.toString()));
cursorPos = Math.min(newCursor, text.length());
if (selectionAnchor > text.length()) selectionAnchor = text.length();
dismissCompletions();
}
/**
* Whether the buffer still matches what the server says the file holds, as
* reported by an edit ack. A mismatch means our merge went wrong somewhere,
* and the answer is to take the server's copy rather than keep diverging.
*/
public boolean matchesServerText(int textHash, int textLength) {
return text.length() == textLength && text.toString().hashCode() == textHash;
}
/** True when {@code name} is the file currently open in this view. */
public boolean isEditing(String name) {
return currentEditorFile != null && currentEditorFile.getName().equals(name);
}
/**
* Adopts the server's copy of the open file, keeping the caret as close to
* where it was as the new text allows.
*/
public void loadServerText(String serverText) {
text = new StringBuilder(serverText);
cursorPos = Math.min(cursorPos, text.length());
if (selectionAnchor > text.length()) selectionAnchor = text.length();
if (currentEditorFile != null) currentEditorFile.setText(serverText);
dismissCompletions();
}
/** Who else has this file open, and where their carets are. */
private List<EditorPresence> remoteEditors = Collections.emptyList();
public void setRemoteEditors(List<EditorPresence> editors) {
remoteEditors = editors;
}
// ── Autocomplete helpers ────────────────────────────────────────────── // ── Autocomplete helpers ──────────────────────────────────────────────
/** Refresh the completion list after every text or cursor change. */ /** Refresh the completion list after every text or cursor change. */
@@ -231,7 +316,7 @@ public class EditorFileView extends Widget {
String prefix = completionProvider.extractPrefix(text.toString(), cursorPos); String prefix = completionProvider.extractPrefix(text.toString(), cursorPos);
int prefixStart = cursorPos - prefix.length(); int prefixStart = cursorPos - prefix.length();
text.replace(prefixStart, cursorPos, item.insert()); applyLocalEdit(prefixStart, cursorPos - prefixStart, item.insert());
cursorPos = prefixStart + item.insert().length(); cursorPos = prefixStart + item.insert().length();
selectionAnchor = -1; selectionAnchor = -1;
dismissCompletions(); dismissCompletions();
@@ -359,28 +444,16 @@ public class EditorFileView extends Widget {
int firstLine = Math.max(0, scrollY / lineH); int firstLine = Math.max(0, scrollY / lineH);
int lastLine = Math.min(lines.length - 1, (scrollY + textAreaHeight()) / lineH + 1); int lastLine = Math.min(lines.length - 1, (scrollY + textAreaHeight()) / lineH + 1);
// Selection highlight // Selection highlight: ours, then everybody else's in their own colour
if (hasSelection()) { if (hasSelection()) {
int lo = Math.min(selectionAnchor, cursorPos); drawSelection(graphics, lines, lineH, firstLine, lastLine, end_x,
int hi = Math.max(selectionAnchor, cursorPos); Math.min(selectionAnchor, cursorPos), Math.max(selectionAnchor, cursorPos), COLOR_SELECTION);
}
int[] loLC = offsetToLineCol(lo); for (EditorPresence editor : remoteEditors) {
int[] hiLC = offsetToLineCol(hi); if (!editor.hasSelection()) continue;
drawSelection(graphics, lines, lineH, firstLine, lastLine, end_x,
for (int ln = Math.max(loLC[0], firstLine); ln <= Math.min(hiLC[0], lastLine); ln++) { Math.min(editor.cursor(), editor.anchor()), Math.max(editor.cursor(), editor.anchor()),
String lineText = lines[ln]; transparent(editor.color(), 0x4D));
int colStart = (ln == loLC[0]) ? loLC[1] : 0;
int colEnd = (ln == hiLC[0]) ? hiLC[1] : lineText.length();
int x0 = textAreaX() + widthUpTo(lineText, colStart) - scrollX;
int x1 = textAreaX() + widthUpTo(lineText, colEnd) - scrollX;
if (x1 == x0) x1 = x0 + 2;
x0 = Math.max(x0, textAreaX());
x1 = Math.min(x1, end_x);
int screenY = start_y + ln * lineH - scrollY;
graphics.fill(x0, screenY, x1, screenY + lineH, COLOR_SELECTION);
}
} }
// Line numbers + text // Line numbers + text
@@ -397,9 +470,15 @@ public class EditorFileView extends Widget {
drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline); drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline);
} }
// Blinking cursor // Other players' carets in this file, each in the colour the server gave them
boolean showCursor = (System.currentTimeMillis() / 500) % 2 == 0; for (EditorPresence editor : remoteEditors) {
if (showCursor) { drawRemoteCaret(graphics, lines, lineH, start_y, end_y, editor);
}
// Caret: blinking in the pane holding the keyboard, a dim line in the
// others, so several panes make it clear which one typing goes to.
boolean focusedPane = editorScreen.selectedWidget == this;
if (currentEditorFile != null && (focusedPane ? (System.currentTimeMillis() / 500) % 2 == 0 : true)) {
int[] lc = offsetToLineCol(cursorPos); int[] lc = offsetToLineCol(cursorPos);
int ln = lc[0]; int ln = lc[0];
int col = lc[1]; int col = lc[1];
@@ -411,7 +490,8 @@ public class EditorFileView extends Widget {
int cursorY = start_y + ln * lineH - scrollY; int cursorY = start_y + ln * lineH - scrollY;
if (cursorX >= textAreaX() && cursorX <= end_x) { if (cursorX >= textAreaX() && cursorX <= end_x) {
graphics.fill(cursorX, cursorY, cursorX + 1, cursorY + lineH, COLOR_CURSOR); graphics.fill(cursorX, cursorY, cursorX + 1, cursorY + lineH,
focusedPane ? COLOR_CURSOR : COLOR_CURSOR_DIM);
} }
} }
@@ -421,6 +501,65 @@ public class EditorFileView extends Widget {
if (isPopupVisible()) { if (isPopupVisible()) {
drawCompletionPopup(graphics, mouseX, mouseY); drawCompletionPopup(graphics, mouseX, mouseY);
} }
// Let everyone else know where our caret ended up.
sendCursorIfMoved();
}
/** Tints the [lo, hi) range of the buffer, clipped to the visible lines. */
private void drawSelection(GuiGraphicsExtractor graphics, String[] lines, int lineH,
int firstLine, int lastLine, int end_x, int lo, int hi, int color) {
int[] loLC = offsetToLineCol(lo);
int[] hiLC = offsetToLineCol(hi);
for (int ln = Math.max(loLC[0], firstLine); ln <= Math.min(hiLC[0], lastLine); ln++) {
String lineText = lines[ln];
int colStart = (ln == loLC[0]) ? loLC[1] : 0;
int colEnd = (ln == hiLC[0]) ? hiLC[1] : lineText.length();
int x0 = textAreaX() + widthUpTo(lineText, colStart) - scrollX;
int x1 = textAreaX() + widthUpTo(lineText, colEnd) - scrollX;
if (x1 == x0) x1 = x0 + 2;
x0 = Math.max(x0, textAreaX());
x1 = Math.min(x1, end_x);
int screenY = getStartY() + ln * lineH - scrollY;
graphics.fill(x0, screenY, x1, screenY + lineH, color);
}
}
/**
* Draws one remote player's caret, in the colour the server assigned them,
* with their name next to it so several people in the same file are
* distinguishable. Anything outside the text area is clipped by the scissor
* the widget already has on.
*/
private void drawRemoteCaret(GuiGraphicsExtractor graphics, String[] lines, int lineH,
int start_y, int end_y, EditorPresence editor) {
int[] lc = offsetToLineCol(editor.cursor());
int ln = Math.min(lc[0], lines.length - 1);
String lineText = lines[ln];
int x = textAreaX() + widthUpTo(lineText, Math.min(lc[1], lineText.length())) - scrollX;
int y = start_y + ln * lineH - scrollY;
if (y + lineH < start_y || y > end_y) return; // scrolled out of sight
graphics.fill(x, y, x + 1, y + lineH, editor.color());
String name = editor.name();
int nameW = font.width(name);
int tagX = Math.max(textAreaX(), Math.min(x - 1, getEndX() - nameW - 5));
int tagY = y - font.lineHeight - 2;
if (tagY < start_y) tagY = Math.min(y + lineH + 1, end_y - font.lineHeight - 2);
graphics.fill(tagX, tagY, tagX + nameW + 5, tagY + font.lineHeight + 2, 0xC0000000);
graphics.fill(tagX, tagY, tagX + 2, tagY + font.lineHeight + 2, editor.color());
graphics.text(font, name, tagX + 4, tagY + 1, 0xFFFFFFFF, false);
}
/** Same colour, with a given alpha instead of opaque. */
private static int transparent(int rgb, int alpha) {
return (alpha << 24) | (rgb & 0x00FFFFFF);
} }
private void drawCompletionPopup(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) { private void drawCompletionPopup(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
@@ -510,7 +649,10 @@ public class EditorFileView extends Widget {
// ── Input handlers ──────────────────────────────────────────────────── // ── Input handlers ────────────────────────────────────────────────────
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
// The pane under the click is the one being worked in from now on.
editorManager.setActivePane(this);
// Check if clicking inside the popup // Check if clicking inside the popup
if (isPopupVisible()) { if (isPopupVisible()) {
int[] origin = popupOrigin(); int[] origin = popupOrigin();
@@ -567,11 +709,19 @@ public class EditorFileView extends Widget {
return true; return true;
} }
/** Clicking another pane takes the keyboard: nothing to complete here any more. */
@Override
public void handleFocusLost() {
dismissCompletions();
}
public boolean handleCharTyped(CharacterEvent event) { public boolean handleCharTyped(CharacterEvent event) {
if (currentEditorFile == null) return false; // an empty pane holds nothing to type into
int codePoint = event.codepoint(); int codePoint = event.codepoint();
if (codePoint >= 32 && codePoint != 127) { if (codePoint >= 32 && codePoint != 127) {
if (hasSelection()) deleteSelection(); if (hasSelection()) deleteSelection();
text.insert(cursorPos, Character.toString(codePoint)); applyLocalEdit(cursorPos, 0, Character.toString(codePoint));
cursorPos += Character.charCount(codePoint); cursorPos += Character.charCount(codePoint);
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
@@ -588,6 +738,10 @@ public class EditorFileView extends Widget {
} }
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
// An empty pane holds nothing to edit; the screen keeps its keys
// (Escape still closes it).
if (currentEditorFile == null) return false;
int key = event.key(); int key = event.key();
boolean shift = event.hasShiftDown(); boolean shift = event.hasShiftDown();
boolean ctrl = event.hasControlDown(); boolean ctrl = event.hasControlDown();
@@ -624,7 +778,7 @@ public class EditorFileView extends Widget {
switch (key) { switch (key) {
case 257 -> { // Enter case 257 -> { // Enter
if (hasSelection()) deleteSelection(); if (hasSelection()) deleteSelection();
text.insert(cursorPos, '\n'); applyLocalEdit(cursorPos, 0, "\n");
cursorPos++; cursorPos++;
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
@@ -633,7 +787,7 @@ public class EditorFileView extends Widget {
} }
case 258 -> { // Tab (no popup) case 258 -> { // Tab (no popup)
if (hasSelection()) deleteSelection(); if (hasSelection()) deleteSelection();
text.insert(cursorPos, '\t'); applyLocalEdit(cursorPos, 0, "\t");
cursorPos++; cursorPos++;
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
@@ -642,7 +796,7 @@ public class EditorFileView extends Widget {
} }
case 259 -> { // Backspace case 259 -> { // Backspace
if (hasSelection()) { deleteSelection(); } if (hasSelection()) { deleteSelection(); }
else if (cursorPos > 0) { text.deleteCharAt(--cursorPos); } else if (cursorPos > 0) { applyLocalEdit(cursorPos - 1, 1, ""); cursorPos--; }
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
updateCompletions(); // re-compute after deletion updateCompletions(); // re-compute after deletion
@@ -650,7 +804,7 @@ public class EditorFileView extends Widget {
} }
case 261 -> { // Delete case 261 -> { // Delete
if (hasSelection()) { deleteSelection(); } if (hasSelection()) { deleteSelection(); }
else if (cursorPos < text.length()) { text.deleteCharAt(cursorPos); } else if (cursorPos < text.length()) { applyLocalEdit(cursorPos, 1, ""); }
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
updateCompletions(); updateCompletions();
@@ -753,7 +907,7 @@ public class EditorFileView extends Widget {
if (ctrl) { if (ctrl) {
if (hasSelection()) deleteSelection(); if (hasSelection()) deleteSelection();
String clip = minecraft.keyboardHandler.getClipboard(); String clip = minecraft.keyboardHandler.getClipboard();
text.insert(cursorPos, clip); applyLocalEdit(cursorPos, 0, clip);
cursorPos += clip.length(); cursorPos += clip.length();
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
@@ -764,6 +918,13 @@ public class EditorFileView extends Widget {
case 83 -> { // Ctrl+S case 83 -> { // Ctrl+S
saveEditorFile(); saveEditorFile();
} }
case 92 -> { // Ctrl+\ splits the area right; Ctrl+Shift+\ splits below
if (ctrl) {
if (shift) editorManager.splitBelow();
else editorManager.splitRight();
return true;
}
}
case 291 -> { // F1 — open the docs on the word under the cursor case 291 -> { // F1 — open the docs on the word under the cursor
editorManager.openDocsAt(wordUnderCursor()); editorManager.openDocsAt(wordUnderCursor());
return true; return true;
@@ -802,9 +963,68 @@ public class EditorFileView extends Widget {
} }
public void setEditorFile(EditorFile currentEditorFile) { public void setEditorFile(EditorFile currentEditorFile) {
boolean sameFile = this.currentEditorFile != null
&& this.currentEditorFile.getName().equals(currentEditorFile.getName());
this.currentEditorFile = currentEditorFile; this.currentEditorFile = currentEditorFile;
text = new StringBuilder(currentEditorFile.getText()); text = new StringBuilder(currentEditorFile.getText());
dismissCompletions(); dismissCompletions();
if (!sameFile) {
// Caret and scroll belonged to the file we just left.
cursorPos = 0;
selectionAnchor = -1;
scrollX = 0;
scrollY = 0;
}
// Join this file's live session (and re-show who is in it).
editorManager.onDocumentOpened(this, currentEditorFile);
}
/**
* Empties this pane: it shows no file and holds nothing to edit. Used when
* its pane is closed; the file itself stays in the project and in any other
* pane showing it.
*/
public void clearFile() {
currentEditorFile = null;
text = new StringBuilder();
cursorPos = 0;
selectionAnchor = -1;
scrollX = 0;
scrollY = 0;
remoteEditors = Collections.emptyList();
dismissCompletions();
}
// ── Presence ──────────────────────────────────────────────────────────
/** Caret and selection as last reported to the server, and when that was. */
private int sentCursor = Integer.MIN_VALUE;
private int sentAnchor = Integer.MIN_VALUE;
private long lastCursorSent;
/** Roughly 16 caret updates a second; dragging selects far more often than that. */
private static final long CURSOR_SEND_INTERVAL_MS = 60;
/**
* Reports our caret to the other editors, coalescing the burst of moves a
* drag-select produces. Only the change that is on screen at the end of the
* interval is worth sending.
*/
private void sendCursorIfMoved() {
if (currentEditorFile == null) return;
if (cursorPos == sentCursor && selectionAnchor == sentAnchor) return;
long now = System.currentTimeMillis();
if (now - lastCursorSent < CURSOR_SEND_INTERVAL_MS) return;
sentCursor = cursorPos;
sentAnchor = selectionAnchor;
lastCursorSent = now;
editorManager.sendCursor(currentEditorFile.getName(), cursorPos, selectionAnchor);
} }
public void saveEditorFile() { public void saveEditorFile() {

View File

@@ -1,19 +1,36 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.SavedProjectData; import com.aranroig.Codecraft;
import com.aranroig.client.wrapper.Logger; import com.aranroig.client.wrapper.Logger;
import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence;
import com.aranroig.editor.ProjectPath;
import com.aranroig.editor.RunInfo; import com.aranroig.editor.RunInfo;
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.ServerboundRequestProjectPayload;
import com.aranroig.payloads.ServerboundRunCodePayload; import com.aranroig.payloads.ServerboundRunCodePayload;
import com.aranroig.payloads.ServerboundSaveCodePayload; import com.aranroig.payloads.ServerboundSaveCodePayload;
import com.aranroig.payloads.ServerboundShellInputPayload;
import com.aranroig.payloads.ServerboundShellResizePayload;
import com.aranroig.payloads.ServerboundSpawnShellPayload;
import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking;
import net.minecraft.client.Minecraft; import net.minecraft.client.Minecraft;
import party.iroiro.luajava.Lua; import party.iroiro.luajava.Lua;
import party.iroiro.luajava.luaj.LuaJ; import party.iroiro.luajava.luaj.LuaJ;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class EditorManager { public class EditorManager {
@@ -21,18 +38,45 @@ public class EditorManager {
EditorFileTree editorFileTree; EditorFileTree editorFileTree;
EditorTopBar editorTopBar; EditorTopBar editorTopBar;
EditorFileView editorFileView; EditorPaneContainer paneContainer;
EditorDocsPanel editorDocsPanel; EditorDocsPanel editorDocsPanel;
EditorTerminalPane editorTerminal;
List<EditorFile> files = new ArrayList<>(); List<EditorFile> files = new ArrayList<>();
/**
* Folders the player has folded in the sidebar. Where the project on disk
* stops being a flat list of paths and becomes a tree is the player's
* business, not the project's, so this stays on this side of the network.
*/
private final Set<String> foldedFolders = new HashSet<>();
/**
* Folders the player has made in the sidebar that nothing lives in yet. Like
* the fold state these are the player's view of the project: the server only
* stores file paths, so a folder with no file in it has no path to be stored
* by. Once a file is created inside one the path carries the folder itself,
* and it needs nothing kept here any more.
*/
private final Set<String> customFolders = new HashSet<>();
/** The folder new files are created in: the last one clicked in the sidebar. */
private String selectedFolder = "";
/** Live-editing state per file: which version we hold and what is in flight. */
private final Map<String, LiveDocument> liveDocs = new HashMap<>();
/** Who is in which file, as the server last told us. */
private final Map<String, List<EditorPresence>> presenceByFile = new HashMap<>();
public EditorManager() { public EditorManager() {
client = Minecraft.getInstance(); client = Minecraft.getInstance();
editorFileTree = new EditorFileTree(this); editorFileTree = new EditorFileTree(this);
editorTopBar = new EditorTopBar(this); editorTopBar = new EditorTopBar(this);
editorFileView = new EditorFileView(this); paneContainer = new EditorPaneContainer(this);
editorDocsPanel = new EditorDocsPanel(this); editorDocsPanel = new EditorDocsPanel(this);
editorTerminal = new EditorTerminalPane(this);
} }
public List<EditorFile> getFiles() { public List<EditorFile> getFiles() {
@@ -45,7 +89,7 @@ public class EditorManager {
public void toggleVisible() { public void toggleVisible() {
requestProjectFiles(); requestProjectFiles();
TextEditorScreen textEditorScreen = new TextEditorScreen(); TextEditorScreen textEditorScreen = new TextEditorScreen(this);
// Populate screen with widgets // Populate screen with widgets
editorFileTree.setSize(0, TOP_BAR_HEIGHT, FILE_RENDER_WIDTH_SIZE, -1); editorFileTree.setSize(0, TOP_BAR_HEIGHT, FILE_RENDER_WIDTH_SIZE, -1);
@@ -55,11 +99,9 @@ public class EditorManager {
editorTopBar.setZIndex(1); editorTopBar.setZIndex(1);
editorTopBar.addToEditorScreen(textEditorScreen); editorTopBar.addToEditorScreen(textEditorScreen);
editorFileView.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1); paneContainer.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1);
if (!files.isEmpty()) { paneContainer.addToEditorScreen(textEditorScreen); // attaches every pane too
editorFileView.setEditorFile(files.getFirst()); paneContainer.openInitialFile();
}
editorFileView.addToEditorScreen(textEditorScreen);
// Full-screen modal docs layer, above every other widget; hidden until opened. // Full-screen modal docs layer, above every other widget; hidden until opened.
editorDocsPanel.setSize(0, 0, -1, -1); editorDocsPanel.setSize(0, 0, -1, -1);
@@ -70,11 +112,18 @@ public class EditorManager {
editorDocsPanel.close(); editorDocsPanel.close();
// Focus the text editor so typing works immediately on open. // Focus the text editor so typing works immediately on open.
textEditorScreen.selectedWidget = editorFileView; textEditorScreen.selectedWidget = paneContainer.activePane();
// Remembered before showing it: opening the editor again replaces the
// screen, and the screen being replaced must not end the session of the
// one that is taking its place.
currentScreen = textEditorScreen;
client.setScreenAndShow(textEditorScreen); client.setScreenAndShow(textEditorScreen);
} }
/** The editor screen currently on screen, if any. */
private TextEditorScreen currentScreen;
/** Opens the Lua API documentation panel (top bar: Help → Lua API Documentation). */ /** Opens the Lua API documentation panel (top bar: Help → Lua API Documentation). */
public void openDocs() { public void openDocs() {
editorDocsPanel.open(); editorDocsPanel.open();
@@ -90,7 +139,7 @@ public class EditorManager {
/** Asks the server for the current project files; the reply lands in {@link #setFiles(List)}. */ /** Asks the server for the current project files; the reply lands in {@link #setFiles(List)}. */
public void requestProjectFiles() { public void requestProjectFiles() {
if (client.player == null) return; if (!connected()) return;
ClientPlayNetworking.send(new ServerboundRequestProjectPayload()); ClientPlayNetworking.send(new ServerboundRequestProjectPayload());
} }
@@ -98,13 +147,22 @@ public class EditorManager {
public void setFiles(List<EditorFile> newFiles) { public void setFiles(List<EditorFile> newFiles) {
files = new ArrayList<>(newFiles); files = new ArrayList<>(newFiles);
EditorFile current = editorFileView.getCurrentEditorFile(); // Each pane keeps showing the file it was showing, refreshed from the
EditorFile target = current != null ? findFile(current.getName()) : null; // server's copy of it — which is what carries the text. A pane whose
if (target == null && !files.isEmpty()) { // file is gone falls back to the project's first one, like the single
target = files.getFirst(); // view always did.
} for (EditorPane pane : paneContainer.panes()) {
if (target != null) { if (!(pane instanceof EditorFileView view)) continue;
editorFileView.setEditorFile(target);
EditorFile current = view.getCurrentEditorFile();
if (current == null && view != paneContainer.activePane()) continue;
EditorFile target = current != null ? findFile(current.getName()) : null;
if (target == null) {
if (files.isEmpty()) continue;
target = files.getFirst();
}
view.setEditorFile(target);
} }
} }
@@ -113,8 +171,9 @@ public class EditorManager {
EditorFile existing = findFile(file.getName()); EditorFile existing = findFile(file.getName());
if (existing == null) { if (existing == null) {
files.add(file); files.add(file);
} else if (existing != editorFileView.getCurrentEditorFile()) { } else if (!isDisplayed(file.getName())) {
// Don't clobber text the user is currently editing. // Don't clobber text the user is editing in a pane: a displayed
// file arrives edit by edit through the live session instead.
existing.setText(file.getText()); existing.setText(file.getText());
} }
} }
@@ -126,29 +185,473 @@ public class EditorManager {
return null; return null;
} }
/** Called on the client thread when the server renamed one of the project files. */
public void applyFileRename(String oldName, String newName) {
renameEntry(liveDocs, oldName, newName);
renameEntry(presenceByFile, oldName, newName);
EditorFile file = findFile(oldName);
if (file != null) file.setName(newName);
// The panes hold this same object, so they already edit the renamed
// file; only the presence display, keyed by the old name, must refresh.
refreshPresenceInPanes(newName);
}
public void openFile(EditorFile file) { public void openFile(EditorFile file) {
editorFileView.setEditorFile(file); // Files always open in a file pane: the shell keeps whatever is docked
// where it is docked.
EditorFileView pane = paneContainer.activeFilePane();
if (pane == null) pane = paneContainer.firstFilePane();
if (pane == null) {
// Only the shell was left; open a file pane beside it again.
pane = new EditorFileView(this);
paneContainer.dockPane(pane, paneContainer.activePane(), EditorPaneContainer.Orientation.HORIZONTAL);
}
pane.setEditorFile(file);
// Clicking a file in the tree means you want to be typing in it.
if (currentScreen != null) currentScreen.selectedWidget = pane;
} }
/** The file the active pane is showing, or null while nothing is open. */
public EditorFile getCurrentFile() {
EditorFileView pane = paneContainer.activeFilePane();
return pane == null ? null : pane.getCurrentEditorFile();
}
/** The pane files open in and typing belongs to, if that pane is a file view. */
EditorFileView activePane() {
return paneContainer.activeFilePane();
}
/** Every pane showing {@code name} — the same file can be open in two of them. */
private List<EditorFileView> panesEditing(String name) {
List<EditorFileView> showing = new ArrayList<>();
for (EditorPane pane : paneContainer.panes()) {
if (pane instanceof EditorFileView view && view.isEditing(name)) showing.add(view);
}
return showing;
}
/** Whether any pane is showing {@code name}. */
private boolean isDisplayed(String name) {
return !panesEditing(name).isEmpty();
}
/** Re-shows who is in {@code name} in every pane that has it open. */
private void refreshPresenceInPanes(String name) {
for (EditorFileView pane : panesEditing(name)) {
pane.setRemoteEditors(presenceFor(name));
}
}
// ── Folders ───────────────────────────────────────────────────────────
// Folders are not stored anywhere: they are the paths the file names carry,
// and the sidebar groups by them. Which of them is folded, and which one new
// files land in, is only this player's view of the project.
/** Whether the sidebar is showing {@code folder} folded. */
public boolean isFolderFolded(String folder) {
return foldedFolders.contains(folder);
}
public void toggleFolderFolded(String folder) {
if (!foldedFolders.remove(folder)) foldedFolders.add(folder);
}
/** Shows a folder again, so something put inside it is not hidden by it. */
public void unfoldFolder(String folder) {
foldedFolders.remove(folder);
}
/** The folder new files are created in; the project root when none is picked. */
public String getSelectedFolder() {
return selectedFolder;
}
public void setSelectedFolder(String folder) {
selectedFolder = folder == null ? "" : folder;
}
/** Folders made in the sidebar that nothing lives in yet; see {@link #customFolders}. */
public Set<String> getCustomFolders() {
return customFolders;
}
/**
* Makes {@code path} show up in the sidebar as a folder of its own, before
* anything is put in it. Folders are not sent anywhere: like the rest of the
* tree this is this player's view, and the folder becomes real on the server
* the moment a file is saved inside it.
*/
public void createFolder(String path) {
if (path == null || path.isEmpty()) return;
customFolders.add(path);
}
// ── Live editing ──────────────────────────────────────────────────────
// The server keeps the authoritative copy of every open file. Everything
// the player types goes to it as an edit against a known version, and
// everything everyone else types comes back and is merged into the buffer,
// which is what makes the file shared rather than merely synced on save.
/**
* Joins the live session of the file a pane just switched to, and shows
* whoever is already in it.
*/
public void onDocumentOpened(EditorFileView pane, EditorFile file) {
pane.setRemoteEditors(presenceFor(file.getName()));
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundOpenDocumentPayload(file.getName()));
}
/**
* Leaves every live session. Only the screen that is actually on screen can
* end it: when the editor is reopened, the screen being thrown away closes
* after the new one has already joined again.
*/
public void onEditorClosed(TextEditorScreen closed) {
if (closed != currentScreen) return;
currentScreen = null;
presenceByFile.clear();
for (EditorPane pane : paneContainer.panes())
if (pane instanceof EditorFileView view) view.setRemoteEditors(List.of());
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundCloseEditorPayload());
}
/**
* Forwards one local edit of the open file. The buffer has already been
* changed (typing has to feel instant); this records it as in flight and
* sends it with the version it was written against.
*/
public void submitEdit(EditorFile file, String buffer, int position, int deleteLength, String insert) {
file.setText(buffer);
if (!connected()) return;
LiveDocument doc = liveDocument(file.getName());
Edit edit = doc.submit(position, deleteLength, insert);
if (edit == null) return; // the change amounted to nothing
ClientPlayNetworking.send(new ServerboundEditPayload(file.getName(), doc.base(), edit));
}
/**
* Someone else's edit of a file we are watching. Every pane showing that
* file gets it; if no pane shows it, it is merged into our stored copy of
* it instead. The merge with our in-flight edits happens once per message
* — applying it to several panes shares that one result, so the second pane
* of the same file never transforms against the first pane's work.
*/
public void applyRemoteDocumentEdit(String file, int version, Edit edit) {
Edit merged = liveDocument(file).integrateRemote(version, edit);
List<EditorFileView> showing = panesEditing(file);
if (!showing.isEmpty()) {
for (EditorFileView pane : showing) pane.applyIntegratedRemoteEdit(merged);
return;
}
EditorFile data = findFile(file);
if (data != null) {
data.setText(merged.apply(data.getText()));
}
}
/**
* The server applied one of our edits; the document is now at
* {@code version}, holding {@code textLength} characters that hash to
* {@code textHash}. Once nothing of ours is in flight any more we can
* compare that against our buffer, and if they disagree the two copies
* drifted apart and ours has to come from the server.
*/
public void applyEditAck(String file, int version, int textHash, int textLength) {
LiveDocument doc = liveDocument(file);
doc.onAck(version);
if (!doc.isSynced()) return;
boolean inSync;
List<EditorFileView> showing = panesEditing(file);
if (!showing.isEmpty()) {
inSync = true;
for (EditorFileView pane : showing) {
inSync &= pane.matchesServerText(textHash, textLength);
}
} else {
EditorFile data = findFile(file);
inSync = data == null
|| (data.getText().length() == textLength && data.getText().hashCode() == textHash);
}
if (!inSync) {
Codecraft.LOGGER.warn("Live copy of {} no longer matches the server; fetching it again", file);
requestDocumentSync(findFile(file));
}
}
/**
* The server's authoritative copy of a file, sent when we join it and again
* when it decides our copy is too far behind to merge into.
*/
public void applyDocumentState(String file, String text, int version) {
LiveDocument doc = liveDocument(file);
List<EditorFileView> showing = panesEditing(file);
if (!showing.isEmpty() && !doc.isSynced() && version <= doc.base()) {
// This snapshot cannot contain what we are still typing, so taking
// it now would throw those keystrokes away. Once they are acked the
// check in applyEditAck asks for a snapshot that does contain them.
return;
}
doc.resetTo(version);
if (!showing.isEmpty()) {
for (EditorFileView pane : showing) pane.loadServerText(text);
} else {
EditorFile data = findFile(file);
if (data != null) data.setText(text);
}
}
/** Asks for the authoritative copy of a file again. */
public void requestDocumentSync(EditorFile file) {
if (file == null || !connected()) return;
ClientPlayNetworking.send(new ServerboundOpenDocumentPayload(file.getName()));
}
/** Sends our caret position to the other editors of {@code file}. */
public void sendCursor(String file, int cursor, int anchor) {
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundCursorPayload(file, cursor, anchor));
}
/** Called by the server when players join, leave or move inside {@code file}. */
public void applyPresence(String file, List<EditorPresence> editors) {
if (editors.isEmpty()) presenceByFile.remove(file);
else presenceByFile.put(file, List.copyOf(editors));
refreshPresenceInPanes(file);
}
/** Who the server says is editing {@code file}. */
public List<EditorPresence> presenceFor(String file) {
return presenceByFile.getOrDefault(file, List.of());
}
/** Who is sharing the file the active pane is showing right now. */
public List<EditorPresence> collaborators() {
EditorFile current = getCurrentFile();
return current == null ? List.of() : presenceFor(current.getName());
}
private LiveDocument liveDocument(String file) {
return liveDocs.computeIfAbsent(file,
name -> new LiveDocument(client.player != null ? client.player.getUUID() : new UUID(0L, 0L)));
}
/** Moves one entry of a per-file map to the file's new name. */
private static <T> void renameEntry(Map<String, T> byName, String oldName, String newName) {
T entry = byName.remove(oldName);
if (entry != null) byName.put(newName, entry);
}
private boolean connected() {
return client.getConnection() != null;
}
// ── Editor actions ────────────────────────────────────────────────────
/**
* Creates an empty file in the folder the sidebar has picked, with a name
* nobody in the project has taken yet, opens it in the view and saves it, so
* it exists on the server and shows up in the other editors' file lists
* right away.
*/
public void newFile() { public void newFile() {
String folder = selectedFolder;
// Otherwise a file made inside a folder the player cannot see is only
// in the editor, and the sidebar looks like nothing happened.
unfoldFolder(folder);
EditorFile file = new EditorFile(uniqueFileName(folder), "");
files.add(file);
openFile(file);
save();
} }
/**
* Opens the sidebar's inline field to name a new folder inside the one that
* is picked, and hands the keyboard to the tree so the name can be typed.
* Nothing is added to the project: an empty folder is only this player's
* view until a file is put in it.
*/
public void newFolder() {
editorFileTree.startNewFolder();
if (currentScreen != null) currentScreen.selectedWidget = editorFileTree;
}
/**
* A name for a new file inside {@code folder} that nobody in the project has
* taken. Names carry no extension — the sidebar shows the name as it is —
* and the folder is part of the name, which is what makes a file land inside it.
*/
private String uniqueFileName(String folder) {
String name = ProjectPath.resolve(folder, "untitled");
for (int i = 2; findFile(name) != null; i++) {
name = ProjectPath.resolve(folder, "untitled-" + i);
}
return name;
}
/**
* Renames a file of the project, refused if the new name is empty or taken.
* Our list and the live-editing bookkeeping follow the new name — the live
* document keeps its version, so editing carries on uninterrupted — and
* the server renames its copy and tells everyone else.
*/
public void renameFile(EditorFile file, String newName) {
if (file == null || newName.isEmpty() || newName.equals(file.getName())) return;
if (findFile(newName) != null) return;
String oldName = file.getName();
renameEntry(liveDocs, oldName, newName);
renameEntry(presenceByFile, oldName, newName);
file.setName(newName);
// The panes hold this same object, so they already edit the renamed
// file; only the presence display, keyed by the old name, must refresh.
refreshPresenceInPanes(newName);
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundRenameFilePayload(oldName, newName));
}
/**
* Flushes the buffer to the project. Everything typed is already with the
* server, so this is mostly the deliberate "put the whole file down" that
* also makes a brand-new file exist on it.
*/
public void save() { public void save() {
EditorFile currentEditorFile = editorFileView.getCurrentEditorFile(); EditorFileView pane = activePane();
if (pane == null) return; // the shell, if it is all that is focused, has nothing to save
EditorFile currentEditorFile = pane.getCurrentEditorFile();
if (currentEditorFile == null) return; if (currentEditorFile == null) return;
editorFileView.writeChanges(); pane.writeChanges();
ServerboundSaveCodePayload payload = new ServerboundSaveCodePayload(currentEditorFile); ServerboundSaveCodePayload payload = new ServerboundSaveCodePayload(currentEditorFile);
if (!connected()) return;
ClientPlayNetworking.send(payload); ClientPlayNetworking.send(payload);
} }
// ── Pane actions ──────────────────────────────────────────────────────
/** Splits the active pane, editing area and all: two panes side by side. */
public void splitRight() {
paneContainer.split(EditorPaneContainer.Orientation.HORIZONTAL, paneContainer.activePane());
}
/** Splits the active pane into one above the other. */
public void splitBelow() {
paneContainer.split(EditorPaneContainer.Orientation.VERTICAL, paneContainer.activePane());
}
/** Closes the active pane; the last one standing just empties instead. */
public void closeActivePane() {
paneContainer.closePane(paneContainer.activePane());
}
/** The pane a click landed in: where files open and typing goes from now on. */
public void setActivePane(EditorPane pane) {
paneContainer.setActivePane(pane);
}
// ── The server shell ──────────────────────────────────────────────────
// The server runs a real bash for this player; the terminal pane is its
// view. Pressing the top bar's Shell button docks the pane (under the pane
// in focus, IDE-style) and asks for the shell; closing the pane's header
// kills it again.
/** Whether the shell is running on the server, as far as this client knows. */
private boolean shellAlive = false;
/** Whether the terminal pane is tiled into the editing area right now. */
public boolean isShellOpen() {
return paneContainer.panes().contains(editorTerminal);
}
/**
* The Shell button: shows the terminal pane — docked below whatever pane
* was in focus the first time — spawns a shell for it if none is running,
* and gives it the keyboard. Pressing it again with the shell up just
* brings the same pane back to focus; only the pane's own close button
* ends the shell.
*/
public void toggleShell() {
paneContainer.dockPane(editorTerminal, paneContainer.activePane(),
EditorPaneContainer.Orientation.VERTICAL);
if (currentScreen != null) currentScreen.selectedWidget = editorTerminal;
if (!connected()) {
editorTerminal.markClosed("no server connection: no shell to spawn");
return;
}
if (!shellAlive) {
editorTerminal.announce("starting a shell on the server...");
ClientPlayNetworking.send(new ServerboundSpawnShellPayload(
editorTerminal.terminalRows(), editorTerminal.terminalCols()));
}
}
/** Called by the terminal pane when its header closes: the shell goes with it. */
public void closeShell() {
shellAlive = false;
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundCloseShellPayload());
}
/**
* Sends raw terminal input — a keystroke, Ctrl-C's {@code \u0003}, an
* arrow key's escape sequence, a status answer the emulator owes it — to
* the pseudo-terminal, which interprets all of that itself.
*/
public void sendShellControl(String bytes) {
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundShellInputPayload(bytes));
}
/**
* Tells the server the terminal pane's grid changed size: it moves the
* pseudo-terminal's window itself — an ioctl, not keystrokes — so a
* full-screen program in the foreground is signalled and reflows while
* it runs, the way a real window resize signals one.
*/
public void sendShellResize(int rows, int cols) {
if (!connected()) return;
ClientPlayNetworking.send(new ServerboundShellResizePayload(rows, cols));
}
/** Called on the client thread with everything the shell printed. */
public void applyShellOutput(String text) {
editorTerminal.appendOutput(text);
}
/** Called on the client thread when the shell exited or could not start. */
public void applyShellClosed(String reason) {
shellAlive = false;
editorTerminal.markClosed(reason);
}
public void undo() { public void undo() {
} }
public void run() { public void run() {
RunInfo runInfo = new RunInfo("main.lua"); // The project's entrypoint is the file named `main`, at the root.
RunInfo runInfo = new RunInfo(ProjectPath.ENTRYPOINT);
ServerboundRunCodePayload payload = new ServerboundRunCodePayload(runInfo); ServerboundRunCodePayload payload = new ServerboundRunCodePayload(runInfo);
if (!connected()) return;
ClientPlayNetworking.send(payload); ClientPlayNetworking.send(payload);
/* /*
String code = files.getFirst().getText(); String code = files.getFirst().getText();

View File

@@ -0,0 +1,34 @@
package com.aranroig.client.editor;
/**
* Something that lives in the editor's pane area: a file being edited
* ({@link EditorFileView}) or the server shell ({@link EditorTerminalPane}).
*
* <p>{@link EditorPaneContainer} treats every pane the same way — a header
* with the title and a close button, draggable sashes around it — so anything
* that wants to be a pane only has to say what its header reads and, when it
* does not want the split buttons or has something to clean up on close,
* override the small hooks here.</p>
*/
public abstract class EditorPane extends Widget {
protected EditorPane(EditorManager editorManager) {
super(editorManager);
}
/** The text of the header above this pane. */
public abstract String paneTitle();
/**
* Whether the header offers the split-right / split-below buttons. File
* panes can be split; the shell is one shell, so its header only holds the
* close button.
*/
public boolean showSplitButtons() {
return true;
}
/** The header's close button was pressed and this pane is going away. */
public void onPaneClosed() {
}
}

View File

@@ -0,0 +1,633 @@
package com.aranroig.client.editor;
import com.aranroig.editor.EditorFile;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import net.minecraft.util.Mth;
import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The editing area: one or more {@link EditorPane} panes tiled side by side
* and stacked — file views and, when opened, the shell — each with a header
* naming what it shows. The header of a pane splits it again (right or below)
* or closes it, and the strips between panes drag to resize them.
*
* <p>The layout is a tree of splits: a node is either a leaf showing one pane
* or a branch placing its children in a row ({@link Orientation#HORIZONTAL},
* with vertical sashes) or a column, each child holding a weight that a sash
* drag moves between its neighbours.</p>
*
* <p>The panes are widgets of the screen in their own right; this widget only
* answers for its headers and sashes — {@link #inside} is false anywhere else —
* so a click on a pane's text reaches that pane directly, and the keyboard
* belongs to whichever pane was last clicked.</p>
*/
public class EditorPaneContainer extends Widget {
/** HORIZONTAL: the children of the split sit side by side, the sash between them is vertical. */
public enum Orientation { HORIZONTAL, VERTICAL }
// ── The layout tree ───────────────────────────────────────────────────
private static class Node { }
private static final class Leaf extends Node {
final EditorPane view;
Leaf(EditorPane view) { this.view = view; }
}
private static final class Branch extends Node {
final Orientation orientation;
final List<Node> children = new ArrayList<>();
/** Size of each child relative to their sum: what dragging a sash moves around. */
final List<Double> weights = new ArrayList<>();
Branch(Orientation orientation) { this.orientation = orientation; }
double weightsSum() {
double sum = 0;
for (double weight : weights) sum += weight;
return sum;
}
}
/** Where a pane header ended up, and whose pane it heads. */
private record HeaderHit(Leaf leaf, int x0, int y0, int x1, int y1) {}
/**
* Where the strip between two children of a split ended up: the thing that
* drags to resize them. It carries the branch's measurements so a drag can
* convert pixels into weights without re-reading a layout that has since
* moved underneath it.
*/
private record SashHit(Branch branch, int index, boolean horizontal,
int x0, int y0, int x1, int y1, int available, double weightsSum) {}
private final List<HeaderHit> headerLayouts = new ArrayList<>();
private final List<SashHit> sashLayouts = new ArrayList<>();
private Node root;
private final List<EditorPane> panes = new ArrayList<>();
/** The pane new files open in, and the one the player is working in. */
private EditorPane activePane;
/** The sash the mouse is holding on to, and where the last drag event was. */
private Branch dragBranch;
private int dragIndex;
private int dragAvailable;
private double dragWeightsSum;
private int lastDragX, lastDragY;
// ── Look ──────────────────────────────────────────────────────────────
private static final int HEADER_HEIGHT = 12;
private static final int SASH_THICKNESS = 3;
private static final int MIN_PANE_WIDTH = 80;
private static final int MIN_PANE_HEIGHT = 30;
private static final int BUTTON_SIZE = 12;
/** The header buttons, right to left. */
private static final int BTN_CLOSE = 0;
private static final int BTN_SPLIT_BELOW = 1;
private static final int BTN_SPLIT_RIGHT = 2;
private static final int BUTTON_COUNT = 3;
private static final int COLOR_BACKGROUND = 0xFF303030;
private static final int COLOR_HEADER = 0xFF262626;
private static final int COLOR_HEADER_ACTIVE = 0xFF3C3C3C;
private static final int COLOR_HEADER_TEXT = 0xFFFFFFFF;
private static final int COLOR_HEADER_DIM = 0xFF9A9A9A;
private static final int COLOR_ACTIVE_ACCENT = 0xFF44688A;
private static final int COLOR_SASH = 0xFF444444;
private static final int COLOR_SASH_HOVER = 0xFF6A9BD5;
private static final int COLOR_BUTTON_HOVER = 0xFF4A4A4A;
private static final int COLOR_BUTTON_CLOSE = 0xFF7A3D3D;
private static final int COLOR_ICON = 0xFFCCCCCC;
// Pixel patterns like the sidebar's icons: '#' is the icon's colour, '.' nothing.
private static final String[] ICON_SPLIT_SIDE = {
"#######",
"#.....#",
"#..#..#",
"#..#..#",
"#..#..#",
"#.....#",
"#######",
};
private static final String[] ICON_SPLIT_STACKED = {
"#######",
"#.....#",
"#.....#",
"#######",
"#.....#",
"#.....#",
"#######",
};
private static final String[] ICON_CLOSE = {
"#.....#",
".#...#.",
"..#.#..",
"...#...",
"..#.#..",
".#...#.",
"#.....#",
};
public EditorPaneContainer(EditorManager editorManager) {
super(editorManager);
EditorFileView first = new EditorFileView(editorManager);
panes.add(first);
activePane = first;
root = new Leaf(first);
}
// ── Panes ─────────────────────────────────────────────────────────────
/** Every pane, whatever order they sit in. */
List<EditorPane> panes() {
return Collections.unmodifiableList(panes);
}
EditorPane activePane() {
return activePane;
}
/** The file pane files open in: the active one if it edits a file. */
EditorFileView activeFilePane() {
return activePane instanceof EditorFileView view ? view : null;
}
void setActivePane(EditorPane pane) {
if (pane != null) activePane = pane;
}
@Override
public void addToEditorScreen(EditorScreen screen) {
super.addToEditorScreen(screen);
for (EditorPane pane : panes) pane.addToEditorScreen(screen);
relayout();
}
/** Puts the project's first file in the pane that has none, for the initial open. */
void openInitialFile() {
EditorFileView pane = activeFilePane() != null ? activeFilePane() : firstFilePane();
if (pane != null && pane.getCurrentEditorFile() == null && !editorManager.getFiles().isEmpty())
pane.setEditorFile(editorManager.getFiles().getFirst());
}
/** The first pane editing a file, whatever the active one is. */
EditorFileView firstFilePane() {
for (EditorPane pane : panes)
if (pane instanceof EditorFileView view) return view;
return null;
}
// ── Splitting, docking and closing ────────────────────────────────────
/**
* Splits {@code source}'s area in two with a new file pane: it starts on
* the same file the source was showing, becomes the active pane, and takes
* the keyboard — what is opened from the tree next lands in it.
*/
void split(Orientation orientation, EditorPane source) {
EditorFileView fresh = new EditorFileView(editorManager);
dockLeaf(fresh, source, orientation);
EditorFile file = source instanceof EditorFileView view ? view.getCurrentEditorFile() : null;
if (file != null) fresh.setEditorFile(file);
if (editorScreen != null) editorScreen.selectedWidget = fresh;
}
/**
* Docks an existing pane — the shell, which stays the same one however
* often it is opened — beside {@code source}, and gives it the focus. A
* pane that is already docked is only focused again.
*/
void dockPane(EditorPane pane, EditorPane source, Orientation orientation) {
if (panes.contains(pane)) {
setActivePane(pane);
if (editorScreen != null) editorScreen.selectedWidget = pane;
return;
}
dockLeaf(pane, source, orientation);
if (editorScreen != null) editorScreen.selectedWidget = pane;
}
/** Puts {@code pane} in the tree beside {@code source} and makes it active. */
private void dockLeaf(EditorPane pane, EditorPane source, Orientation orientation) {
panes.add(pane);
if (editorScreen != null) pane.addToEditorScreen(editorScreen);
Leaf freshLeaf = new Leaf(pane);
Leaf sourceLeaf = findLeaf(source);
if (sourceLeaf == null || root == sourceLeaf) {
Branch branch = new Branch(orientation);
branch.children.add(root); branch.weights.add(1.0);
branch.children.add(freshLeaf); branch.weights.add(1.0);
root = branch;
} else {
Branch parent = findParent(sourceLeaf);
int index = parent.children.indexOf(sourceLeaf);
if (parent.orientation == orientation) {
// Another pane joins the same row or column: everyone in it shrinks.
parent.children.add(index + 1, freshLeaf);
parent.weights.add(index + 1, parent.weights.get(index));
} else {
Branch branch = new Branch(orientation);
branch.children.add(sourceLeaf); branch.weights.add(1.0);
branch.children.add(freshLeaf); branch.weights.add(1.0);
parent.children.set(index, branch);
}
}
setActivePane(pane);
relayout();
}
/** Closes one pane and gives its area back to its neighbours. */
void closePane(EditorPane pane) {
if (pane == null) return;
// The last pane does not go away: a file pane just empties instead.
// Closing the shell while it is all there is leaves an empty file pane
// behind, so the area is never left with nothing to edit at all.
if (panes.size() <= 1) {
if (pane instanceof EditorFileView view) {
view.clearFile();
return;
}
EditorFileView fresh = new EditorFileView(editorManager);
panes.set(0, fresh);
root = new Leaf(fresh);
setActivePane(fresh);
if (editorScreen != null) {
editorScreen.removeWidget(pane);
fresh.addToEditorScreen(editorScreen);
editorScreen.selectedWidget = fresh;
}
pane.onPaneClosed();
relayout();
return;
}
Leaf leaf = findLeaf(pane);
Branch parent = leaf == null ? null : findParent(leaf);
if (parent == null) return;
int index = parent.children.indexOf(leaf);
parent.children.remove(index);
parent.weights.remove(index);
Node replacement = parent;
if (parent.children.size() == 1) {
// A split with one child left is no split: the child takes the
// branch's own place, and the size it had, in the grandparent's row.
replacement = parent.children.get(0);
Branch grandParent = findParent(parent);
if (grandParent == null) root = replacement;
else grandParent.children.set(grandParent.children.indexOf(parent), replacement);
}
panes.remove(pane);
if (pane instanceof EditorFileView view) view.clearFile();
if (editorScreen != null) editorScreen.removeWidget(pane);
pane.onPaneClosed();
if (activePane == pane) setActivePane(firstLeafView(replacement));
if (editorScreen != null && editorScreen.selectedWidget == pane)
editorScreen.selectedWidget = activePane;
relayout();
}
private Leaf findLeaf(EditorPane view) {
return findLeaf(root, view);
}
private static Leaf findLeaf(Node node, EditorPane view) {
if (node instanceof Leaf leaf) return leaf.view == view ? leaf : null;
for (Node child : ((Branch) node).children) {
Leaf found = findLeaf(child, view);
if (found != null) return found;
}
return null;
}
private Branch findParent(Node target) {
return findParent(root, target);
}
private static Branch findParent(Node node, Node target) {
if (!(node instanceof Branch branch)) return null;
if (branch.children.contains(target)) return branch;
for (Node child : branch.children) {
Branch found = findParent(child, target);
if (found != null) return found;
}
return null;
}
private static EditorPane firstLeafView(Node node) {
if (node instanceof Leaf leaf) return leaf.view;
return firstLeafView(((Branch) node).children.get(0));
}
// ── Layout ────────────────────────────────────────────────────────────
/** Places every pane and sash again, and records the headers and sashes for hit-testing. */
private void relayout() {
headerLayouts.clear();
sashLayouts.clear();
if (editorScreen == null || root == null) return;
layoutNode(root, getStartX(), getStartY(), getEndX(), getEndY());
}
private void layoutNode(Node node, int x0, int y0, int x1, int y1) {
if (node instanceof Leaf leaf) {
// The header belongs to this container; the pane gets what is left.
leaf.view.setSize(x0, y0 + HEADER_HEIGHT, x1, y1);
headerLayouts.add(new HeaderHit(leaf, x0, y0, x1, y0 + HEADER_HEIGHT));
return;
}
Branch branch = (Branch) node;
boolean horizontal = branch.orientation == Orientation.HORIZONTAL;
int count = branch.children.size();
int total = horizontal ? x1 - x0 : y1 - y0;
int gaps = SASH_THICKNESS * (count - 1);
int available = Math.max(0, total - gaps);
double sum = branch.weightsSum();
if (sum <= 0) sum = count;
int pos = horizontal ? x0 : y0;
int placed = 0;
for (int i = 0; i < count; i++) {
int extent = (i == count - 1)
? available - placed
: (int) Math.round(available * branch.weights.get(i) / sum);
extent = Math.max(0, extent);
if (i > 0) {
sashLayouts.add(new SashHit(branch, i - 1, horizontal,
horizontal ? pos : x0, horizontal ? y0 : pos,
horizontal ? pos + SASH_THICKNESS : x1, horizontal ? y1 : pos + SASH_THICKNESS,
available, sum));
pos += SASH_THICKNESS;
}
if (horizontal) layoutNode(branch.children.get(i), pos, y0, pos + extent, y1);
else layoutNode(branch.children.get(i), x0, pos, x1, pos + extent);
pos += extent;
placed += extent;
}
}
/**
* Moves the sash being dragged by {@code movedX}/{@code movedY} pixels: the
* neighbour before it grows and the one after shrinks by the same amount,
* until either would come under its minimum size.
*/
private void resizeSash(int movedX, int movedY) {
if (dragBranch == null || dragAvailable <= 0 || dragWeightsSum <= 0) return;
boolean horizontal = dragBranch.orientation == Orientation.HORIZONTAL;
int moved = horizontal ? movedX : movedY;
if (moved == 0) return;
double sum = dragWeightsSum;
double weightA = dragBranch.weights.get(dragIndex);
double weightB = dragBranch.weights.get(dragIndex + 1);
double extentA = dragAvailable * weightA / sum;
double extentB = dragAvailable * weightB / sum;
double min = horizontal ? MIN_PANE_WIDTH : MIN_PANE_HEIGHT;
double delta = Mth.clamp(moved, -(extentA - min), extentB - min);
if (delta == 0) return;
dragBranch.weights.set(dragIndex, (extentA + delta) * sum / dragAvailable);
dragBranch.weights.set(dragIndex + 1, (extentB - delta) * sum / dragAvailable);
}
// ── Hit tests ─────────────────────────────────────────────────────────
/** Only headers and sashes answer to the mouse: the rest of the area is panes. */
@Override
public boolean inside(double x, double y) {
return sashAt((int) x, (int) y) != null || headerAt((int) x, (int) y) != null;
}
private SashHit sashAt(int x, int y) {
for (SashHit sash : sashLayouts)
if (inRect(x, y, sash.x0(), sash.y0(), sash.x1(), sash.y1())) return sash;
return null;
}
private HeaderHit headerAt(int x, int y) {
for (HeaderHit header : headerLayouts)
if (inRect(x, y, header.x0(), header.y0(), header.x1(), header.y1())) return header;
return null;
}
/**
* How many buttons this pane's header has, counted from the right: the
* close button always, the two split buttons only on panes that can be
* tiled.
*/
private static int buttonCount(EditorPane pane) {
return pane.showSplitButtons() ? BUTTON_COUNT : 1;
}
/** The {@code button} of this header, right to left: x0, y0, x1, y1. */
private static int[] buttonRect(HeaderHit header, int button) {
int x1 = header.x1() - 2 - BUTTON_SIZE * button;
return new int[]{x1 - BUTTON_SIZE, header.y0(), x1, header.y1()};
}
private static boolean inRect(int x, int y, int x0, int y0, int x1, int y1) {
return x >= x0 && x < x1 && y >= y0 && y < y1;
}
// ── Draw ──────────────────────────────────────────────────────────────
@Override
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
relayout();
// The panes paint their own areas; this is what the headers and the
// sashes sit on, so nothing of the world shows between them.
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND);
Font font = editorScreen.getFont();
for (SashHit sash : sashLayouts) {
boolean grabbing = dragBranch == sash.branch && dragIndex == sash.index;
int colour = (grabbing || inRect(mouseX, mouseY, sash.x0(), sash.y0(), sash.x1(), sash.y1()))
? COLOR_SASH_HOVER : COLOR_SASH;
if (sash.horizontal()) {
int line = (sash.x0() + sash.x1()) / 2;
graphics.fill(line, sash.y0(), line + 1, sash.y1(), colour);
} else {
int line = (sash.y0() + sash.y1()) / 2;
graphics.fill(sash.x0(), line, sash.x1(), line + 1, colour);
}
}
for (HeaderHit header : headerLayouts) drawHeader(graphics, font, header, mouseX, mouseY);
}
private void drawHeader(GuiGraphicsExtractor graphics, Font font, HeaderHit header, int mouseX, int mouseY) {
EditorPane view = header.leaf().view;
boolean active = view == activePane;
int buttons = buttonCount(view);
graphics.fill(header.x0(), header.y0(), header.x1(), header.y1(),
active ? COLOR_HEADER_ACTIVE : COLOR_HEADER);
if (active)
graphics.fill(header.x0(), header.y1() - 1, header.x1(), header.y1(), COLOR_ACTIVE_ACCENT);
int labelWidth = header.x1() - header.x0() - 8 - BUTTON_SIZE * buttons;
String name = truncateToFit(font, view.paneTitle(), labelWidth);
graphics.text(font, name, header.x0() + 4, header.y0() + 2,
active ? COLOR_HEADER_TEXT : COLOR_HEADER_DIM, false);
// Hovered button gets a background before any icon is drawn.
for (int button = 0; button < buttons; button++) {
int[] rect = buttonRect(header, button);
if (inRect(mouseX, mouseY, rect[0], rect[1], rect[2], rect[3]))
graphics.fill(rect[0], rect[1], rect[2], rect[3],
button == BTN_CLOSE ? COLOR_BUTTON_CLOSE : COLOR_BUTTON_HOVER);
}
for (int button = 0; button < buttons; button++) {
String[] glyph = switch (button) {
case BTN_CLOSE -> ICON_CLOSE;
case BTN_SPLIT_BELOW -> ICON_SPLIT_STACKED;
default -> ICON_SPLIT_SIDE;
};
int[] rect = buttonRect(header, button);
drawIcon(graphics, glyph,
rect[0] + (BUTTON_SIZE - glyph[0].length()) / 2,
rect[1] + (BUTTON_SIZE - glyph.length) / 2,
COLOR_ICON);
}
}
private static String truncateToFit(Font font, String text, int maxWidth) {
if (font.width(text) <= maxWidth) return text;
for (int i = text.length() - 1; i > 0; i--) {
String cut = text.substring(0, i) + "..";
if (font.width(cut) <= maxWidth) return cut;
}
return "";
}
private static void drawIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int colour) {
for (int row = 0; row < glyph.length; row++) {
String pixels = glyph[row];
for (int column = 0; column < pixels.length(); column++) {
if (pixels.charAt(column) != '#') continue;
graphics.fill(x + column, y + row, x + column + 1, y + row + 1, colour);
}
}
}
// ── Input ─────────────────────────────────────────────────────────────
@Override
public boolean handleKeyPressed(KeyEvent event) {
return false;
}
@Override
public boolean handleCharTyped(CharacterEvent event) {
return false;
}
@Override
public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return false;
int mx = (int) event.x();
int my = (int) event.y();
SashHit sash = sashAt(mx, my);
if (sash != null) {
dragBranch = sash.branch;
dragIndex = sash.index;
dragAvailable = sash.available;
dragWeightsSum = sash.weightsSum;
lastDragX = mx;
lastDragY = my;
return true;
}
HeaderHit header = headerAt(mx, my);
if (header == null) return false;
int buttons = buttonCount(header.leaf().view);
for (int button = 0; button < buttons; button++) {
int[] rect = buttonRect(header, button);
if (!inRect(mx, my, rect[0], rect[1], rect[2], rect[3])) continue;
switch (button) {
case BTN_CLOSE -> closePane(header.leaf().view);
case BTN_SPLIT_BELOW -> split(Orientation.VERTICAL, header.leaf().view);
case BTN_SPLIT_RIGHT -> split(Orientation.HORIZONTAL, header.leaf().view);
}
return true;
}
// A click on a header picks that pane: files opened from the tree go
// there, and the keyboard follows it.
setActivePane(header.leaf().view);
if (editorScreen != null) editorScreen.selectedWidget = header.leaf().view;
return true;
}
@Override
public boolean handleMouseDragged(MouseButtonEvent event) {
if (dragBranch == null) return false;
int mx = (int) event.x();
int my = (int) event.y();
resizeSash(mx - lastDragX, my - lastDragY);
lastDragX = mx;
lastDragY = my;
relayout();
return true;
}
@Override
public boolean handleMouseReleased(MouseButtonEvent event) {
if (dragBranch == null) return false;
dragBranch = null;
// The keyboard goes back where it was before the sash took it.
if (editorScreen != null && editorScreen.selectedWidget == this)
editorScreen.selectedWidget = activePane;
return true;
}
@Override
public boolean handleMouseScrolled(double scrollY) {
return false;
}
}

View File

@@ -25,6 +25,16 @@ public abstract class EditorScreen extends Screen {
widgets.add(widget); widgets.add(widget);
} }
/**
* Drops a widget from this screen: it stops being drawn and can no longer
* be clicked. Used when a pane closes, so its area is left to the panes
* that take it over.
*/
public void removeWidget(Widget widget){
widgets.remove(widget);
if(selectedWidget == widget) selectedWidget = null;
}
@Override @Override
public boolean keyPressed(KeyEvent event) { public boolean keyPressed(KeyEvent event) {
if(selectedWidget != null){ if(selectedWidget != null){
@@ -51,11 +61,16 @@ public abstract class EditorScreen extends Screen {
@Override @Override
public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) { public boolean mouseClicked(final MouseButtonEvent event, final boolean doubleClick) {
selectedWidget = raycastWidget(event); Widget hit = raycastWidget(event.x(), event.y());
if (selectedWidget != null && selectedWidget != hit) {
selectedWidget.handleFocusLost();
}
selectedWidget = hit;
if(selectedWidget != null) if(selectedWidget != null)
if (event.button() == 0) { // left button if (event.button() == 0) { // left button
isDragging = true; isDragging = true;
if(selectedWidget.handleMouseClicked(event)) if(selectedWidget.handleMouseClicked(event, doubleClick))
return true; return true;
} }
return super.mouseClicked(event, doubleClick); return super.mouseClicked(event, doubleClick);
@@ -84,21 +99,24 @@ public abstract class EditorScreen extends Screen {
@Override @Override
public boolean mouseScrolled(final double x, final double y, final double scrollX, final double scrollY) { public boolean mouseScrolled(final double x, final double y, final double scrollX, final double scrollY) {
if (selectedWidget != null){ // The widget under the mouse scrolls, not the one holding the keyboard:
if (selectedWidget.inside(x, y)) { // with several panes open, hovering one and scrolling should move that
// scrollY from GLFW: positive = up, which in our model = scroll content upward // one. The focused widget keeps priority while it is under the mouse
if(selectedWidget.handleMouseScrolled(scrollY)) // (the docs modal counts on it).
return true; Widget target = raycastWidget(x, y);
} if (selectedWidget != null && selectedWidget.inside(x, y)) target = selectedWidget;
}
if (target != null && target.handleMouseScrolled(scrollY))
return true;
return super.mouseScrolled(x, y, scrollX, scrollY); return super.mouseScrolled(x, y, scrollX, scrollY);
} }
private Widget raycastWidget(MouseButtonEvent event) { /** The topmost widget containing this point, by z-index. */
private Widget raycastWidget(double x, double y) {
Widget bestWidget = null; Widget bestWidget = null;
for(Widget widget : widgets){ for(Widget widget : widgets){
if(widget.inside(event.x(), event.y())){ if(widget.inside(x, y)){
if(bestWidget == null) bestWidget = widget; if(bestWidget == null) bestWidget = widget;
else { else {
if(bestWidget.getZIndex() < widget.getZIndex()) { if(bestWidget.getZIndex() < widget.getZIndex()) {

View File

@@ -0,0 +1,308 @@
package com.aranroig.client.editor;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
/**
* The terminal pane: keystrokes leave for the server one at a time — no
* local buffer, no Enter to submit — and the shell's output is handed to a
* {@link TerminalEmulator}, which is drawn where it stands. The caret is the
* shell's own cursor: what you type is echoed by the shell's tty, edited by
* its readline, and everything a real terminal is, this is — vim takes the
* screen, less scrolls, Ctrl-C kills.
*
* <p>The pane's own business is the window around that screen: sizing the
* grid to its pixels and telling the server that size — which moves the
* pseudo-terminal's own window, so full-screen programs notice a resize while
* they run — following output at the bottom until the wheel scrolls up, and
* drawing the cursor over whatever the emulator put there. Escape goes to the
* shell (vim would notice); the editor itself closes on its keybind, as
* ever.</p>
*/
public class EditorTerminalPane extends EditorPane {
private static final int SCROLL_SPEED = 3; // lines per wheel notch
private static final int PAD = 2;
private static final int DEFAULT_COLS = 80;
private static final int DEFAULT_ROWS = 24;
/** Frames a new grid sits still before the server is told: dragging a sash resizes every frame. */
private static final int RESIZE_SETTLE_FRAMES = 8;
private static final int COLOR_BACKGROUND = 0xFF141414;
private static final int COLOR_NOTE = 0xFF888888; // pane notes, not shell output
private static final int COLOR_CURSOR = 0xFFD0D0D0;
private static final int COLOR_CURSOR_TEXT = 0xFF141414;
private final TerminalEmulator emu = new TerminalEmulator(DEFAULT_COLS, DEFAULT_ROWS, this::answerShell);
/** Lines the view is lifted from the bottom; 0 = pinned, following. */
private int scroll;
private boolean shellAlive = true;
/** The grid the server was last told about, so a settled size is told once. */
private int sentRows = -1, sentCols = -1;
/** A grid the server has not been told about yet, counted up to {@link #RESIZE_SETTLE_FRAMES}. */
private int pendingRows = -1, pendingCols = -1, pendingFrames;
private Font font;
public EditorTerminalPane(EditorManager editorManager) {
super(editorManager);
}
@Override
public String paneTitle() {
return "Shell";
}
/** One shell, no point offering to tile two views of the same thing. */
@Override
public boolean showSplitButtons() {
return false;
}
/** Closing the pane means closing the shell: it is not kept for later. */
@Override
public void onPaneClosed() {
editorManager.closeShell();
}
/** The grid the shell would open on, for the spawn payload. */
public int terminalCols() { return emu.cols(); }
public int terminalRows() { return emu.rows(); }
// ── Output ────────────────────────────────────────────────────────────
/** Hands the emulator one chunk of what the shell printed. */
public void appendOutput(String text) {
shellAlive = true;
emu.feed(text);
// At the bottom, new lines pull the view along; scrolled up reading
// something older, the view holds still instead of drifting.
if (scroll > 0) scroll = Math.min(scroll + emu.poppedLastFeed(), emu.scrollbackSize());
}
/** The shell exited or could not start: say so and let the button respawn it. */
public void markClosed(String reason) {
shellAlive = false;
sentRows = sentCols = -1;
pendingRows = -1;
emu.writeText(reason + "\r\n", COLOR_NOTE);
}
/** A fresh shell is starting: an empty screen, and what is happening. */
public void announce(String what) {
// Size first: the pane may never have been drawn, and the spawn
// payload that follows should carry the real grid, not the defaults.
if (editorScreen != null) {
font = editorScreen.getFont();
fitSize();
}
emu.reset();
emu.clearScrollback();
scroll = 0;
shellAlive = true;
// Nothing is "already told" about size to a new shell: the spawn
// payload carries this grid, and the first draws tell it again once
// the server can reach the pty's device — a fresh pty starts at the
// kernel's default, and this corrects it well before bash settles.
sentRows = sentCols = -1;
pendingRows = emu.rows();
pendingCols = emu.cols();
pendingFrames = 0;
emu.writeText(what + "\r\n", COLOR_NOTE);
}
// ── Geometry: the grid follows the pane, and the server is told of it ─
private int cellWidth() {
// A terminal is a grid, and the default font is not one: every cell
// gets the width of the widest letter, so columns line up even if
// narrow letters travel with extra air around them.
return Math.max(4, font.width("M"));
}
private void fitSize() {
int newCols = clamp((getEndX() - getStartX() - 2 * PAD) / cellWidth(), 10, 512);
int newRows = clamp((getEndY() - getStartY() - 2 * PAD) / font.lineHeight, 3, 512);
if (newCols != emu.cols() || newRows != emu.rows()) {
emu.resize(newCols, newRows);
pendingRows = newRows;
pendingCols = newCols;
pendingFrames = 0;
}
}
/**
* Tells the server a grid that has sat still for a moment, so the pty's
* window moves: the kernel resizes the terminal and signals whatever the
* shell is running, which is what lets a full-screen program reflow
* mid-resize. Nothing is typed into the shell for this — no {@code stty}
* or {@code export} landing in vim's keystrokes — and dragging a sash
* costs one message, for the size it settles on.
*/
private void pumpResize() {
if (pendingRows < 0) return;
if (!shellAlive || (pendingRows == sentRows && pendingCols == sentCols)) {
pendingRows = -1;
return;
}
if (pendingFrames++ < RESIZE_SETTLE_FRAMES) return;
sentRows = pendingRows;
sentCols = pendingCols;
pendingRows = -1;
editorManager.sendShellResize(sentRows, sentCols);
}
private static int clamp(int value, int low, int high) {
return Math.max(low, Math.min(value, high));
}
// ── Draw ──────────────────────────────────────────────────────────────
@Override
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
font = editorScreen.getFont();
fitSize();
scroll = clamp(scroll, 0, emu.scrollbackSize());
pumpResize();
int lineH = font.lineHeight;
int cellW = cellWidth();
int left = getStartX() + PAD;
int top = getStartY() + PAD;
int rows = emu.rows();
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND);
graphics.enableScissor(getStartX(), top, getEndX(), getEndY() - PAD);
// The content is scrollback, then the screen; the view is a window of
// `rows` lines onto it, pinned to the bottom until scrolled up.
int total = emu.scrollbackSize() + rows;
int end = total - scroll;
int start = Math.max(0, end - rows);
for (int line = start; line < end; line++) {
int y = top + (line - start) * lineH;
for (int x = 0; x < emu.cols(); x++) {
char c = emu.charAt(line, x);
if (c == ' ') continue;
graphics.text(font, String.valueOf(c), left + x * cellW, y, emu.colorAt(line, x), false);
}
}
drawCursor(graphics, left, top, cellW, lineH, start, end);
graphics.disableScissor();
}
private void drawCursor(GuiGraphicsExtractor graphics, int left, int top,
int cellW, int lineH, int start, int end) {
if (!emu.cursorVisible()) return;
int line = emu.cursorContentLine();
if (line < start || line >= end) return;
int x = left + emu.cursorX() * cellW;
int y = top + (line - start) * lineH;
char at = emu.charAt(line, emu.cursorX());
if (editorScreen.selectedWidget == this) {
graphics.fill(x, y, x + cellW, y + lineH, COLOR_CURSOR);
if (at != ' ') graphics.text(font, String.valueOf(at), x, y, COLOR_CURSOR_TEXT, false);
} else {
// The keyboard belongs elsewhere: an outline, not a block.
graphics.fill(x, y, x + cellW, y + 1, COLOR_CURSOR);
graphics.fill(x, y + lineH - 1, x + cellW, y + lineH, COLOR_CURSOR);
graphics.fill(x, y + 1, x + 1, y + lineH - 1, COLOR_CURSOR);
graphics.fill(x + cellW - 1, y + 1, x + cellW, y + lineH - 1, COLOR_CURSOR);
}
}
// ── Input: keystrokes go to the shell, one by one ─────────────────────
@Override
public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
// Clicking the terminal means the keyboard belongs to the shell now.
editorManager.setActivePane(this);
scroll = 0;
return true;
}
@Override
public boolean handleMouseScrolled(double scrollY) {
scroll = clamp(scroll + (int) Math.round(scrollY * SCROLL_SPEED), 0, emu.scrollbackSize());
return true;
}
@Override
public boolean handleMouseDragged(MouseButtonEvent event) {
return true;
}
@Override
public boolean handleMouseReleased(MouseButtonEvent event) {
return true;
}
@Override
public boolean handleKeyPressed(KeyEvent event) {
int key = event.key();
if (event.hasControlDown() && key >= 65 && key <= 90) {
// Ctrl+letter is not a letter: it is \u0001..\u001A, which the tty
// turns into signals and edits (Ctrl-C, Ctrl-D, Ctrl-R…).
sendToShell(String.valueOf((char) (key - 64)));
return true;
}
boolean appKeys = emu.appCursorKeys();
switch (key) {
// Escape belongs to the shell (vim would notice): the editor
// closes on its own keybind instead.
case 256 -> sendToShell("\u001B");
case 257, 335 -> sendToShell("\r"); // Enter, keypad Enter
case 258 -> sendToShell("\t"); // Tab: completion, in shell and vim alike
case 259 -> sendToShell("\u007F"); // Backspace: DEL, what readline expects
case 260 -> sendToShell("\u001B[2~"); // Insert
case 261 -> sendToShell("\u001B[3~"); // Delete
case 262 -> sendToShell(appKeys ? "\u001BOC" : "\u001B[C"); // Right
case 263 -> sendToShell(appKeys ? "\u001BOD" : "\u001B[D"); // Left
case 264 -> sendToShell(appKeys ? "\u001BOB" : "\u001B[B"); // Down
case 265 -> sendToShell(appKeys ? "\u001BOA" : "\u001B[A"); // Up
case 266 -> sendToShell("\u001B[5~"); // Page Up
case 267 -> sendToShell("\u001B[6~"); // Page Down
case 268 -> sendToShell(appKeys ? "\u001BOH" : "\u001B[1~"); // Home
case 269 -> sendToShell(appKeys ? "\u001BOF" : "\u001B[4~"); // End
default -> { }
}
return true;
}
@Override
public boolean handleCharTyped(CharacterEvent event) {
int codePoint = event.codepoint();
if (codePoint < 32 || codePoint == 127) return true; // keys, not text: those went through keyPressed
sendToShell(Character.toString(codePoint));
return true;
}
/** Types one keystroke's worth into the shell — if there is one to type into. */
private void sendToShell(String bytes) {
if (!shellAlive) return; // markClosed already said it on the screen
scroll = 0; // typing looks at where the typing is
editorManager.sendShellControl(bytes);
}
/** The emulator's turn to speak (device attributes, cursor position): back as the shell's input. */
private void answerShell(String response) {
if (shellAlive) editorManager.sendShellControl(response);
}
}

View File

@@ -1,5 +1,6 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.editor.EditorPresence;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent; import net.minecraft.client.input.CharacterEvent;
@@ -35,13 +36,13 @@ public class EditorTopBar extends Widget {
static MenuItem separator() { return new MenuItem("", true); } static MenuItem separator() { return new MenuItem("", true); }
} }
private static final String[] TAB_LABELS = { "File", "Edit", "Run", "Help" }; private static final String[] TAB_LABELS = { "File", "Edit", "Run", "View", "Help" };
private static final List<List<MenuItem>> TAB_ITEMS = List.of( private static final List<List<MenuItem>> TAB_ITEMS = List.of(
// File // File
List.of( List.of(
MenuItem.item("New File"), MenuItem.item("New File"),
MenuItem.item("Open..."), MenuItem.item("New Folder..."),
MenuItem.item("Save"), MenuItem.item("Save"),
MenuItem.item("Save As..."), MenuItem.item("Save As..."),
MenuItem.separator(), MenuItem.separator(),
@@ -66,6 +67,13 @@ public class EditorTopBar extends Widget {
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Build Project") MenuItem.item("Build Project")
), ),
// View
List.of(
MenuItem.item("Split Right"),
MenuItem.item("Split Below"),
MenuItem.separator(),
MenuItem.item("Close Pane")
),
// Help // Help
List.of( List.of(
MenuItem.item("Lua API Documentation") MenuItem.item("Lua API Documentation")
@@ -78,6 +86,36 @@ public class EditorTopBar extends Widget {
/** Mouse position, updated each frame from the screen. */ /** Mouse position, updated each frame from the screen. */
private int mouseX, mouseY; private int mouseX, mouseY;
// ── Shell button ──────────────────────────────────────────────────────
// The one action that deserves to be a button instead of a menu item.
private static final String SHELL_LABEL = ">_ Shell";
private static final int COLOR_SHELL_ACCENT = 0xFF44688A;
private int shellButtonWidth(Font font) { return font.width(SHELL_LABEL) + TAB_PADDING_X * 2 + 2; }
private int shellButtonX0(Font font) { return getEndX() - shellButtonWidth(font); }
private boolean insideShellButton(int mx, int my, Font font) {
return mx >= shellButtonX0(font) && mx < getEndX()
&& my >= getStartY() && my < getStartY() + BAR_HEIGHT;
}
private void drawShellButton(GuiGraphicsExtractor graphics, Font font) {
int x0 = shellButtonX0(font);
int y0 = getStartY();
int y1 = y0 + BAR_HEIGHT;
boolean open = editorManager.isShellOpen();
boolean hovered = insideShellButton(mouseX, mouseY, font);
graphics.fill(x0, y0, getEndX(), y1,
open ? COLOR_TAB_OPEN : hovered ? COLOR_TAB_HOVER : COLOR_BACKGROUND);
graphics.text(font, SHELL_LABEL, x0 + TAB_PADDING_X, y0 + TAB_PADDING_Y, COLOR_TEXT, false);
// The same underline the active pane header wears: this pane is open.
if (open) graphics.fill(x0, y1 - 1, getEndX(), y1, COLOR_SHELL_ACCENT);
}
// ── Drawing ─────────────────────────────────────────────────────────── // ── Drawing ───────────────────────────────────────────────────────────
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
@@ -118,8 +156,45 @@ public class EditorTopBar extends Widget {
tabX = tabEndX; tabX = tabEndX;
} }
drawShellButton(graphics, font);
drawCollaborators(graphics, font);
} }
/**
* Who else is in the file you are looking at, on the right of the bar: a
* coloured dot and a name each, in the colour their caret is drawn in.
* Nothing here means nobody else has this file open.
*/
private void drawCollaborators(GuiGraphicsExtractor graphics, Font font) {
List<EditorPresence> editors = editorManager.collaborators();
if (editors.isEmpty()) return;
List<EditorPresence> shown = editors.size() > MAX_COLLABORATOR_LABELS
? editors.subList(0, MAX_COLLABORATOR_LABELS)
: editors;
String more = editors.size() > shown.size() ? "+" + (editors.size() - shown.size()) : "";
int width = font.width(more);
for (EditorPresence editor : shown) width += font.width(editor.name()) + 13;
// Right-aligned, but never over the menu labels — and leaving the
// shell button its own space at the end of the bar.
int x = Math.max(getStartX() + 120, getEndX() - shellButtonWidth(font) - width);
int y = getStartY() + TAB_PADDING_Y;
for (EditorPresence editor : shown) {
graphics.fill(x, y + 1, x + 3, y + font.lineHeight - 1, editor.color());
graphics.text(font, editor.name(), x + 5, y, editor.color(), false);
x += font.width(editor.name()) + 13;
}
if (!more.isEmpty()) {
graphics.text(font, more, x, y, COLOR_TEXT, false);
}
}
private static final int MAX_COLLABORATOR_LABELS = 4;
@Override @Override
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
return false; return false;
@@ -131,7 +206,7 @@ public class EditorTopBar extends Widget {
} }
@Override @Override
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
int button = event.button(); int button = event.button();
double mx = event.x(); double mx = event.x();
double my = event.y(); double my = event.y();
@@ -155,6 +230,13 @@ public class EditorTopBar extends Widget {
tabX = tabEndX; tabX = tabEndX;
} }
// The shell button, at the end of the bar.
if (insideShellButton(imx, imy, font())) {
openTab = -1;
editorManager.toggleShell();
return true;
}
// Click on a dropdown item? // Click on a dropdown item?
if (openTab >= 0) { if (openTab >= 0) {
int result = getClickedItemIndex(imx, imy, openTab); int result = getClickedItemIndex(imx, imy, openTab);
@@ -235,11 +317,15 @@ public class EditorTopBar extends Widget {
// TODO: wire these to your EditorManager // TODO: wire these to your EditorManager
switch (item.label()) { switch (item.label()) {
case "New File" -> editorManager.newFile(); case "New File" -> editorManager.newFile();
case "New Folder..." -> editorManager.newFolder();
case "Save" -> editorManager.save(); case "Save" -> editorManager.save();
case "Undo" -> editorManager.undo(); case "Undo" -> editorManager.undo();
case "Redo" -> editorManager.redo(); case "Redo" -> editorManager.redo();
case "Run Script" -> editorManager.run(); case "Run Script" -> editorManager.run();
case "Stop" -> editorManager.stop(); case "Stop" -> editorManager.stop();
case "Split Right" -> editorManager.splitRight();
case "Split Below" -> editorManager.splitBelow();
case "Close Pane" -> editorManager.closeActivePane();
case "Lua API Documentation" -> editorManager.openDocs(); case "Lua API Documentation" -> editorManager.openDocs();
// Add remaining cases as needed // Add remaining cases as needed
default -> System.out.println("[TopBar] Clicked: " + item.label()); default -> System.out.println("[TopBar] Clicked: " + item.label());

View File

@@ -0,0 +1,30 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* Completion for the {@code events} global — game event listeners provided by
* codecraft itself. Keep in sync with the listener registration and
* {@code LuaApiDocs}.
*/
public class EventsLibrary implements LuaLibrary {
private static final List<CompletionItem> MEMBERS = List.of(
CompletionItem.method("on_use_item", "on_use_item("),
CompletionItem.method("on_break_block", "on_break_block("),
CompletionItem.method("on_chat", "on_chat("),
CompletionItem.method("on_player_join", "on_player_join("),
CompletionItem.method("on_player_leave", "on_player_leave("),
CompletionItem.method("on_tick", "on_tick(")
);
@Override
public String name() {
return "events";
}
@Override
public List<CompletionItem> members() {
return MEMBERS;
}
}

View File

@@ -0,0 +1,109 @@
package com.aranroig.client.editor;
import com.aranroig.editor.Edit;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.UUID;
/**
* What the client needs to know to edit a document together with other players:
* which version of the server's copy the buffer holds, and which of the
* player's own edits the server has not confirmed yet.
*
* <p>Local edits are applied to the buffer straight away (typing must feel
* instant) and kept in {@link #pending} until the server confirms them. While
* they are in flight someone else's edit can arrive, and the two were written
* against the same version of the text; {@link #integrateRemote} rewrites both
* so they fit one after the other, which is what stops concurrent typing from
* throwing characters away or applying them at the wrong offset.</p>
*
* <p>Every notification the server sends about a document — somebody else's
* edit, or the ack of one of ours — carries its version and arrives in order,
* so {@link #base()} only ever moves forward and one ack retires exactly one
* pending edit.</p>
*/
public final class LiveDocument {
private final UUID author;
/** Server version the buffer corresponds to, ignoring the edits in flight. */
private int base;
/** Our own edits, oldest first, that the server has not acknowledged yet. */
private final Deque<Edit> pending = new ArrayDeque<>();
private long sequence;
public LiveDocument(UUID author) {
this.author = author;
}
/**
* Records an edit the player just made locally and returns it, ready to be
* sent with {@link #base()} as the version it was written against. Returns
* {@code null} when the change amounts to nothing, so it is not queued or
* sent at all.
*/
public Edit submit(int position, int deleteLength, String insert) {
Edit edit = Edit.replace(author, sequence, position, deleteLength, insert);
if (edit.isEmpty()) return null;
sequence++;
pending.addLast(edit);
return edit;
}
/** The version of the server's copy this buffer was written against. */
public int base() {
return base;
}
/** True when everything the player typed has been confirmed by the server. */
public boolean isSynced() {
return pending.isEmpty();
}
/**
* Notes that the server applied the oldest of our edits, taking the document
* to {@code version}.
*/
public void onAck(int version) {
if (!pending.isEmpty()) pending.removeFirst();
base = Math.max(base, version);
}
/**
* Folds somebody else's edit into the local state and returns the version of
* it that fits <em>our</em> buffer, i.e. the one to apply to it. The edits
* still in flight are rewritten the same way, so they stay valid against the
* text they will be replayed onto.
*/
public Edit integrateRemote(int version, Edit remote) {
Edit toApply = remote;
if (!pending.isEmpty()) {
List<Edit> rebased = new ArrayList<>(pending.size());
for (Edit mine : pending) {
// One walk gives both directions: the remote edit as it fits our
// buffer, and our edit as it fits the text it will be acked onto.
Edit[] pair = Edit.transformPair(toApply, mine);
toApply = pair[0];
rebased.add(pair[1]);
}
pending.clear();
pending.addAll(rebased);
}
base = Math.max(base, version);
return toApply;
}
/**
* Adopts the server's document wholesale: nothing is in flight any more and
* the buffer is about to be replaced with {@code version} of it.
*/
public void resetTo(int version) {
pending.clear();
base = version;
}
}

View File

@@ -0,0 +1,21 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* A named Lua global table that supports member completion after a "." or ":"
* trigger — Lua's own standard libraries ({@code string}, {@code math}, …) and
* the tables codecraft itself injects ({@code world}, {@code events}).
*
* <p>To make a new library's members appear in the autocomplete popup,
* implement this interface and add an instance to
* {@link CompletionProvider}.</p>
*/
public interface LuaLibrary {
/** The global table name, e.g. {@code "math"} for {@code math.floor}. */
String name();
/** Members offered when the user types {@code name.} in the editor. */
List<CompletionItem> members();
}

View File

@@ -0,0 +1,85 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* The common Lua code templates offered at the top level of the autocomplete
* popup (kind {@link CompletionItem.Kind#SNIPPET}) and loaded by
* {@link CompletionProvider}.
*/
public final class LuaSnippets {
private LuaSnippets() {
}
private static final List<CompletionItem> SNIPPETS = List.of(
CompletionItem.snippet("fun",
"function ()\n \nend",
"anonymous function"),
CompletionItem.snippet("function",
"function name()\n \nend",
"named function"),
CompletionItem.snippet("lfun",
"local function name()\n \nend",
"local function"),
CompletionItem.snippet("if",
"if then\n \nend",
"if block"),
CompletionItem.snippet("ifel",
"if then\n \nelse\n \nend",
"if / else"),
CompletionItem.snippet("ifelseif",
"if then\n \nelseif then\n \nelse\n \nend",
"if / elseif / else"),
CompletionItem.snippet("for",
"for i = 1, do\n \nend",
"numeric for"),
CompletionItem.snippet("forin",
"for k, v in pairs() do\n \nend",
"generic for (pairs)"),
CompletionItem.snippet("fori",
"for i, v in ipairs() do\n \nend",
"generic for (ipairs)"),
CompletionItem.snippet("while",
"while do\n \nend",
"while loop"),
CompletionItem.snippet("repeat",
"repeat\n \nuntil ",
"repeat / until"),
CompletionItem.snippet("pcall",
"local ok, err = pcall(function()\n \nend)",
"protected call"),
CompletionItem.snippet("class",
"local ClassName = {}\nClassName.__index = ClassName\n\nfunction ClassName.new()\n local self = setmetatable({}, ClassName)\n return self\nend\n\nreturn ClassName",
"OOP class template"),
CompletionItem.snippet("require",
"local = require(\"\")",
"require module"),
CompletionItem.snippet("print",
"print()",
"print(…)"),
CompletionItem.snippet("setblock",
"world.set_block(, , , \"minecraft:stone\")",
"world.set_block(…)"),
CompletionItem.snippet("removeblock",
"world.remove_block(, , )",
"world.remove_block(…)"),
CompletionItem.snippet("getblock",
"local block = world.get_block(, , )",
"world.get_block(…)"),
CompletionItem.snippet("onevent",
"events.on_chat(function(player, message)\n \nend)",
"event listener"),
CompletionItem.snippet("local",
"local = ",
"local variable"),
CompletionItem.snippet("return",
"return ",
"return statement")
);
/** All snippets, in display order. */
public static List<CompletionItem> all() {
return SNIPPETS;
}
}

View File

@@ -0,0 +1,120 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* The Lua standard library tables ({@code string}, {@code table}, {@code math},
* {@code io}, {@code os}, {@code coroutine}) as {@link LuaLibrary} instances,
* so they can be loaded by {@link CompletionProvider} alongside the
* codecraft-provided libraries.
*/
public final class LuaStandardLibraries {
private LuaStandardLibraries() {
}
/** A library defined by a fixed member list. */
private record SimpleLibrary(String name, List<CompletionItem> members) implements LuaLibrary {
}
// ── string.* ──────────────────────────────────────────────────────────
private static final LuaLibrary STRING = new SimpleLibrary("string", List.of(
CompletionItem.method("byte(", "byte("),
CompletionItem.method("char(", "char("),
CompletionItem.method("dump(", "dump("),
CompletionItem.method("find(", "find("),
CompletionItem.method("format(", "format("),
CompletionItem.method("gmatch(", "gmatch("),
CompletionItem.method("gsub(", "gsub("),
CompletionItem.method("len(", "len("),
CompletionItem.method("lower(", "lower("),
CompletionItem.method("match(", "match("),
CompletionItem.method("rep(", "rep("),
CompletionItem.method("reverse(", "reverse("),
CompletionItem.method("sub(", "sub("),
CompletionItem.method("upper(", "upper(")
));
// ── table.* ───────────────────────────────────────────────────────────
private static final LuaLibrary TABLE = new SimpleLibrary("table", List.of(
CompletionItem.method("concat(", "concat("),
CompletionItem.method("insert(", "insert("),
CompletionItem.method("move(", "move("),
CompletionItem.method("pack(", "pack("),
CompletionItem.method("remove(", "remove("),
CompletionItem.method("sort(", "sort("),
CompletionItem.method("unpack(", "unpack(")
));
// ── math.* ────────────────────────────────────────────────────────────
private static final LuaLibrary MATH = new SimpleLibrary("math", List.of(
CompletionItem.method("abs", "abs("),
CompletionItem.method("ceil", "ceil("),
CompletionItem.method("cos", "cos("),
CompletionItem.method("exp", "exp("),
CompletionItem.method("floor", "floor("),
CompletionItem.method("fmod", "fmod("),
CompletionItem.method("log", "log("),
CompletionItem.method("max", "max("),
CompletionItem.method("min", "min("),
CompletionItem.method("modf", "modf("),
CompletionItem.method("pow", "pow("),
CompletionItem.method("random", "random("),
CompletionItem.method("randomseed", "randomseed("),
CompletionItem.method("sin", "sin("),
CompletionItem.method("sqrt", "sqrt("),
CompletionItem.method("tan", "tan("),
CompletionItem.method("tointeger", "tointeger("),
CompletionItem.method("type", "type("),
CompletionItem.method("huge", "huge"),
CompletionItem.method("pi", "pi"),
CompletionItem.method("maxinteger", "maxinteger"),
CompletionItem.method("mininteger", "mininteger")
));
// ── io.* ──────────────────────────────────────────────────────────────
private static final LuaLibrary IO = new SimpleLibrary("io", List.of(
CompletionItem.method("close", "close("),
CompletionItem.method("flush", "flush()"),
CompletionItem.method("input", "input("),
CompletionItem.method("lines", "lines("),
CompletionItem.method("open", "open("),
CompletionItem.method("output", "output("),
CompletionItem.method("popen", "popen("),
CompletionItem.method("read", "read("),
CompletionItem.method("tmpfile", "tmpfile()"),
CompletionItem.method("type", "type("),
CompletionItem.method("write", "write(")
));
// ── os.* ──────────────────────────────────────────────────────────────
private static final LuaLibrary OS = new SimpleLibrary("os", List.of(
CompletionItem.method("clock", "clock()"),
CompletionItem.method("date", "date("),
CompletionItem.method("difftime", "difftime("),
CompletionItem.method("execute", "execute("),
CompletionItem.method("exit", "exit("),
CompletionItem.method("getenv", "getenv("),
CompletionItem.method("remove", "remove("),
CompletionItem.method("rename", "rename("),
CompletionItem.method("setlocale", "setlocale("),
CompletionItem.method("time", "time("),
CompletionItem.method("tmpname", "tmpname()")
));
// ── coroutine.* ───────────────────────────────────────────────────────
private static final LuaLibrary COROUTINE = new SimpleLibrary("coroutine", List.of(
CompletionItem.method("create", "create("),
CompletionItem.method("isyieldable", "isyieldable()"),
CompletionItem.method("resume", "resume("),
CompletionItem.method("running", "running()"),
CompletionItem.method("status", "status("),
CompletionItem.method("wrap", "wrap("),
CompletionItem.method("yield", "yield(")
));
/** All standard libraries, in display order. */
public static List<LuaLibrary> all() {
return List.of(STRING, TABLE, MATH, IO, OS, COROUTINE);
}
}

View File

@@ -0,0 +1,629 @@
package com.aranroig.client.editor;
import java.util.function.Consumer;
/**
* The terminal emulator: a character grid with a cursor, doing what the
* escape sequences a shell prints tell it to do. This class has no idea a
* game exists — it is the screen, and a screen of any terminal program in
* the world would be too — so {@link EditorTerminalPane} draws it and feeds
* it, and nothing else has to care.
*
* <h2>What it understands</h2>
*
* <p>Text and its control characters; SGR colours (the 16, 256 and true
* colour); cursor movement, positioning and saving; erasing line and screen;
* inserting and deleting lines and characters; scroll regions; the
* alternate screen full-screen programs switch to; cursor visibility; auto
* wrap; and the two device queries a program asks a terminal when it wants
* to know what it is talking to — the answers go back through the
* {@code responder} given at construction, because a terminal that stays
* quiet when asked is a program left waiting.</p>
*
* <h2>What it keeps</h2>
*
* <p>Rows that scroll off the top of the main screen become scrollback, up
* to a cap; the alternate screen produces none, which is why vim leaves no
* mess behind. Everything else — window size, keystrokes, what the shell
* should be told about its dimensions — belongs to the pane.</p>
*/
public final class TerminalEmulator {
/** The colour of a cell nothing has been said about. */
public static final int DEFAULT_COLOR = 0xFFD4D4D4;
/** Scrollback lines kept when a {@code yes} decides to introduce itself. */
public static final int MAX_SCROLLBACK = 1000;
/** SGR 30..37 and 90..97, in the order the shell counts them. */
private static final int[] ANSI_COLORS = {
0xFF000000, 0xFFAA0000, 0xFF00AA00, 0xFFAA5500,
0xFF0000AA, 0xAA00AA00, 0xFF00AAAA, 0xFFAAAAAA,
0xFF555555, 0xFFFF5555, 0xFF55FF55, 0xFFFF5555,
0xFF5555FF, 0xFFFF55FF, 0xFF55FFFF, 0xFFFFFFFF,
};
/** One row: a fixed line of characters, one colour each. */
public static final class Row {
final char[] ch;
final int[] fg;
Row(int cols) {
ch = new char[cols];
fg = new int[cols];
java.util.Arrays.fill(ch, ' ');
java.util.Arrays.fill(fg, DEFAULT_COLOR);
}
}
private static final class Screen {
final java.util.List<Row> rows = new java.util.ArrayList<>();
Screen(int cols, int height) {
for (int y = 0; y < height; y++) rows.add(new Row(cols));
}
Screen resized(int newCols, int newRows) {
Screen next = new Screen(newCols, newRows);
for (int y = 0; y < Math.min(rows.size(), newRows); y++) {
Row from = rows.get(y), to = next.rows.get(y);
for (int x = 0; x < Math.min(from.ch.length, newCols); x++) {
to.ch[x] = from.ch[x];
to.fg[x] = from.fg[x];
}
}
return next;
}
}
// Parser states for the incoming stream. Sequences may straddle chunk
// boundaries, so the machine and its scratch buffer are fields, not locals.
private static final int ST_TEXT = 0, ST_ESC = 1, ST_CSI = 2,
ST_STRING = 3, ST_STRING_ESC = 4, ST_CHARSET = 5;
private Screen main, alt;
private boolean onAlt;
private int cols, rows;
private int cx, cy;
private int savedCx, savedCy, savedPen;
private int regionTop, regionBottom;
private int pen = DEFAULT_COLOR;
private boolean wrapNext;
private boolean autoWrap = true;
private boolean appCursorKeys;
private boolean cursorVisible = true;
private final java.util.List<Row> scrollback = new java.util.ArrayList<>();
/** Rows pushed into scrollback by the last {@link #feed}, to keep a view steady. */
private int popped;
private final Consumer<String> responder;
private int parseState = ST_TEXT;
private final StringBuilder seq = new StringBuilder(64);
private boolean csiIntermediate;
/**
* @param responder what to do with the answers a terminal owes the shell
* (device attributes, cursor position); may be ignored
* forever, but a program asking and never hearing keeps
* asking
*/
public TerminalEmulator(int cols, int rows, Consumer<String> responder) {
this.responder = responder;
resize(cols, rows);
reset();
}
// ── Feeding it ────────────────────────────────────────────────────────
/** Hands the emulator one chunk of what the shell printed. */
public void feed(String text) {
popped = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
switch (parseState) {
case ST_TEXT -> textChar(c);
case ST_ESC -> escapeChar(c);
case ST_CSI -> csiChar(c);
case ST_STRING -> {
if (c == '\u0007') parseState = ST_TEXT; // BEL ends it
else if (c == '\u001B') parseState = ST_STRING_ESC; // maybe ST…
}
case ST_STRING_ESC -> parseState = (c == '\\') ? ST_TEXT : ST_ESC;
case ST_CHARSET -> parseState = ST_TEXT; // eat the designator
}
}
}
/** Types plain text at the cursor, the way a pane's own notes arrive. */
public void writeText(String text, int color) {
int previousPen = pen;
pen = color;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') lineFeed();
else if (c == '\r') cx = 0;
else if (c >= 32) printChar(c);
}
pen = previousPen;
}
/** Clears the screen and the cursor: a new shell's clean slate. */
public void reset() {
main = new Screen(cols, rows);
alt = new Screen(cols, rows);
onAlt = false;
regionTop = 0;
regionBottom = rows - 1;
cx = 0;
cy = 0;
pen = DEFAULT_COLOR;
wrapNext = false;
autoWrap = true;
appCursorKeys = false;
cursorVisible = true;
parseState = ST_TEXT;
}
/** Drops the scrollback: its shell is gone with it. */
public void clearScrollback() {
scrollback.clear();
}
// ── What the view needs to draw ───────────────────────────────────────
public int cols() { return cols; }
public int rows() { return rows; }
public int scrollbackSize() { return scrollback.size(); }
public int poppedLastFeed() { return popped; }
public boolean cursorVisible() { return cursorVisible; }
public boolean appCursorKeys() { return appCursorKeys; }
public boolean onAlternateScreen() { return onAlt; }
/** The cursor's row counted from the bottom of the content — its screen row plus the scrollback above it. */
public int cursorContentLine() { return scrollback.size() + cy; }
/** The character of one content line: the scrollback first, then the screen. */
public char charAt(int contentLine, int x) {
return rowAt(contentLine).ch[x];
}
public int colorAt(int contentLine, int x) {
return rowAt(contentLine).fg[x];
}
private Row rowAt(int contentLine) {
return contentLine < scrollback.size()
? scrollback.get(contentLine)
: screen().rows.get(contentLine - scrollback.size());
}
/** The content line the cursor sits on, in absolute coordinates, for the pane to draw a block over. */
public int cursorX() { return cx; }
// ── Resizing the window ───────────────────────────────────────────────
public void resize(int newCols, int newRows) {
if (main == null) { cols = newCols; rows = newRows; return; }
main = main.resized(newCols, newRows);
alt = alt.resized(newCols, newRows);
resizeScrollback(newCols);
cols = newCols;
rows = newRows;
regionTop = 0;
regionBottom = rows - 1;
clampCursor();
wrapNext = false;
}
/**
* Scrollback rows were cut to the old width and must not be read past
* it (or the view, drawn column by column over the new width, walks off
* the end of one): the same treatment as the screens — copy what still
* fits, leave the rest blank.
*/
private void resizeScrollback(int newCols) {
for (int i = 0; i < scrollback.size(); i++) {
Row old = scrollback.get(i);
if (old.ch.length == newCols) continue;
Row fresh = new Row(newCols);
for (int x = 0; x < Math.min(old.ch.length, newCols); x++) {
fresh.ch[x] = old.ch[x];
fresh.fg[x] = old.fg[x];
}
scrollback.set(i, fresh);
}
}
// ── The sequences, one by one ─────────────────────────────────────────
private Screen screen() {
return onAlt ? alt : main;
}
private void textChar(char c) {
if (c == '\u001B') { parseState = ST_ESC; return; }
switch (c) {
case '\u009B' -> startCsi(); // CSI as one character
case '\u0090', '\u0098', '\u009D', '\u009E', '\u009F' -> parseState = ST_STRING;
case '\u0084' -> lineFeed(); // IND
case '\u008D' -> reverseIndex(); // RI
case '\u0085' -> { cx = 0; lineFeed(); } // NEL
case '\u0007' -> { } // BEL: nothing to beep with
case '\b' -> { if (cx > 0) cx--; wrapNext = false; }
case '\t' -> { cx = Math.min(cols - 1, (cx / 8 + 1) * 8); wrapNext = false; }
case '\n', 0x0B, 0x0C -> lineFeed();
case '\r' -> { cx = 0; wrapNext = false; }
case 0, 0x7F -> { }
default -> { if (c >= 32) printChar(c); }
}
}
private void escapeChar(char c) {
parseState = ST_TEXT;
switch (c) {
case '[' -> startCsi();
// OSC (titles and such), DCS, SOS, PM, APC: recognised, swallowed.
case ']', 'P', 'X', '^', '_' -> parseState = ST_STRING;
case '(', ')', '*', '+' -> parseState = ST_CHARSET; // charset designation
case '7' -> { savedCx = cx; savedCy = cy; savedPen = pen; }
case '8' -> { cx = savedCx; cy = savedCy; pen = savedPen; clampCursor(); }
case 'D' -> lineFeed(); // IND
case 'M' -> reverseIndex(); // RI
case 'E' -> { cx = 0; lineFeed(); } // NEL
case 'c' -> reset(); // RIS
default -> { } // '=', '>', ' ', forgotten ones
}
}
private void startCsi() {
parseState = ST_CSI;
seq.setLength(0);
csiIntermediate = false;
}
private void csiChar(char c) {
if (c >= '0' && c <= '?') {
if (seq.length() < 64) seq.append(c); // parameter bytes, '?' and '>' included
return;
}
if (c >= ' ' && c <= '/') { csiIntermediate = true; return; } // intermediates: remembered, ignored
parseState = ST_TEXT;
if (c >= '@' && c <= '~') dispatchCsi(c);
}
private void dispatchCsi(char finalByte) {
String s = seq.toString();
boolean priv = !s.isEmpty()
&& (s.charAt(0) == '?' || s.charAt(0) == '>' || s.charAt(0) == '!' || s.charAt(0) == '=');
String body = priv ? s.substring(1) : s;
String[] parts = body.isEmpty() ? new String[0] : body.split(";", -1);
switch (finalByte) {
case 'A' -> { cy = clamp(cy - param(parts, 0, 1), 0, rows - 1); wrapNext = false; }
case 'B' -> { cy = clamp(cy + param(parts, 0, 1), 0, rows - 1); wrapNext = false; }
case 'C' -> { cx = clamp(cx + param(parts, 0, 1), 0, cols - 1); wrapNext = false; }
case 'D' -> { cx = clamp(cx - param(parts, 0, 1), 0, cols - 1); wrapNext = false; }
case 'E' -> { cy = clamp(cy + param(parts, 0, 1), 0, rows - 1); cx = 0; wrapNext = false; }
case 'F' -> { cy = clamp(cy - param(parts, 0, 1), 0, rows - 1); cx = 0; wrapNext = false; }
case 'G', '`' -> { cx = clamp(param(parts, 0, 1) - 1, 0, cols - 1); wrapNext = false; }
case 'd' -> { cy = clamp(param(parts, 0, 1) - 1, 0, rows - 1); wrapNext = false; }
case 'H', 'f' -> {
cy = clamp(param(parts, 0, 1) - 1, 0, rows - 1);
cx = clamp(param(parts, 1, 1) - 1, 0, cols - 1);
wrapNext = false;
}
case 'J' -> eraseDisplay(param(parts, 0, 0));
case 'K' -> eraseLine(param(parts, 0, 0));
case 'X' -> eraseChars(param(parts, 0, 1));
case 'L' -> insertLines(param(parts, 0, 1));
case 'M' -> deleteLines(param(parts, 0, 1));
case '@' -> insertChars(param(parts, 0, 1));
case 'P' -> deleteChars(param(parts, 0, 1));
case 'S' -> scrollRegionUp(regionTop, regionBottom, param(parts, 0, 1));
case 'T' -> scrollRegionDown(regionTop, regionBottom, param(parts, 0, 1));
case 'r' -> setScrollRegion(parts);
case 'm' -> applySgr(parts);
// Save and restore, but only the public ones: CSI ? u is kitty's
// keyboard probe, and answering it with a cursor teleport would
// corrupt whoever is mid-redraw. Silence is the right answer.
case 's' -> { if (!priv && !csiIntermediate) { savedCx = cx; savedCy = cy; savedPen = pen; } }
case 'u' -> { if (!priv && !csiIntermediate) { cx = savedCx; cy = savedCy; pen = savedPen; clampCursor(); } }
case 'n' -> reportStatus(parts);
case 'c' -> {
if (csiIntermediate) break;
// Device attributes: who are you — somebody with a VT220's
// manners, which is exactly what this emulator obeys.
answer(priv ? "\u001B[>0;0;0c" : "\u001B[?62;1;2;4;6;9c");
}
case 'q' -> {
// XTVERSION (no intermediates); DECSCUSR wears one and passes.
if (priv && !csiIntermediate) answer("\u001BP>|codecraft terminal 1.0\u001B\\");
}
case 'h', 'l' -> setModes(finalByte == 'h', parts);
default -> { } // everything else: recognised, and nothing here obeys it
}
}
// ── What they do to the screen ────────────────────────────────────────
private void printChar(char c) {
if (wrapNext && autoWrap) {
cx = 0;
lineFeed();
}
Row row = screen().rows.get(cy);
row.ch[cx] = c;
row.fg[cx] = pen;
if (cx == cols - 1) wrapNext = autoWrap;
else cx++;
}
private void lineFeed() {
if (cy == regionBottom) scrollRegionUp(regionTop, regionBottom, 1);
else cy++;
}
private void reverseIndex() {
if (cy == regionTop) scrollRegionDown(regionTop, regionBottom, 1);
else cy--;
}
private void scrollRegionUp(int top, int bottom, int n) {
top = clamp(top, 0, rows - 1);
bottom = clamp(bottom, 0, rows - 1);
Screen s = screen();
for (int k = 0; k < n; k++) {
Row gone = s.rows.remove(top);
s.rows.add(bottom, new Row(cols));
// The main screen's top row scrolling out is the one kind of
// scrolling worth remembering; the alternate screen's is not.
if (!onAlt && top == 0) {
scrollback.add(gone);
if (scrollback.size() > MAX_SCROLLBACK) scrollback.remove(0);
popped++;
}
}
}
private void scrollRegionDown(int top, int bottom, int n) {
top = clamp(top, 0, rows - 1);
bottom = clamp(bottom, 0, rows - 1);
Screen s = screen();
for (int k = 0; k < n; k++) {
s.rows.add(top, new Row(cols));
s.rows.remove(bottom);
}
}
private void setScrollRegion(String[] parts) {
int top = param(parts, 0, 1);
int bottom = param(parts, 1, rows);
if (top < 1 || bottom > rows || top >= bottom) return;
regionTop = top - 1;
regionBottom = bottom - 1;
cx = 0;
cy = 0;
wrapNext = false;
}
private void eraseDisplay(int mode) {
switch (mode) {
case 0 -> {
eraseLineFrom(cx);
for (int y = cy + 1; y < rows; y++) screen().rows.set(y, new Row(cols));
}
case 1 -> {
for (int y = 0; y < cy; y++) screen().rows.set(y, new Row(cols));
eraseLineTo(cx);
}
default -> {
for (int y = 0; y < rows; y++) screen().rows.set(y, new Row(cols));
if (mode == 3) scrollback.clear();
}
}
}
private void eraseLine(int mode) {
switch (mode) {
case 0 -> eraseLineFrom(cx);
case 1 -> eraseLineTo(cx);
default -> screen().rows.set(cy, new Row(cols));
}
}
private void eraseLineFrom(int from) {
Row row = screen().rows.get(cy);
for (int x = clamp(from, 0, cols - 1); x < cols; x++) row.ch[x] = ' ';
}
private void eraseLineTo(int to) {
Row row = screen().rows.get(cy);
for (int x = 0; x <= clamp(to, 0, cols - 1); x++) row.ch[x] = ' ';
}
private void eraseChars(int n) {
Row row = screen().rows.get(cy);
for (int x = cx; x < Math.min(cols, cx + n); x++) row.ch[x] = ' ';
}
private void insertLines(int n) {
if (cy < regionTop || cy > regionBottom) return;
n = Math.min(n, regionBottom - cy + 1);
Screen s = screen();
for (int k = 0; k < n; k++) {
s.rows.add(cy, new Row(cols));
s.rows.remove(regionBottom + 1);
}
}
private void deleteLines(int n) {
if (cy < regionTop || cy > regionBottom) return;
n = Math.min(n, regionBottom - cy + 1);
Screen s = screen();
for (int k = 0; k < n; k++) {
s.rows.remove(cy);
s.rows.add(regionBottom, new Row(cols));
}
}
private void insertChars(int n) {
Row row = screen().rows.get(cy);
n = Math.min(n, cols - cx);
for (int x = cols - 1; x >= cx + n; x--) {
row.ch[x] = row.ch[x - n];
row.fg[x] = row.fg[x - n];
}
for (int x = cx; x < Math.min(cols, cx + n); x++) row.ch[x] = ' ';
}
private void deleteChars(int n) {
Row row = screen().rows.get(cy);
n = Math.min(n, cols - cx);
for (int x = cx; x < cols - n; x++) {
row.ch[x] = row.ch[x + n];
row.fg[x] = row.fg[x + n];
}
for (int x = Math.max(0, cols - n); x < cols; x++) row.ch[x] = ' ';
}
private void setModes(boolean on, String[] parts) {
for (int i = 0; i < parts.length; i++) {
switch (param(parts, i, 0)) {
case 1 -> appCursorKeys = on; // DECCKM: arrows send ESC O x
case 7 -> autoWrap = on; // DECAWM
case 25 -> cursorVisible = on; // DECTCEM
case 47, 1047, 1049 -> {
// The alternate screen: full-screen programs live here,
// and leave the main screen — and its scrollback — alone.
if (on) enterAlt();
else leaveAlt();
}
default -> { } // 6, 12, 2004, mouse…: acknowledged, unused
}
}
}
/** The program asked for its own screen; the main one keeps the lights on underneath. */
private void enterAlt() {
if (onAlt) return;
savedCx = cx;
savedCy = cy;
alt = new Screen(cols, rows);
onAlt = true;
cx = 0;
cy = 0;
wrapNext = false;
}
/** …and gave it back. */
private void leaveAlt() {
if (!onAlt) return;
onAlt = false;
cx = savedCx;
cy = savedCy;
clampCursor();
wrapNext = false;
}
/** The emulator's turn to speak: the answers a terminal owes. */
private void answer(String response) {
responder.accept(response);
}
private void reportStatus(String[] parts) {
if (csiIntermediate) return; // DECRQM is asking, not this
int op = param(parts, 0, 0);
if (op == 5) answer("\u001B[0n");
else if (op == 6) answer("\u001B[" + (cy + 1) + ";" + (cx + 1) + "R");
}
// ── Colours ───────────────────────────────────────────────────────────
/** Applies one SGR ("select graphic rendition") parameter list to the pen. */
private void applySgr(String[] parts) {
for (int i = 0; i < parts.length; i++) {
int code = param(parts, i, 0);
switch (code) {
case 0, 22, 39 -> pen = DEFAULT_COLOR; // reset / normal intensity / default fg
case 30, 31, 32, 33, 34, 35, 36, 37 -> pen = ANSI_COLORS[code - 30];
case 90, 91, 92, 93, 94, 95, 96, 97 -> pen = ANSI_COLORS[code - 82];
case 38 -> i = readColor(parts, i, true); // 38;5;n or 38;2;r;g;b
case 48 -> i = readColor(parts, i, false); // background: parsed past, not painted
default -> {
// 1 bold, 4 underline: cells carry no such attribute, and
// these must not eat the codes that follow them.
}
}
}
}
/**
* Reads a 256-colour or true-colour argument list, applying it to the pen
* when it is a foreground. Returns the index of the last part consumed.
*/
private int readColor(String[] parts, int at, boolean foreground) {
try {
if (at + 2 >= parts.length) return parts.length;
int mode = Integer.parseInt(parts[at + 1]);
if (mode == 5) {
if (foreground) pen = palette256(Integer.parseInt(parts[at + 2]));
return at + 2;
}
if (mode == 2 && at + 4 < parts.length) {
if (foreground) {
pen = 0xFF000000
| (Integer.parseInt(parts[at + 2]) & 0xFF) << 16
| (Integer.parseInt(parts[at + 3]) & 0xFF) << 8
| (Integer.parseInt(parts[at + 4]) & 0xFF);
}
return at + 4;
}
} catch (NumberFormatException e) {
// Garbage parameters: leave the pen where it was.
}
return parts.length;
}
/** The xterm 256-colour palette: the 16 above, a 6x6x6 cube, a grey ramp. */
private static int palette256(int index) {
if (index < 16) return ANSI_COLORS[index % ANSI_COLORS.length];
if (index <= 231) {
int i = index - 16;
return 0xFF000000 | ramp(i / 36) << 16 | ramp((i / 6) % 6) << 8 | ramp(i % 6);
}
if (index <= 255) {
int grey = 8 + (index - 232) * 10;
return 0xFF000000 | grey << 16 | grey << 8 | grey;
}
return DEFAULT_COLOR;
}
/** The cube's six steps: 0, 95, 135, 175, 215, 255. */
private static int ramp(int step) {
return step == 0 ? 0 : 55 + step * 40;
}
private void clampCursor() {
cx = clamp(cx, 0, cols - 1);
cy = clamp(cy, 0, rows - 1);
}
private static int clamp(int value, int low, int high) {
return Math.max(low, Math.min(value, high));
}
private static int param(String[] parts, int index, int def) {
if (index >= parts.length) return def;
try {
return parts[index].isEmpty() ? def : Integer.parseInt(parts[index].split(":")[0]);
} catch (NumberFormatException e) {
return def;
}
}
}

View File

@@ -6,12 +6,24 @@ import org.jspecify.annotations.NonNull;
public class TextEditorScreen extends EditorScreen { public class TextEditorScreen extends EditorScreen {
private final EditorManager editorManager;
/** True while the left mouse button is held down during a drag-select. */ /** True while the left mouse button is held down during a drag-select. */
public TextEditorScreen() { public TextEditorScreen(EditorManager editorManager) {
super(Component.literal("Codecraft Editor")); super(Component.literal("Codecraft Editor"));
this.editorManager = editorManager;
} }
/**
* Closing the editor leaves the live editing session, so the other players
* stop seeing this caret and stop sending theirs.
*/
@Override
public void onClose() {
editorManager.onEditorClosed(this);
super.onClose();
}
@Override @Override
public void extractRenderState( public void extractRenderState(
@@ -23,13 +35,7 @@ public class TextEditorScreen extends EditorScreen {
super.extractRenderState(graphics, mouseX, mouseY, delta); super.extractRenderState(graphics, mouseX, mouseY, delta);
for (Widget widget : widgets) { for (Widget widget : widgets) {
widget.draw( widget.draw(graphics, mouseX, mouseY, delta);
graphics,
mouseX,
mouseY,
delta
);
} }
} }
} }

View File

@@ -69,11 +69,15 @@ public abstract class Widget {
public abstract boolean handleKeyPressed(KeyEvent event); public abstract boolean handleKeyPressed(KeyEvent event);
public abstract boolean handleCharTyped(CharacterEvent event); public abstract boolean handleCharTyped(CharacterEvent event);
public abstract boolean handleMouseClicked(MouseButtonEvent event); public abstract boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick);
public abstract boolean handleMouseDragged(MouseButtonEvent event); public abstract boolean handleMouseDragged(MouseButtonEvent event);
public abstract boolean handleMouseReleased(MouseButtonEvent event); public abstract boolean handleMouseReleased(MouseButtonEvent event);
public abstract boolean handleMouseScrolled(double scrollY); public abstract boolean handleMouseScrolled(double scrollY);
/** Called when a click lands on another widget: this one loses the keyboard. */
public void handleFocusLost() {
}
public int getZIndex() { public int getZIndex() {
return z_index; return z_index;
} }

View File

@@ -0,0 +1,26 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* Completion for the {@code world} global — block access provided by codecraft
* itself. Keep in sync with the runtime wrapper and {@code LuaApiDocs}.
*/
public class WorldLibrary implements LuaLibrary {
private static final List<CompletionItem> MEMBERS = List.of(
CompletionItem.method("set_block", "set_block("),
CompletionItem.method("remove_block", "remove_block("),
CompletionItem.method("get_block", "get_block(")
);
@Override
public String name() {
return "world";
}
@Override
public List<CompletionItem> members() {
return MEMBERS;
}
}

View File

@@ -1,13 +1,32 @@
package com.aranroig; package com.aranroig;
import com.aranroig.collab.DocumentManager;
import com.aranroig.editor.EditorFile; 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.ClientboundProjectFilesPayload;
import com.aranroig.payloads.ClientboundRenameFilePayload;
import com.aranroig.payloads.ClientboundSaveCodePayload; 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.ServerboundRequestProjectPayload;
import com.aranroig.payloads.ServerboundRunCodePayload; import com.aranroig.payloads.ServerboundRunCodePayload;
import com.aranroig.payloads.ServerboundSaveCodePayload; import com.aranroig.payloads.ServerboundSaveCodePayload;
import com.aranroig.wrapper.ChatLogger; import com.aranroig.payloads.ServerboundShellInputPayload;
import com.aranroig.wrapper.WorldApi; import com.aranroig.payloads.ServerboundShellResizePayload;
import com.aranroig.payloads.ServerboundSpawnShellPayload;
import com.aranroig.shell.ShellManager;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry; import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
@@ -19,8 +38,6 @@ import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer; import net.minecraft.server.level.ServerPlayer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.luaj.LuaJ;
import java.util.List; import java.util.List;
@@ -42,8 +59,37 @@ public class Codecraft implements ModInitializer {
PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC); PayloadTypeRegistry.serverboundPlay().register(ServerboundSaveCodePayload.TYPE, ServerboundSaveCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRunCodePayload.TYPE, ServerboundRunCodePayload.CODEC); PayloadTypeRegistry.serverboundPlay().register(ServerboundRunCodePayload.TYPE, ServerboundRunCodePayload.CODEC);
PayloadTypeRegistry.serverboundPlay().register(ServerboundRequestProjectPayload.TYPE, ServerboundRequestProjectPayload.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(ClientboundSaveCodePayload.TYPE, ClientboundSaveCodePayload.CODEC);
PayloadTypeRegistry.clientboundPlay().register(ClientboundProjectFilesPayload.TYPE, ClientboundProjectFilesPayload.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) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundRequestProjectPayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer(); MinecraftServer server = context.player().level().getServer();
@@ -53,8 +99,9 @@ public class Codecraft implements ModInitializer {
List<EditorFile> files = savedData.getEditorFiles(); List<EditorFile> files = savedData.getEditorFiles();
// Seed a default entrypoint so the client always has at least one file. // 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()) { if(files.isEmpty()) {
files.add(new EditorFile("main.lua", "")); files.add(new EditorFile(ProjectPath.ENTRYPOINT, ""));
savedData.setEditorFiles(files); savedData.setEditorFiles(files);
} }
@@ -62,36 +109,56 @@ public class Codecraft implements ModInitializer {
}); });
ServerPlayNetworking.registerGlobalReceiver(ServerboundSaveCodePayload.TYPE, (payload, context) -> { 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(); 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()); 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) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer(); MinecraftServer server = context.player().level().getServer();
if(server == null) return; if(server == null) return;
@@ -104,12 +171,10 @@ public class Codecraft implements ModInitializer {
String entrypoint = payload.data().getEntrypoint(); String entrypoint = payload.data().getEntrypoint();
LOGGER.info("Running entrypoint {}", entrypoint); LOGGER.info("Running entrypoint {}", entrypoint);
EditorFile target = null; EditorFile target = findByName(files, entrypoint);
for(EditorFile file : files) { if(target == null) {
if(file.getName().equals(entrypoint)) { // Worlds seeded while names still carried the extension.
target = file; target = findByName(files, entrypoint + ProjectPath.LEGACY_EXTENSION);
break;
}
} }
if(target == null) { if(target == null) {
@@ -117,12 +182,12 @@ public class Codecraft implements ModInitializer {
return; return;
} }
Lua lua = new LuaJ(); // Fresh runtime per run: this drops the listeners the player
lua.push(ChatLogger.print(player)); // registered last time (reset-on-rerun) and registers print/world/
lua.setGlobal("print"); // events on a brand-new Lua state.
WorldApi.register(lua, player); ScriptRuntime runtime = ScriptRuntimeManager.startRun(player);
try { try {
lua.run(target.getText()); runtime.run(target.getText());
} catch (Exception e) { } catch (Exception e) {
LOGGER.warn("Error running " + entrypoint, e); LOGGER.warn("Error running " + entrypoint, e);
player.sendSystemMessage(Component.literal("§ccodecraft error: " + e.getMessage())); 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) { public static Identifier id(String path) {
return Identifier.fromNamespaceAndPath(MOD_ID, path); return Identifier.fromNamespaceAndPath(MOD_ID, path);
} }

View File

@@ -20,15 +20,34 @@ public class SavedProjectData extends SavedData {
} }
public SavedProjectData(List<EditorFile> editorFiles) { 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() { public List<EditorFile> getEditorFiles() {
return editorFiles; return editorFiles;
} }
public void setEditorFiles(List<EditorFile> 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(); setDirty();
} }
@@ -56,9 +75,9 @@ public class SavedProjectData extends SavedData {
return new SavedProjectData(); // Return a new instance if the level is null. 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'. // 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. // using the Codec to decode the NBT into our saved data.
return level.getDataStorage().computeIfAbsent(TYPE); return level.getDataStorage().computeIfAbsent(TYPE);
} }

View 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)];
}
}
}

View File

@@ -1,142 +1,125 @@
package com.aranroig.docs; 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; import java.util.List;
/** /**
* The in-game reference for every Lua global this mod exposes to user scripts. * 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 * <p>The catalog is data, not code: it lives in
* wrappers in {@code com.aranroig.wrapper} (currently {@code world} from * {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from
* {@link com.aranroig.wrapper.WorldApi} and the {@code print} helper). The * the mod resources on first access, so documentation can be edited (and, once
* client editor reads it to render the browsable documentation panel, so it is * packed, overridden) without touching Java. It describes the functions
* the single source of truth shown to players.</p> * 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> * <p>Keep it in sync with the wrapper implementations and {@code docs/lua-api.md}.</p>
*/ */
public final class LuaApiDocs { 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() { 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. */ /** All documented topics, in display order. */
public static List<Topic> topics() { public static synchronized List<Topic> topics() {
return TOPICS; if (cache == null) {
cache = load();
}
return cache;
} }
/** Flattened list of every documented function, across all topics. */ /** Flattened list of every documented function, across all topics. */
public static List<FunctionDoc> functions() { 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();
} }
} }

View 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;
}
}

View File

@@ -38,6 +38,10 @@ public class EditorFile {
return name; return name;
} }
public void setName(String name) {
this.name = name;
}
public String getText() { public String getText() {
return text; return text;
} }

View 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;
}
}

View 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;
}
}

View 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);
}
}

View 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;
}
}

View 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);
}
}
}

View 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();
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View 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.
}
}
}

View 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.
}
}
}

View 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"
}
]
}
]
}
]
}