Mes coses divertides
Some checks failed
build / build (push) Failing after 52s

This commit is contained in:
2026-10-08 01:54:02 +02:00
parent 5897870725
commit b7e416d335
35 changed files with 2420 additions and 346 deletions

View File

@@ -27,7 +27,7 @@ Loom uses `splitEnvironmentSourceSets()`:
Flow: client editor → custom payloads → server → persisted project. 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** (`com.aranroig.project.ProjectStore`): the project lives on the server's disk under `config/codecraft/` as plain `.lua` files mirroring the project paths (`lib/gui/theme` → `config/codecraft/lib/gui/theme.lua`), so it can also be edited with external editors — the project is re-read from disk every time the editor opens. Explicit saves write synchronously; keystrokes go to a pending map a daemon thread flushes ~1s after typing settles, and everything pending is flushed on server stop. Names are sanitized (`..` etc. refused) before touching the filesystem. `SavedProjectData` (world `SavedData`) is legacy: kept only to migrate a world's scripts into the config folder once, on `SERVER_STARTED`, when the config folder holds no scripts yet. The project is now per server-install, not per world.
- **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. - **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.

View File

@@ -20,6 +20,8 @@ repositories {
loom { loom {
splitEnvironmentSourceSets() splitEnvironmentSourceSets()
accessWidenerPath = file("src/main/resources/codecraft.accesswidener")
mods { mods {
"codecraft" { "codecraft" {
sourceSet sourceSets.main sourceSet sourceSets.main

View File

@@ -32,6 +32,22 @@ without the decimal, concatenate them into a string:
print("blocks placed: " .. 12) -- -> blocks placed: 12 print("blocks placed: " .. 12) -- -> blocks placed: 12
``` ```
## run(command)
Runs a Minecraft command from the server command source, with full server permissions
and no player position or entity. The command may be written with or without a leading
slash. The function returns `true` when the command is submitted, or `false` and a
reason when the argument is invalid. A `true` result means the command was submitted;
it does not guarantee the command succeeded.
```lua
run("time set day")
run("weather clear")
```
For commands that need a player or coordinates, use explicit selectors and coordinates
in the command string. The command source is the server, not the player running Lua.
## Blocks ## Blocks
Coordinates are **absolute world coordinates** — never relative to the player — in the Coordinates are **absolute world coordinates** — never relative to the player — in the
@@ -43,6 +59,11 @@ use them in the script.
| `world.set_block(x, y, z, block)` | `true`, or `false` and a reason | | `world.set_block(x, y, z, block)` | `true`, or `false` and a reason |
| `world.remove_block(x, y, z[, drops])` | `true`, or `false` and a reason | | `world.remove_block(x, y, z[, drops])` | `true`, or `false` and a reason |
| `world.get_block(x, y, z)` | block id string, or `nil` and a reason | | `world.get_block(x, y, z)` | block id string, or `nil` and a reason |
| `world.get_dimension()` | dimension id |
| `world.get_time()` / `world.set_time(ticks)` | world clock time in ticks |
| `world.get_weather()` / `world.set_weather(weather[, ticks])` | `clear`, `rain` or `thunder` |
| `world.get_biome(x, y, z)` | biome id, or `nil` and a reason |
| `world.players()` | array of online player names |
### world.set_block(x, y, z, block) ### world.set_block(x, y, z, block)
@@ -92,6 +113,106 @@ if block ~= "minecraft:air" then
end end
``` ```
## Entities
Entity ids returned by `entities.nearby` and `entities.spawn` are UUID strings. The
nearby query only checks loaded entities in the executing player's current dimension;
it excludes the script owner, its radius defaults to 16 blocks and is capped at 128.
Entity positions are absolute.
| Function | Purpose |
| -------- | ------- |
| `entities.nearby([radius[, type]])` | UUIDs of nearby entities, optionally filtered by type id |
| `entities.spawn(type, x, y, z)` | Spawn a summonable entity and return its UUID |
| `entities.get(uuid)` | Return type id, x, y, z and custom/display name |
| `entities.teleport(uuid, x, y, z)` | Move an entity in its current dimension |
| `entities.remove(uuid)` | Remove an entity (players are protected) |
| `entities.set_name(uuid, name)` | Set a visible custom name |
| `entities.set_health(uuid, health)` | Set living entity health up to its maximum |
```lua
local ids = entities.nearby(12, "minecraft:zombie")
for _, id in ipairs(ids) do
local type, x, y, z, name = entities.get(id)
print(name .. " is at " .. x .. ", " .. y .. ", " .. z)
end
```
## Scoreboards
Scoreboard helpers operate on the server scoreboard. Objective names follow vanilla's
1–16 character limit. `create_objective` defaults to the `dummy` criterion; built-in
criteria such as `deathCount` and `health` are also accepted. `display` accepts `list`,
`sidebar` or `below_name`.
| Function | Purpose |
| -------- | ------- |
| `scoreboard.create_objective(name[, criterion[, display_name]])` | Create an objective |
| `scoreboard.remove_objective(name)` | Remove an objective |
| `scoreboard.set(player, objective, value)` | Set a score |
| `scoreboard.add(player, objective, value)` | Add to a score |
| `scoreboard.get(player, objective)` | Read a score (`nil` when unset) |
| `scoreboard.reset(player[, objective])` | Clear one score or all of a player's scores |
| `scoreboard.display(objective, slot)` | Show an objective in a display slot |
```lua
scoreboard.create_objective("coins", "dummy", "Coins")
scoreboard.add("Alex", "coins", 5)
scoreboard.display("coins", "sidebar")
```
## HUD and boss bars
Titles, subtitles and action-bar messages go to the player who ran the script by default;
pass an online player name to target someone else. Title timings are measured in ticks
(20 ticks per second). Boss bars are saved server-side, identified by a resource id; ids
without a namespace use `codecraft:`. A new boss bar is shown to the script owner by
default. `bossbar_visible` can add or remove any online player.
| Function | Purpose |
| -------- | ------- |
| `hud.title(text)` / `hud.subtitle(text)` | Show a title or subtitle |
| `hud.action_bar(text)` | Show text above the hotbar |
| `hud.title_times(fade_in, stay, fade_out)` | Set title timings in ticks |
| `hud.clear_titles([reset])` | Clear title and subtitle |
| `hud.bossbar_add(id, name[, max])` | Create a boss bar (max defaults to 100) |
| `hud.bossbar_remove(id)` | Remove a boss bar |
| `hud.bossbar_value(id, value)` / `hud.bossbar_max(id, value)` | Change boss bar progress |
| `hud.bossbar_visible(id, visible)` | Show or hide it for the script owner |
```lua
hud.title_times(10, 60, 20)
hud.title("Welcome!")
hud.action_bar("You have " .. scoreboard.get("Alex", "coins") .. " coins")
hud.bossbar_add("round", "Round progress", 10)
hud.bossbar_value("round", 3)
```
## Items and inventories
Item ids can omit the `minecraft:` namespace. Inventory slots are indexed from 0 to 35
in the player's main inventory. The optional player argument names an online player;
when omitted, the script owner is used. Excess items from `items.give` drop at the
target player's feet. `items.clear` and `items.count` only affect the main inventory.
| Function | Purpose |
| -------- | ------- |
| `items.give(item, count[, player])` | Give items; overflow drops at the player |
| `items.count(item[, player])` | Count matching items in the main inventory |
| `items.clear(item[, player])` | Remove matching items; also returns the removed count |
| `items.get_slot(slot[, player])` | Read an inventory slot (item id and count, or `nil`) |
| `items.set_slot(slot, item, count[, player])` | Replace a slot; count 0 clears it |
```lua
items.give("gold_ingot", 8)
print("You now have " .. items.count("minecraft:gold_ingot"))
items.set_slot(0, "minecraft:diamond_sword", 1)
```
All mutating helpers return `true` on success or `false` and a reason on invalid input
or missing targets. Read helpers return their value, or `nil` and a reason when lookup
fails.
## Events ## Events
Listeners let a script react to the game *after* it has finished running. Register one Listeners let a script react to the game *after* it has finished running. Register one
@@ -125,7 +246,7 @@ the event:
cheap: they run twenty times a second, and a slow one lags the whole server. 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 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 registered them — they can call `print` and the Minecraft API tables. An error inside a
callback is printed to the owner's chat; it never stops the game or the other callback is printed to the owner's chat; it never stops the game or the other
listeners. listeners.

View File

@@ -42,7 +42,7 @@ public class CompletionProvider {
for (String fn : new String[]{ for (String fn : new String[]{
"assert", "collectgarbage", "dofile", "error", "getmetatable", "assert", "collectgarbage", "dofile", "error", "getmetatable",
"ipairs", "load", "loadfile", "next", "pairs", "ipairs", "load", "loadfile", "next", "pairs",
"pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "pcall", "print", "run", "rawequal", "rawget", "rawlen", "rawset",
"require", "select", "setmetatable", "tonumber", "tostring", "require", "select", "setmetatable", "tonumber", "tostring",
"type", "unpack", "xpcall" "type", "unpack", "xpcall"
}) items.add(CompletionItem.method(fn + "(", fn + "(")); }) items.add(CompletionItem.method(fn + "(", fn + "("));
@@ -71,6 +71,7 @@ public class CompletionProvider {
libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library
libraries.add(new WorldLibrary()); // block access provided by codecraft libraries.add(new WorldLibrary()); // block access provided by codecraft
libraries.add(new EventsLibrary()); // game event listeners provided by codecraft libraries.add(new EventsLibrary()); // game event listeners provided by codecraft
libraries.addAll(MinecraftLibraries.all()); // server-side Minecraft APIs
Map<String, List<CompletionItem>> members = new LinkedHashMap<>(); Map<String, List<CompletionItem>> members = new LinkedHashMap<>();
for (LuaLibrary library : libraries) { for (LuaLibrary library : libraries) {

View File

@@ -5,6 +5,7 @@ import com.aranroig.docs.FunctionDoc;
import com.aranroig.docs.LuaApiDocs; import com.aranroig.docs.LuaApiDocs;
import com.aranroig.docs.Topic; import com.aranroig.docs.Topic;
import com.aranroig.client.editor.LuaHighlighter.Span; import com.aranroig.client.editor.LuaHighlighter.Span;
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;
import net.minecraft.client.input.CharacterEvent; import net.minecraft.client.input.CharacterEvent;
@@ -54,24 +55,14 @@ public class EditorDocsPanel extends Widget {
private final LuaHighlighter highlighter = new LuaHighlighter(); private final LuaHighlighter highlighter = new LuaHighlighter();
// ── Colors (same palette as the rest of the editor) ─────────────────── /** Code examples currently rendered on the detail page, with screen-space hitboxes. */
private final List<CodeBlockLayout> codeBlocks = new ArrayList<>();
private int activeExample = -1;
private int selectionAnchor = -1;
private int selectionCursor = -1;
private boolean selectingCode = false;
private static final int COLOR_OVERLAY = 0xB0000000; private record CodeBlockLayout(int index, String code, int x, int y, int width, int height) {}
private static final int COLOR_PANEL_BG = 0xFF1E1E1E;
private static final int COLOR_BORDER = 0xFF666666;
private static final int COLOR_TITLE_BG = 0xFF252525;
private static final int COLOR_TITLE = 0xFFFFFFFF;
private static final int COLOR_HINT = 0xFF555577;
private static final int COLOR_TEXT = 0xFFD4D4D4;
private static final int COLOR_DIM = 0xFF888888;
private static final int COLOR_TOPIC = 0xFF4EC9B0;
private static final int COLOR_SIGNATURE = 0xFFDCDCAA;
private static final int COLOR_PARAM_NAME = 0xFF9CDCFE;
private static final int COLOR_SECTION = 0xFF569CD6;
private static final int COLOR_ROW_SELECTED = 0xFF383868;
private static final int COLOR_ROW_HOVER = 0xFF2A2A3A;
private static final int COLOR_LIST_BG = 0xFF1A1A1A;
private static final int COLOR_CODE_BG = 0xFF252525;
// ── Layout ──────────────────────────────────────────────────────────── // ── Layout ────────────────────────────────────────────────────────────
@@ -124,6 +115,7 @@ public class EditorDocsPanel extends Widget {
public void close() { public void close() {
visible = false; visible = false;
selectingCode = false;
if (editorScreen != null && editorScreen.selectedWidget == this) { if (editorScreen != null && editorScreen.selectedWidget == this) {
editorScreen.selectedWidget = null; editorScreen.selectedWidget = null;
} }
@@ -155,6 +147,9 @@ public class EditorDocsPanel extends Widget {
private void selectRow(int index) { private void selectRow(int index) {
selectedRow = index; selectedRow = index;
detailScroll = 0; detailScroll = 0;
activeExample = -1;
selectionAnchor = -1;
selectionCursor = -1;
} }
private void scrollSelectionIntoView() { private void scrollSelectionIntoView() {
@@ -224,48 +219,48 @@ public class EditorDocsPanel extends Widget {
Math.max(0, detailContentHeight - (panelY2() - listTop() - PAD * 2)))); Math.max(0, detailContentHeight - (panelY2() - listTop() - PAD * 2))));
// Backdrop + panel // Backdrop + panel
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_OVERLAY); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().overlay());
graphics.fill(panelX1(), panelY1(), panelX2(), panelY2(), COLOR_PANEL_BG); graphics.fill(panelX1(), panelY1(), panelX2(), panelY2(), editorManager.theme().background());
graphics.fill(panelX1(), panelY1(), panelX2(), panelY1() + 1, COLOR_BORDER); // top graphics.fill(panelX1(), panelY1(), panelX2(), panelY1() + 1, editorManager.theme().border()); // top
graphics.fill(panelX1(), panelY2() - 1, panelX2(), panelY2(), COLOR_BORDER); // bottom graphics.fill(panelX1(), panelY2() - 1, panelX2(), panelY2(), editorManager.theme().border()); // bottom
graphics.fill(panelX1(), panelY1(), panelX1() + 1, panelY2(), COLOR_BORDER); // left graphics.fill(panelX1(), panelY1(), panelX1() + 1, panelY2(), editorManager.theme().border()); // left
graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), COLOR_BORDER); // right graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), editorManager.theme().border()); // right
drawTitleBar(graphics); drawTitleBar(graphics);
drawList(graphics, mouseX, mouseY); drawList(graphics, mouseX, mouseY);
graphics.fill(listX2() - 1, listTop(), listX2(), panelY2() - 1, COLOR_BORDER); graphics.fill(listX2() - 1, listTop(), listX2(), panelY2() - 1, editorManager.theme().border());
drawDetail(graphics); drawDetail(graphics);
} }
private void drawTitleBar(@NonNull GuiGraphicsExtractor graphics) { private void drawTitleBar(@NonNull GuiGraphicsExtractor graphics) {
int titleH = titleHeight(); int titleH = titleHeight();
graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, COLOR_TITLE_BG); graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, editorManager.theme().raisedBackground());
graphics.text(font, "Lua API documentation", graphics.text(font, "Lua API documentation",
panelX1() + PAD, panelY1() + (titleH - lineHeight()) / 2, COLOR_TITLE, false); panelX1() + PAD, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Close button // Close button
int buttonSize = titleH; int buttonSize = titleH;
int bx = panelX2() - buttonSize; int bx = panelX2() - buttonSize;
boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH; boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH;
if (hovered) { if (hovered) {
graphics.fill(bx, panelY1(), panelX2() - 1, panelY1() + titleH, COLOR_ROW_HOVER); graphics.fill(bx, panelY1(), panelX2() - 1, panelY1() + titleH, editorManager.theme().hoverBackground());
} }
graphics.text(font, "X", graphics.text(font, "X",
bx + (buttonSize - font.width("X")) / 2, bx + (buttonSize - font.width("X")) / 2,
panelY1() + (titleH - lineHeight()) / 2, COLOR_TITLE, false); panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Hint, right-aligned before the button // Hint, right-aligned before the button
String hint = "F1 in the editor opens docs on the word under the cursor"; String hint = "F1 in the editor opens docs on the word under the cursor";
int hintX = bx - 8 - font.width(hint); int hintX = bx - 8 - font.width(hint);
if (hintX > panelX1() + font.width("Lua API documentation") + 12) { if (hintX > panelX1() + font.width("Lua API documentation") + 12) {
graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, COLOR_HINT, false); graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().hint(), false);
} }
} }
private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) { private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1); graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1);
graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, COLOR_LIST_BG); graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, editorManager.theme().sidebarBackground());
int rowH = rowHeight(); int rowH = rowHeight();
for (int i = 0; i < rows.size(); i++) { for (int i = 0; i < rows.size(); i++) {
@@ -277,17 +272,17 @@ public class EditorDocsPanel extends Widget {
boolean hovered = mouseX >= panelX1() && mouseX < listX2() boolean hovered = mouseX >= panelX1() && mouseX < listX2()
&& mouseY >= y && mouseY < y + rowH; && mouseY >= y && mouseY < y + rowH;
if (selected) { if (selected) {
graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, COLOR_ROW_SELECTED); graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, editorManager.theme().selection());
} else if (hovered) { } else if (hovered) {
graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, COLOR_ROW_HOVER); graphics.fill(panelX1() + 1, y, listX2() - 1, y + rowH, editorManager.theme().selectionHover());
} }
if (row.isFunction()) { if (row.isFunction()) {
graphics.text(font, row.label(), panelX1() + PAD + FUNC_INDENT, graphics.text(font, row.label(), panelX1() + PAD + FUNC_INDENT,
y + ROW_PAD / 2, COLOR_TEXT, false); y + ROW_PAD / 2, editorManager.theme().text(), false);
} else { } else {
graphics.text(font, row.label(), panelX1() + PAD, graphics.text(font, row.label(), panelX1() + PAD,
y + ROW_PAD / 2, COLOR_TOPIC, true); y + ROW_PAD / 2, editorManager.theme().syntaxBuiltin(), true);
} }
} }
graphics.disableScissor(); graphics.disableScissor();
@@ -296,6 +291,7 @@ public class EditorDocsPanel extends Widget {
// ── Detail page ─────────────────────────────────────────────────────── // ── Detail page ───────────────────────────────────────────────────────
private void drawDetail(@NonNull GuiGraphicsExtractor graphics) { private void drawDetail(@NonNull GuiGraphicsExtractor graphics) {
codeBlocks.clear();
int x = detailX(); int x = detailX();
int maxWidth = panelX2() - PAD - x; int maxWidth = panelX2() - PAD - x;
int y = detailTop() - detailScroll; int y = detailTop() - detailScroll;
@@ -306,19 +302,19 @@ public class EditorDocsPanel extends Widget {
if (function == null) { if (function == null) {
Topic topic = topics.get(rows.get(selectedRow).topic()); Topic topic = topics.get(rows.get(selectedRow).topic());
y = drawSection(graphics, topic.title(), x, y); y = drawSection(graphics, topic.title(), x, y);
y = drawWrapped(graphics, topic.blurb(), x, maxWidth, y, COLOR_TEXT); y = drawWrapped(graphics, topic.blurb(), x, maxWidth, y, editorManager.theme().syntaxDefault());
y += lineHeight(); y += lineHeight();
y = drawSection(graphics, "Functions", x, y); y = drawSection(graphics, "Functions", x, y);
for (FunctionDoc f : topic.functions()) { for (FunctionDoc f : topic.functions()) {
y = drawLine(graphics, f.signature(), x, maxWidth, y, COLOR_SIGNATURE); y = drawLine(graphics, f.signature(), x, maxWidth, y, editorManager.theme().syntaxMethod());
y += lineHeight() / 2; y += lineHeight() / 2;
} }
} else { } else {
y = drawLine(graphics, function.signature(), x, maxWidth, y, COLOR_SIGNATURE); y = drawLine(graphics, function.signature(), x, maxWidth, y, editorManager.theme().syntaxMethod());
y += lineHeight(); y += lineHeight();
y = drawSection(graphics, "Description", x, y); y = drawSection(graphics, "Description", x, y);
y = drawWrapped(graphics, function.summary(), x, maxWidth, y, COLOR_TEXT); y = drawWrapped(graphics, function.summary(), x, maxWidth, y, editorManager.theme().syntaxDefault());
y += lineHeight() / 2; y += lineHeight() / 2;
if (!function.params().isEmpty()) { if (!function.params().isEmpty()) {
@@ -326,11 +322,11 @@ public class EditorDocsPanel extends Widget {
for (var param : function.params()) { for (var param : function.params()) {
String suffix = param.optional() ? " (optional)" : ""; String suffix = param.optional() ? " (optional)" : "";
drawRun(graphics, x, y, drawRun(graphics, x, y,
param.name(), COLOR_PARAM_NAME, param.name(), editorManager.theme().syntaxParam(),
" · " + param.type() + suffix, COLOR_DIM); " · " + param.type() + suffix, editorManager.theme().mutedText());
y += lineHeight(); y += lineHeight();
y = drawWrapped(graphics, param.description(), x + FUNC_INDENT, y = drawWrapped(graphics, param.description(), x + FUNC_INDENT,
maxWidth - FUNC_INDENT, y, COLOR_TEXT); maxWidth - FUNC_INDENT, y, editorManager.theme().syntaxDefault());
y += lineHeight() / 2; y += lineHeight() / 2;
} }
y += lineHeight() / 2; y += lineHeight() / 2;
@@ -338,7 +334,7 @@ public class EditorDocsPanel extends Widget {
if (function.returns() != null && !function.returns().isEmpty()) { if (function.returns() != null && !function.returns().isEmpty()) {
y = drawSection(graphics, "Returns", x, y); y = drawSection(graphics, "Returns", x, y);
y = drawWrapped(graphics, function.returns(), x, maxWidth, y, COLOR_TEXT); y = drawWrapped(graphics, function.returns(), x, maxWidth, y, editorManager.theme().syntaxDefault());
y += lineHeight() / 2; y += lineHeight() / 2;
} }
@@ -346,11 +342,11 @@ public class EditorDocsPanel extends Widget {
y = drawSection(graphics, "Notes", x, y); y = drawSection(graphics, "Notes", x, y);
for (String note : function.notes()) { for (String note : function.notes()) {
String bullet = "• "; String bullet = "• ";
drawRun(graphics, x, y, bullet, COLOR_DIM, null, COLOR_TEXT); drawRun(graphics, x, y, bullet, editorManager.theme().mutedText(), null, editorManager.theme().syntaxDefault());
int bulletW = font.width(bullet); int bulletW = font.width(bullet);
List<String> lines = wrap(note, maxWidth - bulletW); List<String> lines = wrap(note, maxWidth - bulletW);
for (String line : lines) { for (String line : lines) {
graphics.text(font, line, x + bulletW, y, COLOR_TEXT, false); graphics.text(font, line, x + bulletW, y, editorManager.theme().syntaxDefault(), false);
y += lineHeight(); y += lineHeight();
} }
// The last line already advanced a full line; add an extra gap so // The last line already advanced a full line; add an extra gap so
@@ -361,11 +357,12 @@ public class EditorDocsPanel extends Widget {
y -= lineHeight() / 2; // drop the gap left after the final bullet y -= lineHeight() / 2; // drop the gap left after the final bullet
} }
for (ExampleDoc example : function.examples()) { for (int i = 0; i < function.examples().size(); i++) {
ExampleDoc example = function.examples().get(i);
y = drawSection(graphics, y = drawSection(graphics,
example.title().isEmpty() ? "Example" : "Example — " + example.title(), example.title().isEmpty() ? "Example" : "Example — " + example.title(),
x, y); x, y);
y = drawCodeBlock(graphics, example.code(), x, maxWidth, y); y = drawCodeBlock(graphics, example.code(), i, x, maxWidth, y);
y += lineHeight() / 2; y += lineHeight() / 2;
} }
} }
@@ -376,7 +373,7 @@ public class EditorDocsPanel extends Widget {
/** Section header; returns the y below it. */ /** Section header; returns the y below it. */
private int drawSection(@NonNull GuiGraphicsExtractor graphics, String title, int x, int y) { private int drawSection(@NonNull GuiGraphicsExtractor graphics, String title, int x, int y) {
graphics.text(font, title, x, y, COLOR_SECTION, true); graphics.text(font, title, x, y, editorManager.theme().syntaxKeyword(), true);
return y + lineHeight() + lineHeight() / 2; return y + lineHeight() + lineHeight() / 2;
} }
@@ -413,32 +410,96 @@ public class EditorDocsPanel extends Widget {
} }
/** Fenced, syntax-highlighted Lua snippet on a dark background. */ /** Fenced, syntax-highlighted Lua snippet on a dark background. */
private int drawCodeBlock(@NonNull GuiGraphicsExtractor graphics, String code, private int drawCodeBlock(@NonNull GuiGraphicsExtractor graphics, String code, int index,
int x, int maxWidth, int y) { int x, int maxWidth, int y) {
String[] lines = code.split("\n", -1); String[] lines = code.split("\n", -1);
int blockTop = y; int blockTop = y;
int blockH = lines.length * lineHeight() + PAD * 2; int blockH = lines.length * lineHeight() + PAD * 2;
int blockWidth = Math.min(maxWidth, panelX2() - PAD - x);
int textX = x + PAD;
int textY = blockTop + PAD;
graphics.fill(x, blockTop, Math.min(x + maxWidth, panelX2() - PAD), blockTop + blockH, COLOR_CODE_BG); codeBlocks.add(new CodeBlockLayout(index, code, textX, textY,
Math.max(0, blockWidth - PAD * 2), blockH - PAD * 2));
graphics.fill(x, blockTop, x + blockWidth, blockTop + blockH,
editorManager.theme().raisedBackground());
boolean inMultiline = false; boolean inMultiline = false;
int textY = blockTop + PAD; int lineOffset = 0;
for (String line : lines) { for (String line : lines) {
int textX = x + PAD; drawCodeSelection(graphics, code, lineOffset, line, textX, textY, index);
LuaHighlighter.LineTokens tokens = highlighter.tokenizeLine(line, inMultiline); LuaHighlighter.LineTokens tokens = highlighter.tokenizeLine(line, inMultiline, editorManager.theme());
int lineTextX = textX;
for (Span span : tokens.spans()) { for (Span span : tokens.spans()) {
graphics.text(font, span.text(), textX, textY, span.color(), true); graphics.text(font, span.text(), lineTextX, textY, span.color(), true);
textX += font.width(span.text()); lineTextX += font.width(span.text());
} }
if (tokens.spans().isEmpty()) { if (tokens.spans().isEmpty()) {
graphics.text(font, line, textX, textY, COLOR_TEXT, true); graphics.text(font, line, lineTextX, textY, editorManager.theme().syntaxDefault(), true);
} }
inMultiline = tokens.continuesMultilineString(); inMultiline = tokens.continuesMultilineString();
textY += lineHeight(); textY += lineHeight();
lineOffset += line.length() + 1;
} }
return blockTop + blockH + lineHeight() / 2; return blockTop + blockH + lineHeight() / 2;
} }
private void drawCodeSelection(@NonNull GuiGraphicsExtractor graphics, String code, int lineOffset,
String line, int x, int y, int exampleIndex) {
if (activeExample != exampleIndex || selectionAnchor < 0 || selectionCursor < 0) return;
int lo = Math.min(selectionAnchor, selectionCursor);
int hi = Math.max(selectionAnchor, selectionCursor);
int lineEnd = lineOffset + line.length();
int start = Math.max(lo, lineOffset);
int end = Math.min(hi, lineEnd);
if (start < end) {
int x1 = x + font.width(line.substring(0, start - lineOffset));
int x2 = x + font.width(line.substring(0, end - lineOffset));
graphics.fill(x1, y, Math.max(x1 + 1, x2), y + lineHeight(), editorManager.theme().selection());
} else if (hi > lineEnd && lineEnd < code.length() && lo <= lineEnd) {
// A selected newline has no glyph, so mark its position just after the line.
int newlineX = x + font.width(line);
graphics.fill(newlineX, y, newlineX + Math.max(2, font.width(" ")), y + lineHeight(),
editorManager.theme().selection());
}
}
private CodeBlockLayout codeBlockAt(double x, double y) {
if (x < listX2() || x >= panelX2() - 1 || y < listTop() || y >= panelY2() - 1) return null;
for (CodeBlockLayout block : codeBlocks) {
if (x >= block.x() && x <= block.x() + block.width()
&& y >= block.y() && y < block.y() + block.height()) return block;
}
return null;
}
private CodeBlockLayout activeCodeBlock() {
for (CodeBlockLayout block : codeBlocks) {
if (block.index() == activeExample) return block;
}
return null;
}
private int codeOffsetAt(CodeBlockLayout block, double mouseX, double mouseY) {
String[] lines = block.code().split("\n", -1);
int line = Math.max(0, Math.min((int) Math.floor((mouseY - block.y()) / lineHeight()), lines.length - 1));
String text = lines[line];
double relativeX = Math.max(0, mouseX - block.x());
int column = 0;
for (int i = 0; i < text.length(); i++) {
int before = font.width(text.substring(0, i));
int charWidth = font.width(text.substring(i, i + 1));
if (relativeX < before + charWidth / 2.0) break;
column = i + 1;
}
int offset = column;
for (int i = 0; i < line; i++) offset += lines[i].length() + 1;
return Math.min(offset, block.code().length());
}
// ── Input handling ──────────────────────────────────────────────────── // ── Input handling ────────────────────────────────────────────────────
@Override @Override
@@ -461,6 +522,10 @@ public class EditorDocsPanel extends Widget {
// Left list: select the clicked row. // Left list: select the clicked row.
if (mx < listX2() && my >= listTop()) { if (mx < listX2() && my >= listTop()) {
selectingCode = false;
activeExample = -1;
selectionAnchor = -1;
selectionCursor = -1;
int index = (my - listTop() + listScroll) / rowHeight(); int index = (my - listTop() + listScroll) / rowHeight();
if (index >= 0 && index < rows.size()) { if (index >= 0 && index < rows.size()) {
selectRow(index); selectRow(index);
@@ -468,6 +533,20 @@ public class EditorDocsPanel extends Widget {
return true; return true;
} }
CodeBlockLayout block = codeBlockAt(mx, my);
if (block != null) {
activeExample = block.index();
selectionAnchor = codeOffsetAt(block, mx, my);
selectionCursor = selectionAnchor;
selectingCode = true;
return true;
}
activeExample = -1;
selectionAnchor = -1;
selectionCursor = -1;
selectingCode = false;
// Anything else inside the panel is consumed (scrolling happens per-column). // Anything else inside the panel is consumed (scrolling happens per-column).
return true; return true;
} }
@@ -475,6 +554,24 @@ public class EditorDocsPanel extends Widget {
@Override @Override
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
if (!visible) return false; if (!visible) return false;
if (activeExample >= 0 && event.hasControlDown()) {
CodeBlockLayout block = activeCodeBlock();
if (block != null) {
if (event.key() == 65) { // Ctrl+A selects this example
selectionAnchor = 0;
selectionCursor = block.code().length();
return true;
}
if (event.key() == 67 && selectionAnchor >= 0 && selectionCursor >= 0) { // Ctrl+C
int lo = Math.min(selectionAnchor, selectionCursor);
int hi = Math.max(selectionAnchor, selectionCursor);
if (lo != hi) {
Minecraft.getInstance().keyboardHandler.setClipboard(block.code().substring(lo, hi));
}
return true;
}
}
}
switch (event.key()) { switch (event.key()) {
case 256 -> { // Escape — close the docs, not the editor case 256 -> { // Escape — close the docs, not the editor
close(); close();
@@ -501,11 +598,17 @@ public class EditorDocsPanel extends Widget {
@Override @Override
public boolean handleMouseDragged(MouseButtonEvent event) { public boolean handleMouseDragged(MouseButtonEvent event) {
if (selectingCode) {
CodeBlockLayout block = activeCodeBlock();
if (block != null) selectionCursor = codeOffsetAt(block, event.x(), event.y());
return true;
}
return visible; return visible;
} }
@Override @Override
public boolean handleMouseReleased(MouseButtonEvent event) { public boolean handleMouseReleased(MouseButtonEvent event) {
selectingCode = false;
return visible; return visible;
} }

View File

@@ -26,20 +26,6 @@ import java.util.TreeSet;
*/ */
public class EditorFileTree extends Widget { public class EditorFileTree extends Widget {
private static final int COLOR_TEXT = 0xFFFFFFFF;
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 MAX_NAME_LENGTH = 64;
private static final int PADDING_X = 3; private static final int PADDING_X = 3;
@@ -195,7 +181,7 @@ public class EditorFileTree extends Widget {
// ── 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) {
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().sidebarBackground());
Font font = editorScreen.getFont(); Font font = editorScreen.getFont();
int lineH = font.lineHeight; int lineH = font.lineHeight;
@@ -225,9 +211,9 @@ public class EditorFileTree extends Widget {
// copy of the file the view is editing. // copy of the file the view is editing.
boolean isOpenFile = row.file != null && openFile != null && row.file.getName().equals(openFile.getName()); 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); if (isOpenFile) graphics.fill(getStartX(), y, getEndX(), y + lineH, editorManager.theme().activeBackground());
else if (row.isFolder() && editorManager.getSelectedFolder().equals(row.path())) else if (row.isFolder() && editorManager.getSelectedFolder().equals(row.path()))
graphics.fill(getStartX(), y, getEndX(), y + lineH, COLOR_ROW_FOLDER); graphics.fill(getStartX(), y, getEndX(), y + lineH, editorManager.theme().raisedBackground());
// A coloured stripe beside a file means somebody else has it open. // 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. // Up to three of them fit; more than that just keeps the first.
@@ -256,21 +242,24 @@ public class EditorFileTree extends Widget {
if (row.isFolder()) { if (row.isFolder()) {
boolean folded = editorManager.isFolderFolded(row.path()); boolean folded = editorManager.isFolderFolded(row.path());
drawIcon(graphics, folded ? ICON_COLLAPSED : ICON_EXPANDED, x, y, lineH, COLOR_CHEVRON, COLOR_CHEVRON); drawIcon(graphics, folded ? ICON_COLLAPSED : ICON_EXPANDED, x, y, lineH,
editorManager.theme().mutedText(), editorManager.theme().mutedText());
x += CHEVRON_WIDTH + CHEVRON_GAP; x += CHEVRON_WIDTH + CHEVRON_GAP;
drawIcon(graphics, ICON_FOLDER, x, y, lineH, drawIcon(graphics, ICON_FOLDER, x, y, lineH,
folded ? COLOR_FOLDER : COLOR_FOLDER_OPEN, COLOR_FOLDER_SEAM); folded ? editorManager.theme().folder() : editorManager.theme().folderBright(),
editorManager.theme().folderSeam());
} else { } else {
for (int c = 0; c < Math.min(3, editors.size()); c++) { 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()); graphics.fill(x + c, y + 2, x + c + 1, y + lineH - 2, editors.get(c).color());
} }
x += PRESENCE_GUTTER; x += PRESENCE_GUTTER;
drawIcon(graphics, ICON_FILE, x, y, lineH, COLOR_FILE, COLOR_FILE_LINES); drawIcon(graphics, ICON_FILE, x, y, lineH,
editorManager.theme().fileIcon(), editorManager.theme().fileDetail());
} }
graphics.text(font, row.label(), textX, y, COLOR_TEXT, true); graphics.text(font, row.label(), textX, y, editorManager.theme().text(), false);
} }
/** Centres a glyph in the row and paints it pixel by pixel. */ /** Centres a glyph in the row and paints it pixel by pixel. */
@@ -296,7 +285,7 @@ public class EditorFileTree extends Widget {
* folder, so the text is passed in rather than read from one fixed field. * 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) { 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); graphics.fill(getStartX(), y, getEndX(), y + lineH, editorManager.theme().activeBackground());
// As the name grows, keep its end inside the panel like a real field does. // As the name grows, keep its end inside the panel like a real field does.
String shown = text + "|"; String shown = text + "|";
@@ -304,7 +293,7 @@ public class EditorFileTree extends Widget {
int from = 0; int from = 0;
while (from < shown.length() - 1 && font.width(shown.substring(from)) > maxWidth) from++; while (from < shown.length() - 1 && font.width(shown.substring(from)) > maxWidth) from++;
graphics.text(font, shown.substring(from), textX, y, COLOR_TEXT, false); graphics.text(font, shown.substring(from), textX, y, editorManager.theme().text(), false);
} }
// ── Input ───────────────────────────────────────────────────────────── // ── Input ─────────────────────────────────────────────────────────────

View File

@@ -33,7 +33,12 @@ public class EditorFileView extends EditorPane {
@Override @Override
public String paneTitle() { public String paneTitle() {
EditorFile file = getCurrentEditorFile(); EditorFile file = getCurrentEditorFile();
return file == null ? "(no file)" : file.getName(); return file == null ? "" : file.getName();
}
@Override
public boolean showHeader() {
return currentEditorFile != null;
} }
// ── Scroll state ────────────────────────────────────────────────────── // ── Scroll state ──────────────────────────────────────────────────────
@@ -49,15 +54,6 @@ public class EditorFileView extends EditorPane {
private int textAreaWidth() { return getEndX() - textAreaX(); } private int textAreaWidth() { return getEndX() - textAreaX(); }
private int textAreaHeight() { return getEndY() - getStartY(); } private int textAreaHeight() { return getEndY() - getStartY(); }
// ── Colors ────────────────────────────────────────────────────────────
private static final int COLOR_TEXT = 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_GUTTER_BG = 0xFF252525;
private static final int COLOR_GUTTER_TEXT = 0xFF888888;
private static final int COLOR_GUTTER_DIV = 0xFF444444;
// ── Autocomplete state ──────────────────────────────────────────────── // ── Autocomplete state ────────────────────────────────────────────────
private final CompletionProvider completionProvider = new CompletionProvider(); private final CompletionProvider completionProvider = new CompletionProvider();
@@ -81,19 +77,6 @@ public class EditorFileView extends EditorPane {
/** Maximum number of suggestions shown at once. */ /** Maximum number of suggestions shown at once. */
private static final int MAX_COMPLETIONS = 8; private static final int MAX_COMPLETIONS = 8;
// Popup colours — dark, VSCode-ish
private static final int COLOR_POPUP_BG = 0xFF1E1E1E;
private static final int COLOR_POPUP_BORDER = 0xFF666666;
private static final int COLOR_POPUP_SELECTED = 0xFF383868;
private static final int COLOR_POPUP_TEXT = 0xFFD4D4D4;
private static final int COLOR_POPUP_DETAIL = 0xFF888888;
private static final int COLOR_KIND_KEYWORD = 0xFF569CD6;
private static final int COLOR_KIND_TYPE = 0xFF4EC9B0;
private static final int COLOR_KIND_METHOD = 0xFFDCDCAA;
private static final int COLOR_KIND_FIELD = 0xFF9CDCFE;
private static final int COLOR_KIND_SNIPPET = 0xFFCE9178;
private static final int POPUP_ITEM_HEIGHT = 12; private static final int POPUP_ITEM_HEIGHT = 12;
private static final int POPUP_PADDING = 4; private static final int POPUP_PADDING = 4;
private static final int POPUP_WIDTH = 240; private static final int POPUP_WIDTH = 240;
@@ -357,11 +340,11 @@ public class EditorFileView extends EditorPane {
private int kindColor(CompletionItem.Kind kind) { private int kindColor(CompletionItem.Kind kind) {
return switch (kind) { return switch (kind) {
case KEYWORD -> COLOR_KIND_KEYWORD; case KEYWORD -> editorManager.theme().syntaxKeyword();
case TYPE -> COLOR_KIND_TYPE; case TYPE -> editorManager.theme().syntaxBuiltin();
case METHOD -> COLOR_KIND_METHOD; case METHOD -> editorManager.theme().syntaxMethod();
case FIELD -> COLOR_KIND_FIELD; case FIELD -> editorManager.theme().syntaxParam();
case SNIPPET -> COLOR_KIND_SNIPPET; case SNIPPET -> editorManager.theme().syntaxString();
}; };
} }
@@ -390,7 +373,7 @@ public class EditorFileView extends EditorPane {
boolean inBlock = false; boolean inBlock = false;
for (int i = 0; i < lines.length; i++) { for (int i = 0; i < lines.length; i++) {
multilineState[i] = inBlock; multilineState[i] = inBlock;
LuaHighlighter.LineTokens result = luaHighlighter.tokenizeLine(lines[i], inBlock); LuaHighlighter.LineTokens result = luaHighlighter.tokenizeLine(lines[i], inBlock, editorManager.theme());
inBlock = result.continuesMultilineString(); inBlock = result.continuesMultilineString();
} }
} }
@@ -403,11 +386,11 @@ public class EditorFileView extends EditorPane {
*/ */
private void drawHighlightedLine(GuiGraphicsExtractor graphics, String rawLine, private void drawHighlightedLine(GuiGraphicsExtractor graphics, String rawLine,
int drawX, int drawY, boolean inMultiline) { int drawX, int drawY, boolean inMultiline) {
LuaHighlighter.LineTokens tokens = luaHighlighter.tokenizeLine(rawLine, inMultiline); LuaHighlighter.LineTokens tokens = luaHighlighter.tokenizeLine(rawLine, inMultiline, editorManager.theme());
int x = drawX; int x = drawX;
for (LuaHighlighter.Span span : tokens.spans()) { for (LuaHighlighter.Span span : tokens.spans()) {
String display = sanitize(span.text()); String display = sanitize(span.text());
graphics.text(font, display, x, drawY, span.color(), true); graphics.text(font, display, x, drawY, span.color(), false);
x += font.width(display); x += font.width(display);
} }
} }
@@ -428,11 +411,20 @@ public class EditorFileView extends EditorPane {
graphics.enableScissor(start_x, start_y, end_x, end_y); graphics.enableScissor(start_x, start_y, end_x, end_y);
// Background // Background
graphics.fill(start_x, start_y, end_x, end_y, 0xFF303030); graphics.fill(start_x, start_y, end_x, end_y, editorManager.theme().background());
if (currentEditorFile == null) {
String emptyMessage = "Select a file to start editing";
int messageX = start_x + (end_x - start_x - font.width(emptyMessage)) / 2;
int messageY = start_y + (end_y - start_y - font.lineHeight) / 2;
graphics.text(font, emptyMessage, messageX, messageY, editorManager.theme().mutedText(), false);
graphics.disableScissor();
return;
}
// Gutter background + divider // Gutter background + divider
graphics.fill(start_x, start_y, gutterDivX() - 1, end_y, COLOR_GUTTER_BG); graphics.fill(start_x, start_y, gutterDivX() - 1, end_y, editorManager.theme().sidebarBackground());
graphics.fill(gutterDivX() - 1, start_y, gutterDivX(), end_y, COLOR_GUTTER_DIV); graphics.fill(gutterDivX() - 1, start_y, gutterDivX(), end_y, editorManager.theme().border());
// Rebuild per-line multiline-string state whenever text changes // Rebuild per-line multiline-string state whenever text changes
int currentVersion = text.length() ^ text.toString().hashCode(); int currentVersion = text.length() ^ text.toString().hashCode();
@@ -447,7 +439,8 @@ public class EditorFileView extends EditorPane {
// Selection highlight: ours, then everybody else's in their own colour // Selection highlight: ours, then everybody else's in their own colour
if (hasSelection()) { if (hasSelection()) {
drawSelection(graphics, lines, lineH, firstLine, lastLine, end_x, drawSelection(graphics, lines, lineH, firstLine, lastLine, end_x,
Math.min(selectionAnchor, cursorPos), Math.max(selectionAnchor, cursorPos), COLOR_SELECTION); Math.min(selectionAnchor, cursorPos), Math.max(selectionAnchor, cursorPos),
transparent(editorManager.theme().selection(), 0x66));
} }
for (EditorPresence editor : remoteEditors) { for (EditorPresence editor : remoteEditors) {
if (!editor.hasSelection()) continue; if (!editor.hasSelection()) continue;
@@ -464,7 +457,7 @@ public class EditorFileView extends EditorPane {
int numW = font.width(lineNum); int numW = font.width(lineNum);
graphics.text(font, lineNum, graphics.text(font, lineNum,
gutterDivX() - 4 - numW, gutterDivX() - 4 - numW,
screenY, COLOR_GUTTER_TEXT, false); screenY, editorManager.theme().mutedText(), false);
boolean lineInMultiline = (i < multilineState.length) && multilineState[i]; boolean lineInMultiline = (i < multilineState.length) && multilineState[i];
drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline); drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline);
@@ -491,7 +484,7 @@ public class EditorFileView extends EditorPane {
if (cursorX >= textAreaX() && cursorX <= end_x) { if (cursorX >= textAreaX() && cursorX <= end_x) {
graphics.fill(cursorX, cursorY, cursorX + 1, cursorY + lineH, graphics.fill(cursorX, cursorY, cursorX + 1, cursorY + lineH,
focusedPane ? COLOR_CURSOR : COLOR_CURSOR_DIM); focusedPane ? editorManager.theme().cursor() : editorManager.theme().dimCursor());
} }
} }
@@ -552,9 +545,10 @@ public class EditorFileView extends EditorPane {
int tagY = y - font.lineHeight - 2; int tagY = y - font.lineHeight - 2;
if (tagY < start_y) tagY = Math.min(y + lineH + 1, end_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 + nameW + 5, tagY + font.lineHeight + 2,
transparent(editorManager.theme().raisedBackground(), 0xC0));
graphics.fill(tagX, tagY, tagX + 2, tagY + font.lineHeight + 2, editor.color()); graphics.fill(tagX, tagY, tagX + 2, tagY + font.lineHeight + 2, editor.color());
graphics.text(font, name, tagX + 4, tagY + 1, 0xFFFFFFFF, false); graphics.text(font, name, tagX + 4, tagY + 1, editorManager.theme().text(), false);
} }
/** Same colour, with a given alpha instead of opaque. */ /** Same colour, with a given alpha instead of opaque. */
@@ -570,18 +564,19 @@ public class EditorFileView extends EditorPane {
int popupH = completions.size() * POPUP_ITEM_HEIGHT + POPUP_PADDING * 2; int popupH = completions.size() * POPUP_ITEM_HEIGHT + POPUP_PADDING * 2;
// Shadow (subtle depth) // Shadow (subtle depth)
graphics.fill(px + 2, py + 2, px + POPUP_WIDTH + 2, py + popupH + 2, 0x55000000); graphics.fill(px + 2, py + 2, px + POPUP_WIDTH + 2, py + popupH + 2,
transparent(editorManager.theme().background(), 0x55));
// Background + border // Background + border
graphics.fill(px, py, px + POPUP_WIDTH, py + popupH, COLOR_POPUP_BG); graphics.fill(px, py, px + POPUP_WIDTH, py + popupH, editorManager.theme().raisedBackground());
// Top border // Top border
graphics.fill(px, py, px + POPUP_WIDTH, py + 1, COLOR_POPUP_BORDER); graphics.fill(px, py, px + POPUP_WIDTH, py + 1, editorManager.theme().border());
// Bottom border // Bottom border
graphics.fill(px, py + popupH - 1, px + POPUP_WIDTH, py + popupH, COLOR_POPUP_BORDER); graphics.fill(px, py + popupH - 1, px + POPUP_WIDTH, py + popupH, editorManager.theme().border());
// Left border // Left border
graphics.fill(px, py, px + 1, py + popupH, COLOR_POPUP_BORDER); graphics.fill(px, py, px + 1, py + popupH, editorManager.theme().border());
// Right border // Right border
graphics.fill(px + POPUP_WIDTH - 1, py, px + POPUP_WIDTH, py + popupH, COLOR_POPUP_BORDER); graphics.fill(px + POPUP_WIDTH - 1, py, px + POPUP_WIDTH, py + popupH, editorManager.theme().border());
String currentPrefix = completionProvider.extractPrefix(text.toString(), cursorPos); String currentPrefix = completionProvider.extractPrefix(text.toString(), cursorPos);
@@ -595,10 +590,10 @@ public class EditorFileView extends EditorPane {
// Row background // Row background
if (selected) { if (selected) {
graphics.fill(px + 1, itemY, px + POPUP_WIDTH - 1, itemY + POPUP_ITEM_HEIGHT, graphics.fill(px + 1, itemY, px + POPUP_WIDTH - 1, itemY + POPUP_ITEM_HEIGHT,
COLOR_POPUP_SELECTED); editorManager.theme().selection());
} else if (hovered) { } else if (hovered) {
graphics.fill(px + 1, itemY, px + POPUP_WIDTH - 1, itemY + POPUP_ITEM_HEIGHT, graphics.fill(px + 1, itemY, px + POPUP_WIDTH - 1, itemY + POPUP_ITEM_HEIGHT,
0xFF2A2A3A); editorManager.theme().selectionHover());
} }
// Kind colour strip (left edge) // Kind colour strip (left edge)
@@ -622,11 +617,11 @@ public class EditorFileView extends EditorPane {
String matchedPart = label.substring(0, currentPrefix.length()); String matchedPart = label.substring(0, currentPrefix.length());
String remainingPart = label.substring(currentPrefix.length()); String remainingPart = label.substring(currentPrefix.length());
graphics.text(font, matchedPart, labelX, labelY, 0xFFFFFFFF, false); graphics.text(font, matchedPart, labelX, labelY, editorManager.theme().text(), false);
int afterMatchX = labelX + font.width(matchedPart); int afterMatchX = labelX + font.width(matchedPart);
graphics.text(font, remainingPart, afterMatchX, labelY, COLOR_POPUP_TEXT, false); graphics.text(font, remainingPart, afterMatchX, labelY, editorManager.theme().text(), false);
} else { } else {
graphics.text(font, label, labelX, labelY, COLOR_POPUP_TEXT, false); graphics.text(font, label, labelX, labelY, editorManager.theme().text(), false);
} }
// Detail annotation — right-aligned, dimmed // Detail annotation — right-aligned, dimmed
@@ -635,7 +630,7 @@ public class EditorFileView extends EditorPane {
int detailX = px + POPUP_WIDTH - detailW - POPUP_PADDING; int detailX = px + POPUP_WIDTH - detailW - POPUP_PADDING;
// Only draw if it fits without overlapping the label // Only draw if it fits without overlapping the label
if (detailX > labelX + font.width(label) + 4) { if (detailX > labelX + font.width(label) + 4) {
graphics.text(font, detail, detailX, labelY, COLOR_POPUP_DETAIL, false); graphics.text(font, detail, detailX, labelY, editorManager.theme().mutedText(), false);
} }
} }
@@ -643,7 +638,7 @@ public class EditorFileView extends EditorPane {
if (completions.size() > 1) { if (completions.size() > 1) {
int hintY = py + popupH + 2; int hintY = py + popupH + 2;
String hint = "↑↓ navigate Tab/Enter accept Esc dismiss"; String hint = "↑↓ navigate Tab/Enter accept Esc dismiss";
graphics.text(font, hint, px, hintY, 0xFF555577, false); graphics.text(font, hint, px, hintY, editorManager.theme().hint(), false);
} }
} }
@@ -1038,4 +1033,4 @@ public class EditorFileView extends EditorPane {
public EditorFile getCurrentEditorFile() { public EditorFile getCurrentEditorFile() {
return currentEditorFile; return currentEditorFile;
} }
} }

View File

@@ -0,0 +1,260 @@
package com.aranroig.client.editor;
import com.mojang.blaze3d.font.GlyphInfo;
import com.mojang.blaze3d.pipeline.RenderPipeline;
import com.mojang.blaze3d.textures.GpuTextureView;
import com.mojang.blaze3d.vertex.VertexConsumer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GlyphSource;
import net.minecraft.client.gui.font.FontSet;
import net.minecraft.client.gui.font.TextRenderable;
import net.minecraft.client.gui.font.glyphs.BakedGlyph;
import net.minecraft.client.gui.font.glyphs.EffectGlyph;
import net.minecraft.client.renderer.rendertype.RenderType;
import net.minecraft.network.chat.FontDescription;
import net.minecraft.network.chat.Style;
import net.minecraft.resources.Identifier;
import net.minecraft.util.RandomSource;
import org.joml.Matrix4fc;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* The editor's monospace font: vanilla's default font with its characters
* adapted to a fixed pitch, instead of a bundled font file.
*
* The default font is pixel-perfect but not monospaced: most letters advance
* 6px while i, l or a comma advance 2-4. This class wraps vanilla's glyph
* source so every glyph reports {@link #CELL_WIDTH} as its advance and is
* drawn centered in that cell. Measuring and drawing both walk the glyph
* source, so everything a Font derives — widths, cursor column math, word
* wrapping, the terminal grid — becomes monospaced too.
*
* Characters that vanilla draws poorly in code (i and l are bare 1px stems)
* can be replaced by hand: {@link #CUSTOM_GLYPHS} maps a character to rows
* of '#' and '.', painted pixel by pixel instead of vanilla's bitmap, in the
* color the text is drawn with.
*
* The FontSet is looked up through the FontManager on every use, so resource
* reloads (F3+T) and packs that replace the default font are picked up
* without any reload listener of our own.
*
* EditorScreen.getFont() hands it to every editor widget, so only the editor
* draws monospace; the rest of the game keeps the plain default font.
*/
public final class EditorFonts {
/** Vanilla's own font definition; the editor reuses its glyphs. */
public static final Identifier VANILLA_DEFAULT = Identifier.withDefaultNamespace("default");
/** Vanilla's usual advance: the pitch every character gets instead. */
public static final float CELL_WIDTH = 6.0f;
/** Same z-offset vanilla gives to underline and strikethrough bars. */
private static final float EFFECT_DEPTH = 0.01f;
/**
* Hand-drawn glyphs, in cell coordinates: each entry is one scanline,
* '#' paints a pixel (in the text color, shadow included), anything else
* is left empty. Columns count from the left edge of the 6px cell, rows
* from the top of the line, so capitals span rows 0 to 6 and a character
* with a descender may use rows 7-8. The matrix replaces vanilla's
* bitmap entirely: vanilla pixels outside the '#'s are not drawn.
*/
private static final Map<Character, String[]> CUSTOM_GLYPHS = Map.of(
'i', new String[] {
".#....",
"......",
"##....",
".#....",
".#....",
".#....",
"..##..",
},
'l', new String[] {
"###...",
"..#...",
"..#...",
"..#...",
"..#...",
"..#...",
"...##.",
});
private static Font editorFont;
private EditorFonts() {}
/** The editor's monospace font, drawn with vanilla's default glyphs. */
public static Font get() {
if (editorFont == null) {
editorFont = create();
}
return editorFont;
}
private static Font create() {
return new Font(new Font.Provider() {
@Override
public GlyphSource glyphs(FontDescription description) {
// Editor code is not chat: no fishy-text filtering.
FontSet fontSet = fontSet(description);
return new MonospaceSource(fontSet.source(false), fontSet.whiteGlyph());
}
@Override
public EffectGlyph effect() {
return fontSet(FontDescription.DEFAULT).whiteGlyph();
}
});
}
private static FontSet fontSet(FontDescription description) {
Identifier font = description instanceof FontDescription.Resource resource
? resource.id() : VANILLA_DEFAULT;
return Minecraft.getInstance().fontManager.getFontSetRaw(font);
}
/** Wraps every glyph the vanilla default font set serves onto a cell. */
private record MonospaceSource(GlyphSource delegate, EffectGlyph effect) implements GlyphSource {
@Override
public BakedGlyph getGlyph(int codepoint) {
return new MonospaceGlyph(delegate.getGlyph(codepoint), effect,
CUSTOM_GLYPHS.get((char) codepoint));
}
@Override
public BakedGlyph getRandomGlyph(RandomSource random, int width) {
return new MonospaceGlyph(delegate.getRandomGlyph(random, width), effect, null);
}
}
/**
* A glyph that always advances by {@link #CELL_WIDTH}, however wide it
* naturally is: the layout steps one full cell per character. Vanilla
* bitmaps slide to the middle of the cell, so narrow letters sit between
* their neighbours instead of hugging the left side; hand-drawn ones are
* painted at their matrix positions from the cell's left edge.
*/
private record MonospaceGlyph(BakedGlyph delegate, EffectGlyph effect, String[] pixels)
implements BakedGlyph {
@Override
public GlyphInfo info() {
GlyphInfo natural = delegate.info();
return new GlyphInfo() {
@Override
public float getAdvance() {
return CELL_WIDTH;
}
@Override
public float getBoldOffset() {
return natural.getBoldOffset();
}
@Override
public float getShadowOffset() {
return natural.getShadowOffset();
}
};
}
@Override
public TextRenderable.Styled createGlyph(float x, float y, int color, int shadowColor,
Style style, float boldDelta, float shadowDelta) {
if (pixels != null) {
return paintMatrix(x, y, color, shadowColor, style, shadowDelta);
}
float naturalAdvance = delegate.info().getAdvance();
float centered = x + (CELL_WIDTH - naturalAdvance) / 2.0f;
return delegate.createGlyph(centered, y, color, shadowColor, style, boldDelta, shadowDelta);
}
/** Paint the matrix: one rectangle per horizontal run of '#'. */
private TextRenderable.Styled paintMatrix(float cellX, float cellY, int color,
int shadowColor, Style style, float shadowDelta) {
List<TextRenderable> parts = new ArrayList<>();
for (int row = 0; row < pixels.length; row++) {
String line = pixels[row];
int col = 0;
while (col < line.length()) {
if (line.charAt(col) != '#') {
col++;
continue;
}
int end = col;
while (end < line.length() && line.charAt(end) == '#') end++;
parts.add(effect.createEffect(cellX + col, cellY + row,
cellX + end, cellY + row + 1.0f,
EFFECT_DEPTH, color, shadowColor, shadowDelta));
col = end;
}
}
return parts.isEmpty() ? null : new PixelArtGlyph(parts, style);
}
}
/** The pixels of one hand-drawn glyph, submitted as a single renderable. */
private record PixelArtGlyph(List<TextRenderable> parts, Style style) implements TextRenderable.Styled {
@Override
public void render(Matrix4fc pose, VertexConsumer buffer, int light, boolean applyMipmaps) {
for (TextRenderable part : parts) {
part.render(pose, buffer, light, applyMipmaps);
}
}
@Override
public RenderType renderType(Font.DisplayMode mode) {
return parts.get(0).renderType(mode);
}
@Override
public GpuTextureView textureView() {
return parts.get(0).textureView();
}
@Override
public RenderPipeline guiPipeline() {
return parts.get(0).guiPipeline();
}
@Override
public Style style() {
return style;
}
@Override
public float left() {
float value = Float.POSITIVE_INFINITY;
for (TextRenderable part : parts) value = Math.min(value, part.left());
return value;
}
@Override
public float top() {
float value = Float.POSITIVE_INFINITY;
for (TextRenderable part : parts) value = Math.min(value, part.top());
return value;
}
@Override
public float right() {
float value = Float.NEGATIVE_INFINITY;
for (TextRenderable part : parts) value = Math.max(value, part.right());
return value;
}
@Override
public float bottom() {
float value = Float.NEGATIVE_INFINITY;
for (TextRenderable part : parts) value = Math.max(value, part.bottom());
return value;
}
}
}

View File

@@ -20,6 +20,7 @@ import com.aranroig.payloads.ServerboundShellInputPayload;
import com.aranroig.payloads.ServerboundShellResizePayload; import com.aranroig.payloads.ServerboundShellResizePayload;
import com.aranroig.payloads.ServerboundSpawnShellPayload; 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.fabricmc.loader.api.FabricLoader;
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;
@@ -31,6 +32,10 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Properties;
public class EditorManager { public class EditorManager {
@@ -69,8 +74,11 @@ public class EditorManager {
/** Who is in which file, as the server last told us. */ /** Who is in which file, as the server last told us. */
private final Map<String, List<EditorPresence>> presenceByFile = new HashMap<>(); private final Map<String, List<EditorPresence>> presenceByFile = new HashMap<>();
private EditorTheme theme = EditorTheme.MIDNIGHT;
public EditorManager() { public EditorManager() {
client = Minecraft.getInstance(); client = Minecraft.getInstance();
loadTheme();
editorFileTree = new EditorFileTree(this); editorFileTree = new EditorFileTree(this);
editorTopBar = new EditorTopBar(this); editorTopBar = new EditorTopBar(this);
@@ -79,12 +87,54 @@ public class EditorManager {
editorTerminal = new EditorTerminalPane(this); editorTerminal = new EditorTerminalPane(this);
} }
public EditorTheme.Palette theme() {
return theme.palette();
}
public EditorTheme currentTheme() {
return theme;
}
public void setTheme(EditorTheme theme) {
if (this.theme == theme) return;
this.theme = theme;
Path path = themeConfigPath();
try {
Files.createDirectories(path.getParent());
Properties properties = new Properties();
properties.setProperty("theme", theme.name());
try (var writer = Files.newBufferedWriter(path)) {
properties.store(writer, "Codecraft editor preferences");
}
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not save Codecraft editor theme", e);
}
}
private void loadTheme() {
Path path = themeConfigPath();
if (!Files.isRegularFile(path)) return;
Properties properties = new Properties();
try (var reader = Files.newBufferedReader(path)) {
properties.load(reader);
theme = EditorTheme.fromName(properties.getProperty("theme", "MIDNIGHT"));
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not load Codecraft editor theme", e);
}
}
private static Path themeConfigPath() {
return FabricLoader.getInstance().getConfigDir().resolve("codecraft/client.properties");
}
public List<EditorFile> getFiles() { public List<EditorFile> getFiles() {
return files; return files;
} }
private final int FILE_RENDER_WIDTH_SIZE = 150; private final int FILE_RENDER_WIDTH_SIZE = 150;
private final int TOP_BAR_HEIGHT = 12; private final int TOP_BAR_HEIGHT = 12;
private boolean sidebarVisible = true;
public void toggleVisible() { public void toggleVisible() {
requestProjectFiles(); requestProjectFiles();
@@ -92,14 +142,14 @@ public class EditorManager {
TextEditorScreen textEditorScreen = new TextEditorScreen(this); 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, sidebarWidth(), -1);
editorFileTree.addToEditorScreen(textEditorScreen); editorFileTree.addToEditorScreen(textEditorScreen);
editorTopBar.setSize(0, 0, -1, TOP_BAR_HEIGHT); editorTopBar.setSize(0, 0, -1, TOP_BAR_HEIGHT);
editorTopBar.setZIndex(1); editorTopBar.setZIndex(1);
editorTopBar.addToEditorScreen(textEditorScreen); editorTopBar.addToEditorScreen(textEditorScreen);
paneContainer.setSize(FILE_RENDER_WIDTH_SIZE, TOP_BAR_HEIGHT, -1, -1); paneContainer.setSize(sidebarWidth(), TOP_BAR_HEIGHT, -1, -1);
paneContainer.addToEditorScreen(textEditorScreen); // attaches every pane too paneContainer.addToEditorScreen(textEditorScreen); // attaches every pane too
paneContainer.openInitialFile(); paneContainer.openInitialFile();
@@ -121,6 +171,20 @@ public class EditorManager {
client.setScreenAndShow(textEditorScreen); client.setScreenAndShow(textEditorScreen);
} }
private int sidebarWidth() {
return sidebarVisible ? FILE_RENDER_WIDTH_SIZE : 0;
}
/** Shows or hides the project sidebar and gives its width to the panes. */
public void toggleSidebar() {
sidebarVisible = !sidebarVisible;
if (currentScreen == null) return;
int width = sidebarWidth();
editorFileTree.setSize(0, TOP_BAR_HEIGHT, width, -1);
paneContainer.setSize(width, TOP_BAR_HEIGHT, -1, -1);
}
/** The editor screen currently on screen, if any. */ /** The editor screen currently on screen, if any. */
private TextEditorScreen currentScreen; private TextEditorScreen currentScreen;

View File

@@ -4,11 +4,10 @@ package com.aranroig.client.editor;
* Something that lives in the editor's pane area: a file being edited * Something that lives in the editor's pane area: a file being edited
* ({@link EditorFileView}) or the server shell ({@link EditorTerminalPane}). * ({@link EditorFileView}) or the server shell ({@link EditorTerminalPane}).
* *
* <p>{@link EditorPaneContainer} treats every pane the same way — a header * <p>{@link EditorPaneContainer} provides an optional header with the title
* with the title and a close button, draggable sashes around it — so anything * and pane controls, plus draggable sashes around each pane. Subclasses can
* that wants to be a pane only has to say what its header reads and, when it * choose whether to show a header, which title and controls it has, and what
* does not want the split buttons or has something to clean up on close, * cleanup to do when it closes.</p>
* override the small hooks here.</p>
*/ */
public abstract class EditorPane extends Widget { public abstract class EditorPane extends Widget {
@@ -19,6 +18,11 @@ public abstract class EditorPane extends Widget {
/** The text of the header above this pane. */ /** The text of the header above this pane. */
public abstract String paneTitle(); public abstract String paneTitle();
/** Whether this pane needs a header at all. */
public boolean showHeader() {
return true;
}
/** /**
* Whether the header offers the split-right / split-below buttons. File * 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 * panes can be split; the shell is one shell, so its header only holds the

View File

@@ -101,18 +101,6 @@ public class EditorPaneContainer extends Widget {
private static final int BTN_SPLIT_RIGHT = 2; private static final int BTN_SPLIT_RIGHT = 2;
private static final int BUTTON_COUNT = 3; 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. // 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_SIDE = {
"#######", "#######",
@@ -361,9 +349,14 @@ public class EditorPaneContainer extends Widget {
private void layoutNode(Node node, int x0, int y0, int x1, int y1) { private void layoutNode(Node node, int x0, int y0, int x1, int y1) {
if (node instanceof Leaf leaf) { if (node instanceof Leaf leaf) {
// The header belongs to this container; the pane gets what is left. // The header belongs to this container; panes without one use the
leaf.view.setSize(x0, y0 + HEADER_HEIGHT, x1, y1); // full area, including the space normally reserved for the header.
headerLayouts.add(new HeaderHit(leaf, x0, y0, x1, y0 + HEADER_HEIGHT)); if (leaf.view.showHeader()) {
leaf.view.setSize(x0, y0 + HEADER_HEIGHT, x1, y1);
headerLayouts.add(new HeaderHit(leaf, x0, y0, x1, y0 + HEADER_HEIGHT));
} else {
leaf.view.setSize(x0, y0, x1, y1);
}
return; return;
} }
@@ -473,14 +466,14 @@ public class EditorPaneContainer extends Widget {
// The panes paint their own areas; this is what the headers and the // The panes paint their own areas; this is what the headers and the
// sashes sit on, so nothing of the world shows between them. // sashes sit on, so nothing of the world shows between them.
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().background());
Font font = editorScreen.getFont(); Font font = editorScreen.getFont();
for (SashHit sash : sashLayouts) { for (SashHit sash : sashLayouts) {
boolean grabbing = dragBranch == sash.branch && dragIndex == sash.index; boolean grabbing = dragBranch == sash.branch && dragIndex == sash.index;
int colour = (grabbing || inRect(mouseX, mouseY, sash.x0(), sash.y0(), sash.x1(), sash.y1())) int colour = (grabbing || inRect(mouseX, mouseY, sash.x0(), sash.y0(), sash.x1(), sash.y1()))
? COLOR_SASH_HOVER : COLOR_SASH; ? editorManager.theme().accent() : editorManager.theme().border();
if (sash.horizontal()) { if (sash.horizontal()) {
int line = (sash.x0() + sash.x1()) / 2; int line = (sash.x0() + sash.x1()) / 2;
graphics.fill(line, sash.y0(), line + 1, sash.y1(), colour); graphics.fill(line, sash.y0(), line + 1, sash.y1(), colour);
@@ -499,21 +492,21 @@ public class EditorPaneContainer extends Widget {
int buttons = buttonCount(view); int buttons = buttonCount(view);
graphics.fill(header.x0(), header.y0(), header.x1(), header.y1(), graphics.fill(header.x0(), header.y0(), header.x1(), header.y1(),
active ? COLOR_HEADER_ACTIVE : COLOR_HEADER); active ? editorManager.theme().activeBackground() : editorManager.theme().raisedBackground());
if (active) if (active)
graphics.fill(header.x0(), header.y1() - 1, header.x1(), header.y1(), COLOR_ACTIVE_ACCENT); graphics.fill(header.x0(), header.y1() - 1, header.x1(), header.y1(), editorManager.theme().accent());
int labelWidth = header.x1() - header.x0() - 8 - BUTTON_SIZE * buttons; int labelWidth = header.x1() - header.x0() - 8 - BUTTON_SIZE * buttons;
String name = truncateToFit(font, view.paneTitle(), labelWidth); String name = truncateToFit(font, view.paneTitle(), labelWidth);
graphics.text(font, name, header.x0() + 4, header.y0() + 2, graphics.text(font, name, header.x0() + 4, header.y0() + 2,
active ? COLOR_HEADER_TEXT : COLOR_HEADER_DIM, false); active ? editorManager.theme().text() : editorManager.theme().mutedText(), false);
// Hovered button gets a background before any icon is drawn. // Hovered button gets a background before any icon is drawn.
for (int button = 0; button < buttons; button++) { for (int button = 0; button < buttons; button++) {
int[] rect = buttonRect(header, button); int[] rect = buttonRect(header, button);
if (inRect(mouseX, mouseY, rect[0], rect[1], rect[2], rect[3])) if (inRect(mouseX, mouseY, rect[0], rect[1], rect[2], rect[3]))
graphics.fill(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); button == BTN_CLOSE ? editorManager.theme().danger() : editorManager.theme().hoverBackground());
} }
for (int button = 0; button < buttons; button++) { for (int button = 0; button < buttons; button++) {
@@ -526,7 +519,7 @@ public class EditorPaneContainer extends Widget {
drawIcon(graphics, glyph, drawIcon(graphics, glyph,
rect[0] + (BUTTON_SIZE - glyph[0].length()) / 2, rect[0] + (BUTTON_SIZE - glyph[0].length()) / 2,
rect[1] + (BUTTON_SIZE - glyph.length) / 2, rect[1] + (BUTTON_SIZE - glyph.length) / 2,
COLOR_ICON); editorManager.theme().text());
} }
} }

View File

@@ -1,5 +1,6 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.screens.Screen; import net.minecraft.client.gui.screens.Screen;
import net.minecraft.client.input.CharacterEvent; import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent; import net.minecraft.client.input.KeyEvent;
@@ -17,6 +18,16 @@ public abstract class EditorScreen extends Screen {
super(title); super(title);
} }
/**
* Code wants a fixed pitch, and the game's default font is proportional:
* every widget takes its font from here, so the editor draws vanilla's
* default glyphs forced onto a monospaced grid (see EditorFonts).
*/
@Override
public Font getFont() {
return EditorFonts.get();
}
protected List<Widget> widgets = new ArrayList<>(); protected List<Widget> widgets = new ArrayList<>();
protected Widget selectedWidget; protected Widget selectedWidget;

View File

@@ -33,11 +33,6 @@ public class EditorTerminalPane extends EditorPane {
/** Frames a new grid sits still before the server is told: dragging a sash resizes every frame. */ /** 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 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); private final TerminalEmulator emu = new TerminalEmulator(DEFAULT_COLS, DEFAULT_ROWS, this::answerShell);
/** Lines the view is lifted from the bottom; 0 = pinned, following. */ /** Lines the view is lifted from the bottom; 0 = pinned, following. */
@@ -95,7 +90,7 @@ public class EditorTerminalPane extends EditorPane {
shellAlive = false; shellAlive = false;
sentRows = sentCols = -1; sentRows = sentCols = -1;
pendingRows = -1; pendingRows = -1;
emu.writeText(reason + "\r\n", COLOR_NOTE); emu.writeText(reason + "\r\n", editorManager.theme().terminalNote());
} }
/** A fresh shell is starting: an empty screen, and what is happening. */ /** A fresh shell is starting: an empty screen, and what is happening. */
@@ -118,7 +113,7 @@ public class EditorTerminalPane extends EditorPane {
pendingRows = emu.rows(); pendingRows = emu.rows();
pendingCols = emu.cols(); pendingCols = emu.cols();
pendingFrames = 0; pendingFrames = 0;
emu.writeText(what + "\r\n", COLOR_NOTE); emu.writeText(what + "\r\n", editorManager.theme().terminalNote());
} }
// ── Geometry: the grid follows the pane, and the server is told of it ─ // ── Geometry: the grid follows the pane, and the server is told of it ─
@@ -182,7 +177,7 @@ public class EditorTerminalPane extends EditorPane {
int top = getStartY() + PAD; int top = getStartY() + PAD;
int rows = emu.rows(); int rows = emu.rows();
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), COLOR_BACKGROUND); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().terminalBackground());
graphics.enableScissor(getStartX(), top, getEndX(), getEndY() - PAD); graphics.enableScissor(getStartX(), top, getEndX(), getEndY() - PAD);
// The content is scrollback, then the screen; the view is a window of // The content is scrollback, then the screen; the view is a window of
@@ -215,14 +210,14 @@ public class EditorTerminalPane extends EditorPane {
char at = emu.charAt(line, emu.cursorX()); char at = emu.charAt(line, emu.cursorX());
if (editorScreen.selectedWidget == this) { if (editorScreen.selectedWidget == this) {
graphics.fill(x, y, x + cellW, y + lineH, COLOR_CURSOR); graphics.fill(x, y, x + cellW, y + lineH, editorManager.theme().terminalCursor());
if (at != ' ') graphics.text(font, String.valueOf(at), x, y, COLOR_CURSOR_TEXT, false); if (at != ' ') graphics.text(font, String.valueOf(at), x, y, editorManager.theme().terminalBackground(), false);
} else { } else {
// The keyboard belongs elsewhere: an outline, not a block. // The keyboard belongs elsewhere: an outline, not a block.
graphics.fill(x, y, x + cellW, y + 1, COLOR_CURSOR); graphics.fill(x, y, x + cellW, y + 1, editorManager.theme().terminalCursor());
graphics.fill(x, y + lineH - 1, x + cellW, y + lineH, COLOR_CURSOR); graphics.fill(x, y + lineH - 1, x + cellW, y + lineH, editorManager.theme().terminalCursor());
graphics.fill(x, y + 1, x + 1, y + lineH - 1, COLOR_CURSOR); graphics.fill(x, y + 1, x + 1, y + lineH - 1, editorManager.theme().terminalCursor());
graphics.fill(x + cellW - 1, y + 1, x + cellW, y + lineH - 1, COLOR_CURSOR); graphics.fill(x + cellW - 1, y + 1, x + cellW, y + lineH - 1, editorManager.theme().terminalCursor());
} }
} }

View File

@@ -0,0 +1,75 @@
package com.aranroig.client.editor;
/** Shared color palettes for the editor and its auxiliary panels. */
public enum EditorTheme {
MIDNIGHT("Midnight", new Palette(
0xFF303030, 0xFF202020, 0xFF262626, 0xFF3C3C3C, 0xFF2D2D2D,
0xFFFFFFFF, 0xFF9A9A9A, 0xFF444444, 0xFF44688A, 0xFF0055AA,
0xFF383868, 0xFF2A2A3A, 0xFF7A3D3D,
0xFFC79A55, 0xFFE8BC6E, 0xFF8A683A, 0xFFA9BCCB, 0xFF5F7484,
0xFFFFFFFF, 0x66FFFFFF,
0xFFD4D4D4, 0xFF569CD6, 0xFF4EC9B0, 0xFFCE9178, 0xFFB5CEA8,
0xFF6A9955, 0xFF9CDCFE, 0xFFDCDCAA, 0xFF555577,
0xFF141414, 0xFF888888, 0xFF141414, 0xB0000000)),
LIGHT("Light", new Palette(
0xFFFFFFFF, 0xFFF3F3F3, 0xFFE7E7E7, 0xFFD6E8FA, 0xFFE4EFFF,
0xFF1F1F1F, 0xFF666666, 0xFFC8C8C8, 0xFF007ACC, 0xFF1B8AD6,
0xFFADD6FF, 0xFFEAF3FB, 0xFFB42318,
0xFFB7791F, 0xFFD69B36, 0xFF8A5C18, 0xFF637B8A, 0xFF8497A2,
0xFF333333, 0x66333333,
0xFF202020, 0xFF0000FF, 0xFF267F99, 0xFFA31515, 0xFF098658,
0xFF008000, 0xFF001080, 0xFF795E26, 0xFF777777,
0xFFEEEEEE, 0xFF777777, 0xFFEEEEEE, 0xB0000000)),
NORD("Nord", new Palette(
0xFF2E3440, 0xFF292E39, 0xFF3B4252, 0xFF434C5E, 0xFF3A4250,
0xFFECEFF4, 0xFFD8DEE9, 0xFF4C566A, 0xFF88C0D0, 0xFF81A1C1,
0xFF434C5E, 0xFF3B4252, 0xFFBF616A,
0xFFEBCB8B, 0xFFF0D399, 0xFFB48E5D, 0xFF8FBCBB, 0xFF5E81AC,
0xFFECEFF4, 0x66ECEFF4,
0xFFD8DEE9, 0xFF81A1C1, 0xFF8FBCBB, 0xFFA3BE8C, 0xFFB48EAD,
0xFF616E88, 0xFF88C0D0, 0xFFEBCB8B, 0xFF616E88,
0xFF242933, 0xFF9AA5B5, 0xFF242933, 0xB0000000)),
MONOKAI("Monokai", new Palette(
0xFF272822, 0xFF202119, 0xFF303128, 0xFF414236, 0xFF38392E,
0xFFF8F8F2, 0xFF9B9B8F, 0xFF49483E, 0xFFA6E22E, 0xFFB6F34C,
0xFF49483E, 0xFF3A3B32, 0xFFF92672,
0xFFE6DB74, 0xFFF0E68C, 0xFF8F874F, 0xFFA6E22E, 0xFF75715E,
0xFFF8F8F2, 0x66F8F8F2,
0xFFF8F8F2, 0xFFF92672, 0xFFA6E22E, 0xFFE6DB74, 0xFFAE81FF,
0xFF75715E, 0xFFFD971F, 0xFFA6E22E, 0xFF75715E,
0xFF1E1F1A, 0xFF909185, 0xFF1E1F1A, 0xB0000000));
private final String displayName;
private final Palette palette;
EditorTheme(String displayName, Palette palette) {
this.displayName = displayName;
this.palette = palette;
}
public String displayName() {
return displayName;
}
public Palette palette() {
return palette;
}
public static EditorTheme fromName(String name) {
for (EditorTheme theme : values()) {
if (theme.name().equalsIgnoreCase(name) || theme.displayName.equalsIgnoreCase(name)) return theme;
}
return MIDNIGHT;
}
public record Palette(
int background, int sidebarBackground, int raisedBackground, int activeBackground, int hoverBackground,
int text, int mutedText, int border, int accent, int accentHover,
int selection, int selectionHover, int danger,
int folder, int folderBright, int folderSeam, int fileIcon, int fileDetail,
int cursor, int dimCursor,
int syntaxDefault, int syntaxKeyword, int syntaxBuiltin, int syntaxString, int syntaxNumber,
int syntaxComment, int syntaxParam, int syntaxMethod, int hint,
int terminalBackground, int terminalNote, int terminalCursor, int overlay) {
}
}

View File

@@ -20,16 +20,6 @@ public class EditorTopBar extends Widget {
private static final int TAB_PADDING_Y = 2; private static final int TAB_PADDING_Y = 2;
// ── Colors ──────────────────────────────────────────────────────────── // ── Colors ────────────────────────────────────────────────────────────
private static final int COLOR_TEXT = 0xFFFFFFFF;
private static final int COLOR_BACKGROUND = 0xFF1C1C1C;
private static final int COLOR_TAB_HOVER = 0xFF2D2D2D;
private static final int COLOR_TAB_OPEN = 0xFF3A3A3A;
private static final int COLOR_DROPDOWN_BG = 0xFF252525;
private static final int COLOR_ITEM_HOVER = 0xFF0055AA;
private static final int COLOR_SEPARATOR = 0xFF444444;
// ── Menu definitions ────────────────────────────────────────────────── // ── Menu definitions ──────────────────────────────────────────────────
private record MenuItem(String label, boolean isSeparator) { private record MenuItem(String label, boolean isSeparator) {
static MenuItem item(String label) { return new MenuItem(label, false); } static MenuItem item(String label) { return new MenuItem(label, false); }
@@ -69,10 +59,17 @@ public class EditorTopBar extends Widget {
), ),
// View // View
List.of( List.of(
MenuItem.item("Toggle Sidebar"),
MenuItem.separator(),
MenuItem.item("Split Right"), MenuItem.item("Split Right"),
MenuItem.item("Split Below"), MenuItem.item("Split Below"),
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Close Pane") MenuItem.item("Close Pane"),
MenuItem.separator(),
MenuItem.item("Midnight"),
MenuItem.item("Light"),
MenuItem.item("Nord"),
MenuItem.item("Monokai")
), ),
// Help // Help
List.of( List.of(
@@ -90,8 +87,6 @@ public class EditorTopBar extends Widget {
// The one action that deserves to be a button instead of a menu item. // The one action that deserves to be a button instead of a menu item.
private static final String SHELL_LABEL = ">_ Shell"; 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 shellButtonWidth(Font font) { return font.width(SHELL_LABEL) + TAB_PADDING_X * 2 + 2; }
private int shellButtonX0(Font font) { return getEndX() - shellButtonWidth(font); } private int shellButtonX0(Font font) { return getEndX() - shellButtonWidth(font); }
@@ -109,11 +104,12 @@ public class EditorTopBar extends Widget {
boolean hovered = insideShellButton(mouseX, mouseY, font); boolean hovered = insideShellButton(mouseX, mouseY, font);
graphics.fill(x0, y0, getEndX(), y1, graphics.fill(x0, y0, getEndX(), y1,
open ? COLOR_TAB_OPEN : hovered ? COLOR_TAB_HOVER : COLOR_BACKGROUND); open ? editorManager.theme().activeBackground()
graphics.text(font, SHELL_LABEL, x0 + TAB_PADDING_X, y0 + TAB_PADDING_Y, COLOR_TEXT, false); : hovered ? editorManager.theme().hoverBackground() : editorManager.theme().sidebarBackground());
graphics.text(font, SHELL_LABEL, x0 + TAB_PADDING_X, y0 + TAB_PADDING_Y, editorManager.theme().text(), false);
// The same underline the active pane header wears: this pane is open. // The same underline the active pane header wears: this pane is open.
if (open) graphics.fill(x0, y1 - 1, getEndX(), y1, COLOR_SHELL_ACCENT); if (open) graphics.fill(x0, y1 - 1, getEndX(), y1, editorManager.theme().accent());
} }
// ── Drawing ─────────────────────────────────────────────────────────── // ── Drawing ───────────────────────────────────────────────────────────
@@ -122,7 +118,8 @@ public class EditorTopBar extends Widget {
// Bar background // Bar background
Font font = editorScreen.getFont(); Font font = editorScreen.getFont();
cachedFont = font; cachedFont = font;
graphics.fill(getStartX(), getStartY(), getEndX(), getStartY() + BAR_HEIGHT, COLOR_BACKGROUND); graphics.fill(getStartX(), getStartY(), getEndX(), getStartY() + BAR_HEIGHT,
editorManager.theme().sidebarBackground());
this.mouseX = mouseX; this.mouseX = mouseX;
this.mouseY = mouseY; this.mouseY = mouseY;
@@ -140,14 +137,15 @@ public class EditorTopBar extends Widget {
boolean isOpen = openTab == i; boolean isOpen = openTab == i;
// Tab background // Tab background
int bg = isOpen ? COLOR_TAB_OPEN : (hovered ? COLOR_TAB_HOVER : COLOR_BACKGROUND); int bg = isOpen ? editorManager.theme().activeBackground()
: (hovered ? editorManager.theme().hoverBackground() : editorManager.theme().sidebarBackground());
graphics.fill(tabX, getStartY(), tabEndX, tabEndY, bg); graphics.fill(tabX, getStartY(), tabEndX, tabEndY, bg);
// Tab label // Tab label
graphics.text(font, label, graphics.text(font, label,
tabX + TAB_PADDING_X, tabX + TAB_PADDING_X,
getStartY() + TAB_PADDING_Y, getStartY() + TAB_PADDING_Y,
COLOR_TEXT, false); editorManager.theme().text(), false);
// Dropdown // Dropdown
if (isOpen) { if (isOpen) {
@@ -189,7 +187,7 @@ public class EditorTopBar extends Widget {
x += font.width(editor.name()) + 13; x += font.width(editor.name()) + 13;
} }
if (!more.isEmpty()) { if (!more.isEmpty()) {
graphics.text(font, more, x, y, COLOR_TEXT, false); graphics.text(font, more, x, y, editorManager.theme().text(), false);
} }
} }
@@ -279,29 +277,30 @@ public class EditorTopBar extends Widget {
for (MenuItem m : items) totalH += m.isSeparator() ? 5 : itemH; for (MenuItem m : items) totalH += m.isSeparator() ? 5 : itemH;
// Background + border // Background + border
graphics.fill(tabX, topY, dropX2, topY + totalH, COLOR_DROPDOWN_BG); graphics.fill(tabX, topY, dropX2, topY + totalH, editorManager.theme().raisedBackground());
graphics.fill(tabX, topY, dropX2, topY + 1, COLOR_SEPARATOR); // top graphics.fill(tabX, topY, dropX2, topY + 1, editorManager.theme().border()); // top
graphics.fill(tabX, topY, tabX + 1, topY + totalH, COLOR_SEPARATOR); // left graphics.fill(tabX, topY, tabX + 1, topY + totalH, editorManager.theme().border()); // left
graphics.fill(dropX2-1, topY, dropX2, topY + totalH, COLOR_SEPARATOR); // right graphics.fill(dropX2-1, topY, dropX2, topY + totalH, editorManager.theme().border()); // right
graphics.fill(tabX, topY+totalH-1, dropX2, topY + totalH, COLOR_SEPARATOR); // bottom graphics.fill(tabX, topY+totalH-1, dropX2, topY + totalH, editorManager.theme().border()); // bottom
int curY = topY; int curY = topY;
for (MenuItem item : items) { for (int i = 0; i < items.size(); i++) {
MenuItem item = items.get(i);
if (item.isSeparator()) { if (item.isSeparator()) {
graphics.fill(tabX + 4, curY + 2, dropX2 - 4, curY + 3, COLOR_SEPARATOR); graphics.fill(tabX + 4, curY + 2, dropX2 - 4, curY + 3, editorManager.theme().border());
curY += 5; curY += 5;
} else { } else {
boolean hovered = mouseX >= tabX && mouseX < dropX2 boolean hovered = mouseX >= tabX && mouseX < dropX2
&& mouseY >= curY && mouseY < curY + itemH; && mouseY >= curY && mouseY < curY + itemH;
if (hovered) { if (hovered) {
graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, COLOR_ITEM_HOVER); graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, editorManager.theme().accentHover());
} }
graphics.text(font, item.label(), graphics.text(font, displayLabel(tabIndex, i),
tabX + TAB_PADDING_X, tabX + TAB_PADDING_X,
curY + TAB_PADDING_Y, curY + TAB_PADDING_Y,
COLOR_TEXT, false); editorManager.theme().text(), false);
curY += itemH; curY += itemH;
} }
@@ -323,10 +322,15 @@ public class EditorTopBar extends Widget {
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 "Toggle Sidebar" -> editorManager.toggleSidebar();
case "Split Right" -> editorManager.splitRight(); case "Split Right" -> editorManager.splitRight();
case "Split Below" -> editorManager.splitBelow(); case "Split Below" -> editorManager.splitBelow();
case "Close Pane" -> editorManager.closeActivePane(); case "Close Pane" -> editorManager.closeActivePane();
case "Lua API Documentation" -> editorManager.openDocs(); case "Lua API Documentation" -> editorManager.openDocs();
case "Midnight" -> editorManager.setTheme(EditorTheme.MIDNIGHT);
case "Light" -> editorManager.setTheme(EditorTheme.LIGHT);
case "Nord" -> editorManager.setTheme(EditorTheme.NORD);
case "Monokai" -> editorManager.setTheme(EditorTheme.MONOKAI);
// 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());
} }
@@ -336,14 +340,24 @@ public class EditorTopBar extends Widget {
private int dropdownWidth(Font font, int tabIndex) { private int dropdownWidth(Font font, int tabIndex) {
int maxW = 80; // minimum dropdown width int maxW = 80; // minimum dropdown width
for (MenuItem item : TAB_ITEMS.get(tabIndex)) { List<MenuItem> items = TAB_ITEMS.get(tabIndex);
for (int i = 0; i < items.size(); i++) {
MenuItem item = items.get(i);
if (!item.isSeparator()) { if (!item.isSeparator()) {
maxW = Math.max(maxW, font.width(item.label()) + TAB_PADDING_X * 2 + 8); maxW = Math.max(maxW, font.width(displayLabel(tabIndex, i)) + TAB_PADDING_X * 2 + 8);
} }
} }
return maxW; return maxW;
} }
private String displayLabel(int tabIndex, int itemIndex) {
MenuItem item = TAB_ITEMS.get(tabIndex).get(itemIndex);
if (tabIndex == 3 && item.label().equals(editorManager.currentTheme().displayName())) {
return "✓ " + item.label();
}
return item.label();
}
private int getClickedItemIndex(int mx, int my, int tabIndex) { private int getClickedItemIndex(int mx, int my, int tabIndex) {
int tabX = getStartX(); int tabX = getStartX();
for (int i = 0; i < tabIndex; i++) { for (int i = 0; i < tabIndex; i++) {
@@ -402,4 +416,4 @@ public class EditorTopBar extends Widget {
/** Lazy accessor — store the font reference after the first draw() call if preferred. */ /** Lazy accessor — store the font reference after the first draw() call if preferred. */
private Font cachedFont; private Font cachedFont;
private Font font() { return cachedFont; } private Font font() { return cachedFont; }
} }

View File

@@ -24,24 +24,12 @@ import java.util.Set;
* </ul> * </ul>
* *
* <p>Multi-line strings/comments ({@code [[ … ]]}) require cross-line state; * <p>Multi-line strings/comments ({@code [[ … ]]}) require cross-line state;
* that state is carried through {@link #tokenizeLine(String, boolean)} via the * that state is carried through {@link #tokenizeLine(String, boolean, EditorTheme.Palette)} via the
* {@code inMultilineString} flag, and the method returns whether the caller * {@code inMultilineString} flag, and the method returns whether the caller
* should pass {@code true} for the <em>next</em> line. * should pass {@code true} for the <em>next</em> line.
*/ */
public class LuaHighlighter { public class LuaHighlighter {
// ── Token colours (VSCode-dark palette) ──────────────────────────────
public static final int C_DEFAULT = 0xFFD4D4D4; // plain identifiers / text
public static final int C_KEYWORD = 0xFF569CD6; // language keywords
public static final int C_BUILTIN = 0xFF4EC9B0; // built-in functions & globals
public static final int C_LIBRARY = 0xFF4EC9B0; // std-lib table names (math, …)
public static final int C_STRING = 0xFFCE9178; // string literals
public static final int C_NUMBER = 0xFFB5CEA8; // numeric literals
public static final int C_COMMENT = 0xFF6A9955; // comments
public static final int C_OPERATOR = 0xFFD4D4D4; // operators / punctuation
public static final int C_BOOLEAN = 0xFF569CD6; // true / false / nil
public static final int C_PARAM = 0xFF9CDCFE; // function parameters (heuristic)
// ── Lua vocabulary ──────────────────────────────────────────────────── // ── Lua vocabulary ────────────────────────────────────────────────────
private static final Set<String> KEYWORDS = Set.of( private static final Set<String> KEYWORDS = Set.of(
@@ -56,7 +44,7 @@ public class LuaHighlighter {
private static final Set<String> BUILTINS = Set.of( private static final Set<String> BUILTINS = Set.of(
"assert", "collectgarbage", "dofile", "error", "assert", "collectgarbage", "dofile", "error",
"getmetatable", "ipairs", "load", "loadfile", "next", "getmetatable", "ipairs", "load", "loadfile", "next",
"pairs", "pcall", "print", "rawequal", "rawget", "pairs", "pcall", "print", "run", "rawequal", "rawget",
"rawlen", "rawset", "require", "select", "setmetatable", "rawlen", "rawset", "require", "select", "setmetatable",
"tonumber", "tostring", "type", "unpack", "xpcall", "tonumber", "tostring", "type", "unpack", "xpcall",
"_G", "_VERSION" "_G", "_VERSION"
@@ -89,7 +77,7 @@ public class LuaHighlighter {
* previous line and hasn't been closed yet * previous line and hasn't been closed yet
* @return spans + continuation flag * @return spans + continuation flag
*/ */
public LineTokens tokenizeLine(String rawLine, boolean inMultilineString) { public LineTokens tokenizeLine(String rawLine, boolean inMultilineString, EditorTheme.Palette theme) {
List<Span> spans = new ArrayList<>(); List<Span> spans = new ArrayList<>();
int len = rawLine.length(); int len = rawLine.length();
int i = 0; int i = 0;
@@ -99,11 +87,11 @@ public class LuaHighlighter {
int close = rawLine.indexOf("]]"); int close = rawLine.indexOf("]]");
if (close == -1) { if (close == -1) {
// Entire line is still inside the block string // Entire line is still inside the block string
spans.add(new Span(rawLine, C_STRING)); spans.add(new Span(rawLine, theme.syntaxString()));
return new LineTokens(spans, true); return new LineTokens(spans, true);
} else { } else {
// Closing delimiter is on this line // Closing delimiter is on this line
spans.add(new Span(rawLine.substring(0, close + 2), C_STRING)); spans.add(new Span(rawLine.substring(0, close + 2), theme.syntaxString()));
i = close + 2; i = close + 2;
inMultilineString = false; inMultilineString = false;
} }
@@ -116,33 +104,33 @@ public class LuaHighlighter {
// ── Single-line comment ─────────────────────────────────────── // ── Single-line comment ───────────────────────────────────────
if (c == '-' && i + 1 < len && rawLine.charAt(i + 1) == '-') { if (c == '-' && i + 1 < len && rawLine.charAt(i + 1) == '-') {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
// Check for long comment --[[ … ]] // Check for long comment --[[ … ]]
if (i + 3 < len && rawLine.charAt(i + 2) == '[' && rawLine.charAt(i + 3) == '[') { if (i + 3 < len && rawLine.charAt(i + 2) == '[' && rawLine.charAt(i + 3) == '[') {
int close = rawLine.indexOf("]]", i + 4); int close = rawLine.indexOf("]]", i + 4);
if (close == -1) { if (close == -1) {
spans.add(new Span(rawLine.substring(i), C_COMMENT)); spans.add(new Span(rawLine.substring(i), theme.syntaxComment()));
return new LineTokens(spans, true); // multi-line comment (treated like string) return new LineTokens(spans, true); // multi-line comment (treated like string)
} else { } else {
spans.add(new Span(rawLine.substring(i, close + 2), C_COMMENT)); spans.add(new Span(rawLine.substring(i, close + 2), theme.syntaxComment()));
i = close + 2; i = close + 2;
continue; continue;
} }
} }
// Regular -- comment: rest of line // Regular -- comment: rest of line
spans.add(new Span(rawLine.substring(i), C_COMMENT)); spans.add(new Span(rawLine.substring(i), theme.syntaxComment()));
return new LineTokens(spans, false); return new LineTokens(spans, false);
} }
// ── Multi-line string literal [[ ───────────────────────────── // ── Multi-line string literal [[ ─────────────────────────────
if (c == '[' && i + 1 < len && rawLine.charAt(i + 1) == '[') { if (c == '[' && i + 1 < len && rawLine.charAt(i + 1) == '[') {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
int close = rawLine.indexOf("]]", i + 2); int close = rawLine.indexOf("]]", i + 2);
if (close == -1) { if (close == -1) {
spans.add(new Span(rawLine.substring(i), C_STRING)); spans.add(new Span(rawLine.substring(i), theme.syntaxString()));
return new LineTokens(spans, true); return new LineTokens(spans, true);
} else { } else {
spans.add(new Span(rawLine.substring(i, close + 2), C_STRING)); spans.add(new Span(rawLine.substring(i, close + 2), theme.syntaxString()));
i = close + 2; i = close + 2;
continue; continue;
} }
@@ -150,7 +138,7 @@ public class LuaHighlighter {
// ── String literal " or ' ───────────────────────────────────── // ── String literal " or ' ─────────────────────────────────────
if (c == '"' || c == '\'') { if (c == '"' || c == '\'') {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
char quote = c; char quote = c;
int start = i; int start = i;
i++; i++;
@@ -160,13 +148,13 @@ public class LuaHighlighter {
if (ch == quote) { i++; break; } if (ch == quote) { i++; break; }
i++; i++;
} }
spans.add(new Span(rawLine.substring(start, i), C_STRING)); spans.add(new Span(rawLine.substring(start, i), theme.syntaxString()));
continue; continue;
} }
// ── Number literal ──────────────────────────────────────────── // ── Number literal ────────────────────────────────────────────
if (Character.isDigit(c) || (c == '.' && i + 1 < len && Character.isDigit(rawLine.charAt(i + 1)))) { if (Character.isDigit(c) || (c == '.' && i + 1 < len && Character.isDigit(rawLine.charAt(i + 1)))) {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
int start = i; int start = i;
// Hex? // Hex?
if (c == '0' && i + 1 < len && (rawLine.charAt(i + 1) == 'x' || rawLine.charAt(i + 1) == 'X')) { if (c == '0' && i + 1 < len && (rawLine.charAt(i + 1) == 'x' || rawLine.charAt(i + 1) == 'X')) {
@@ -180,13 +168,13 @@ public class LuaHighlighter {
while (i < len && Character.isDigit(rawLine.charAt(i))) i++; while (i < len && Character.isDigit(rawLine.charAt(i))) i++;
} }
} }
spans.add(new Span(rawLine.substring(start, i), C_NUMBER)); spans.add(new Span(rawLine.substring(start, i), theme.syntaxNumber()));
continue; continue;
} }
// ── Identifier or keyword ───────────────────────────────────── // ── Identifier or keyword ─────────────────────────────────────
if (Character.isLetter(c) || c == '_') { if (Character.isLetter(c) || c == '_') {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
int start = i; int start = i;
while (i < len && (Character.isLetterOrDigit(rawLine.charAt(i)) || rawLine.charAt(i) == '_')) i++; while (i < len && (Character.isLetterOrDigit(rawLine.charAt(i)) || rawLine.charAt(i) == '_')) i++;
String word = rawLine.substring(start, i); String word = rawLine.substring(start, i);
@@ -197,32 +185,32 @@ public class LuaHighlighter {
boolean isMember = (start > 0 && (rawLine.charAt(start - 1) == '.' || rawLine.charAt(start - 1) == ':')); boolean isMember = (start > 0 && (rawLine.charAt(start - 1) == '.' || rawLine.charAt(start - 1) == ':'));
if (BOOLEAN_NIL.contains(word)) { if (BOOLEAN_NIL.contains(word)) {
spans.add(new Span(word, C_BOOLEAN)); spans.add(new Span(word, theme.syntaxKeyword()));
} else if (KEYWORDS.contains(word)) { } else if (KEYWORDS.contains(word)) {
spans.add(new Span(word, C_KEYWORD)); spans.add(new Span(word, theme.syntaxKeyword()));
} else if (!isMember && LIBRARIES.contains(word)) { } else if (!isMember && LIBRARIES.contains(word)) {
spans.add(new Span(word, C_LIBRARY)); spans.add(new Span(word, theme.syntaxBuiltin()));
} else if (!isMember && BUILTINS.contains(word)) { } else if (!isMember && BUILTINS.contains(word)) {
spans.add(new Span(word, C_BUILTIN)); spans.add(new Span(word, theme.syntaxBuiltin()));
} else if (isCall) { } else if (isCall) {
// User-defined function call: slightly highlighted // User-defined function call: slightly highlighted
spans.add(new Span(word, C_BUILTIN)); spans.add(new Span(word, theme.syntaxBuiltin()));
} else { } else {
spans.add(new Span(word, C_DEFAULT)); spans.add(new Span(word, theme.syntaxDefault()));
} }
continue; continue;
} }
// ── Operator / punctuation ──────────────────────────────────── // ── Operator / punctuation ────────────────────────────────────
if (isOperator(c)) { if (isOperator(c)) {
flushPlain(spans, plain); flushPlain(spans, plain, theme);
// Grab multi-char operators: ~=, ==, <=, >=, .., ... // Grab multi-char operators: ~=, ==, <=, >=, .., ...
if (i + 2 < len && rawLine.charAt(i) == '.' && rawLine.charAt(i+1) == '.' && rawLine.charAt(i+2) == '.') { if (i + 2 < len && rawLine.charAt(i) == '.' && rawLine.charAt(i+1) == '.' && rawLine.charAt(i+2) == '.') {
spans.add(new Span("...", C_OPERATOR)); i += 3; spans.add(new Span("...", theme.syntaxDefault())); i += 3;
} else if (i + 1 < len && isTwoCharOp(rawLine, i)) { } else if (i + 1 < len && isTwoCharOp(rawLine, i)) {
spans.add(new Span(rawLine.substring(i, i + 2), C_OPERATOR)); i += 2; spans.add(new Span(rawLine.substring(i, i + 2), theme.syntaxDefault())); i += 2;
} else { } else {
spans.add(new Span(String.valueOf(c), C_OPERATOR)); i++; spans.add(new Span(String.valueOf(c), theme.syntaxDefault())); i++;
} }
continue; continue;
} }
@@ -232,15 +220,15 @@ public class LuaHighlighter {
i++; i++;
} }
flushPlain(spans, plain); flushPlain(spans, plain, theme);
return new LineTokens(spans, false); return new LineTokens(spans, false);
} }
// ── Helpers ─────────────────────────────────────────────────────────── // ── Helpers ───────────────────────────────────────────────────────────
private static void flushPlain(List<Span> spans, StringBuilder sb) { private static void flushPlain(List<Span> spans, StringBuilder sb, EditorTheme.Palette theme) {
if (sb.length() > 0) { if (sb.length() > 0) {
spans.add(new Span(sb.toString(), C_DEFAULT)); spans.add(new Span(sb.toString(), theme.syntaxDefault()));
sb.setLength(0); sb.setLength(0);
} }
} }
@@ -264,4 +252,4 @@ public class LuaHighlighter {
|| (a == '<' && b == '<') || (a == '<' && b == '<')
|| (a == '>' && b == '>'); || (a == '>' && b == '>');
} }
} }

View File

@@ -0,0 +1,28 @@
package com.aranroig.client.editor;
import java.util.List;
/** Autocomplete members for server-side Minecraft APIs exposed to Lua. */
public final class MinecraftLibraries {
private MinecraftLibraries() {
}
public static List<LuaLibrary> all() {
return List.of(
library("entities", "nearby", "spawn", "get", "teleport", "remove", "set_name", "set_health"),
library("scoreboard", "create_objective", "remove_objective", "set", "add", "get", "reset", "display"),
library("hud", "title", "subtitle", "action_bar", "title_times", "clear_titles", "bossbar_add", "bossbar_remove", "bossbar_value", "bossbar_max", "bossbar_visible"),
library("items", "give", "count", "clear", "get_slot", "set_slot")
);
}
private static LuaLibrary library(String name, String... names) {
List<CompletionItem> members = java.util.Arrays.stream(names)
.map(member -> CompletionItem.method(member, member + "("))
.toList();
return new LuaLibrary() {
@Override public String name() { return name; }
@Override public List<CompletionItem> members() { return members; }
};
}
}

View File

@@ -1,9 +1,14 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class TextEditorScreen extends EditorScreen { public class TextEditorScreen extends EditorScreen {
private final EditorManager editorManager; private final EditorManager editorManager;
@@ -25,6 +30,15 @@ public class TextEditorScreen extends EditorScreen {
super.onClose(); super.onClose();
} }
@Override
public boolean keyPressed(KeyEvent event) {
if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B
editorManager.toggleSidebar();
return true;
}
return super.keyPressed(event);
}
@Override @Override
public void extractRenderState( public void extractRenderState(
@NonNull GuiGraphicsExtractor graphics, @NonNull GuiGraphicsExtractor graphics,
@@ -34,7 +48,15 @@ public class TextEditorScreen extends EditorScreen {
) { ) {
super.extractRenderState(graphics, mouseX, mouseY, delta); super.extractRenderState(graphics, mouseX, mouseY, delta);
for (Widget widget : widgets) { // Draw back-to-front by z-index, the same order raycastWidget uses to
// pick what the mouse hits. Painting in plain insertion order would let
// a later-added text-editor pane cover the top bar's dropdown menus, or
// cover the docs modal a split pane was added after. List.sort is stable,
// so widgets sharing a z-index keep the order they were added in.
List<Widget> ordered = new ArrayList<>(widgets);
ordered.sort(Comparator.comparingInt(Widget::getZIndex));
for (Widget widget : ordered) {
widget.draw(graphics, mouseX, mouseY, delta); widget.draw(graphics, mouseX, mouseY, delta);
} }
} }

View File

@@ -11,7 +11,14 @@ public class WorldLibrary implements LuaLibrary {
private static final List<CompletionItem> MEMBERS = List.of( private static final List<CompletionItem> MEMBERS = List.of(
CompletionItem.method("set_block", "set_block("), CompletionItem.method("set_block", "set_block("),
CompletionItem.method("remove_block", "remove_block("), CompletionItem.method("remove_block", "remove_block("),
CompletionItem.method("get_block", "get_block(") CompletionItem.method("get_block", "get_block("),
CompletionItem.method("get_dimension", "get_dimension("),
CompletionItem.method("get_time", "get_time("),
CompletionItem.method("set_time", "set_time("),
CompletionItem.method("get_weather", "get_weather("),
CompletionItem.method("set_weather", "set_weather("),
CompletionItem.method("get_biome", "get_biome("),
CompletionItem.method("players", "players(")
); );
@Override @Override

View File

@@ -26,6 +26,7 @@ import com.aranroig.payloads.ServerboundSaveCodePayload;
import com.aranroig.payloads.ServerboundShellInputPayload; import com.aranroig.payloads.ServerboundShellInputPayload;
import com.aranroig.payloads.ServerboundShellResizePayload; import com.aranroig.payloads.ServerboundShellResizePayload;
import com.aranroig.payloads.ServerboundSpawnShellPayload; import com.aranroig.payloads.ServerboundSpawnShellPayload;
import com.aranroig.project.ProjectStore;
import com.aranroig.shell.ShellManager; import com.aranroig.shell.ShellManager;
import net.fabricmc.api.ModInitializer; import net.fabricmc.api.ModInitializer;
@@ -34,7 +35,6 @@ import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.chat.Component; import net.minecraft.network.chat.Component;
import net.minecraft.resources.Identifier; import net.minecraft.resources.Identifier;
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;
@@ -83,6 +83,12 @@ public class Codecraft implements ModInitializer {
// currently running script happens per event. // currently running script happens per event.
ScriptRuntimeManager.install(); ScriptRuntimeManager.install();
// The project now lives as plain .lua files under config/codecraft:
// move a world's scripts out of its saved data the first time a
// server starts, and drain the queued keystroke writes to disk before
// it stops.
ProjectStore.install();
// Drop players from their live editing sessions when they leave, and // Drop players from their live editing sessions when they leave, and
// throw the cached documents away when the world stops. // throw the cached documents away when the world stops.
DocumentManager.install(); DocumentManager.install();
@@ -92,17 +98,15 @@ public class Codecraft implements ModInitializer {
ShellManager.install(); ShellManager.install();
ServerPlayNetworking.registerGlobalReceiver(ServerboundRequestProjectPayload.TYPE, (payload, context) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundRequestProjectPayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer(); // Read fresh from disk every time the editor opens: scripts edited
if(server == null) return; // with an external editor in the meantime are in here too.
List<EditorFile> files = ProjectStore.loadAll();
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
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. // Names carry no extension: the sidebar shows them as they are.
if(files.isEmpty()) { if(files.isEmpty()) {
files.add(new EditorFile(ProjectPath.ENTRYPOINT, "")); ProjectStore.write(ProjectPath.ENTRYPOINT, "");
savedData.setEditorFiles(files); files = List.of(new EditorFile(ProjectPath.ENTRYPOINT, ""));
} }
ServerPlayNetworking.send(context.player(), new ClientboundProjectFilesPayload(List.copyOf(files))); ServerPlayNetworking.send(context.player(), new ClientboundProjectFilesPayload(List.copyOf(files)));
@@ -160,24 +164,18 @@ public class Codecraft implements ModInitializer {
ShellManager.close(context.player())); ShellManager.close(context.player()));
ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> { ServerPlayNetworking.registerGlobalReceiver(ServerboundRunCodePayload.TYPE, (payload, context) -> {
MinecraftServer server = context.player().level().getServer();
if(server == null) return;
ServerPlayer player = context.player(); ServerPlayer player = context.player();
SavedProjectData savedData = SavedProjectData.getSavedBlockData(server);
List<EditorFile> files = savedData.getEditorFiles();
String entrypoint = payload.data().getEntrypoint(); String entrypoint = payload.data().getEntrypoint();
LOGGER.info("Running entrypoint {}", entrypoint); LOGGER.info("Running entrypoint {}", entrypoint);
EditorFile target = findByName(files, entrypoint); String code = ProjectStore.read(entrypoint);
if(target == null) { if(code == null) {
// Worlds seeded while names still carried the extension. // Worlds seeded while names still carried the extension.
target = findByName(files, entrypoint + ProjectPath.LEGACY_EXTENSION); code = ProjectStore.read(entrypoint + ProjectPath.LEGACY_EXTENSION);
} }
if(target == null) { if(code == null) {
player.sendSystemMessage(Component.literal("§ccodecraft: entrypoint not found: " + entrypoint)); player.sendSystemMessage(Component.literal("§ccodecraft: entrypoint not found: " + entrypoint));
return; return;
} }
@@ -187,7 +185,7 @@ public class Codecraft implements ModInitializer {
// events on a brand-new Lua state. // events on a brand-new Lua state.
ScriptRuntime runtime = ScriptRuntimeManager.startRun(player); ScriptRuntime runtime = ScriptRuntimeManager.startRun(player);
try { try {
runtime.run(target.getText()); runtime.run(code);
} 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()));
@@ -195,14 +193,6 @@ 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

@@ -12,6 +12,15 @@ import net.minecraft.world.level.saveddata.SavedDataType;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/**
* The project files as they were stored before: baked into the world's saved
* data, where no editor outside the game could reach them.
*
* <p>Superseded by {@link com.aranroig.project.ProjectStore}, which keeps the
* project as plain files under {@code config/codecraft}. This class is kept
* only so a world updated from the old storage gets its scripts migrated
* there once; nothing reads or writes it any more besides that migration.</p>
*/
public class SavedProjectData extends SavedData { public class SavedProjectData extends SavedData {
private List<EditorFile> editorFiles; private List<EditorFile> editorFiles;

View File

@@ -1,10 +1,10 @@
package com.aranroig.collab; package com.aranroig.collab;
import com.aranroig.Codecraft; import com.aranroig.Codecraft;
import com.aranroig.SavedProjectData;
import com.aranroig.editor.Edit; import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence; import com.aranroig.editor.EditorPresence;
import com.aranroig.project.ProjectStore;
import com.aranroig.payloads.ClientboundDocumentEditPayload; import com.aranroig.payloads.ClientboundDocumentEditPayload;
import com.aranroig.payloads.ClientboundDocumentStatePayload; import com.aranroig.payloads.ClientboundDocumentStatePayload;
import com.aranroig.payloads.ClientboundEditAckPayload; import com.aranroig.payloads.ClientboundEditAckPayload;
@@ -51,7 +51,10 @@ import java.util.UUID;
* <h2>Threading</h2> * <h2>Threading</h2>
* *
* <p>All of this runs on the server thread: payload handlers and the connection * <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> * events below are dispatched there, so the maps need no locking. Nothing here
* touches the disk either: what the documents hold is written out by
* {@link com.aranroig.project.ProjectStore}, which keeps the server thread off
* the filesystem.</p>
*/ */
public final class DocumentManager { public final class DocumentManager {
@@ -112,7 +115,7 @@ public final class DocumentManager {
session.anchor = -1; session.anchor = -1;
} }
Document document = document(server, file); Document document = document(file);
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version)); ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
broadcastPresence(server, file); broadcastPresence(server, file);
@@ -141,7 +144,7 @@ public final class DocumentManager {
MinecraftServer server = server(player); MinecraftServer server = server(player);
if (server == null) return; if (server == null) return;
Document document = document(server, file); Document document = document(file);
// Never take the client's word for who wrote an edit: rebasing skips // 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. // the sender's own edits, so a spoofed author would apply one twice.
@@ -162,7 +165,7 @@ public final class DocumentManager {
} }
document.apply(applied); document.apply(applied);
boolean brandNew = persist(server, file, document.text); boolean brandNew = ProjectStore.scheduleWrite(file, document.text);
ServerPlayNetworking.send(player, ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length())); new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
@@ -184,7 +187,7 @@ public final class DocumentManager {
MinecraftServer server = server(player); MinecraftServer server = server(player);
if (server == null) return; if (server == null) return;
Document document = document(server, file); Document document = document(file);
String current = document.text; String current = document.text;
if (current.equals(text)) { if (current.equals(text)) {
@@ -192,7 +195,7 @@ public final class DocumentManager {
// has to exist on disk (a brand-new file is saved before it has // 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 // any edits flowing), and confirm the version they are on so they
// can check their copy against it. // can check their copy against it.
persist(server, file, current); ProjectStore.write(file, current);
ServerPlayNetworking.send(player, ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length())); new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length()));
} else { } else {
@@ -204,7 +207,7 @@ public final class DocumentManager {
// A whole-file save states what the file should contain, so it is // A whole-file save states what the file should contain, so it is
// applied to the server's current text instead of being rebased. // applied to the server's current text instead of being rebased.
document.apply(edit); document.apply(edit);
persist(server, file, document.text); ProjectStore.write(file, document.text);
ServerPlayNetworking.send(player, ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length())); new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
@@ -219,30 +222,16 @@ public final class DocumentManager {
/** /**
* Moves {@code oldName} to {@code newName} everywhere the server knows it: * Moves {@code oldName} to {@code newName} everywhere the server knows it:
* in the saved project, in the cached document and in the sessions of * on disk and in the write queue, in the cached document and in the
* everyone editing it — and the other editors' file lists are told. A name * sessions of everyone editing it — and the other editors' file lists are
* the project already holds is refused. * told. A name the project already holds is refused.
*/ */
public static void renameFile(ServerPlayer player, String oldName, String newName) { public static void renameFile(ServerPlayer player, String oldName, String newName) {
MinecraftServer server = server(player); MinecraftServer server = server(player);
if (server == null || oldName.equals(newName)) return; if (server == null || oldName.equals(newName)) return;
SavedProjectData data = SavedProjectData.getSavedBlockData(server); if (ProjectStore.exists(newName)) return; // the name is taken
List<EditorFile> files = data.getEditorFiles(); ProjectStore.rename(oldName, newName);
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 live document keeps its version history under the new name, so
// the editors of the file can carry on without refetching anything. // the editors of the file can carry on without refetching anything.
@@ -282,44 +271,16 @@ public final class DocumentManager {
// ── Internals ───────────────────────────────────────────────────────── // ── Internals ─────────────────────────────────────────────────────────
private static Document document(MinecraftServer server, String file) { private static Document document(String file) {
Document document = DOCUMENTS.get(file); Document document = DOCUMENTS.get(file);
if (document == null) { if (document == null) {
String text = ""; String text = ProjectStore.read(file);
for (EditorFile editorFile : SavedProjectData.getSavedBlockData(server).getEditorFiles()) { document = new Document(text == null ? "" : text);
if (editorFile.getName().equals(file)) {
text = editorFile.getText();
break;
}
}
document = new Document(text);
DOCUMENTS.put(file, document); DOCUMENTS.put(file, document);
} }
return 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} * 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 * with {@code text}. It is how one player's new file turns into a row in the

View File

@@ -19,8 +19,9 @@ import java.util.List;
* {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from * {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from
* the mod resources on first access, so documentation can be edited (and, once * the mod resources on first access, so documentation can be edited (and, once
* packed, overridden) without touching Java. It describes the functions * packed, overridden) without touching Java. It describes the functions
* registered by the wrappers in {@code com.aranroig.wrapper} (currently * registered by the wrappers in {@code com.aranroig.wrapper} (including
* {@code world} and the {@code print} helper) and by * {@code world}, {@code entities}, {@code scoreboard}, {@code hud}, {@code items},
* {@code run} and the {@code print} helper) and by
* {@link com.aranroig.listeners.EventsApi} ({@code events}). The client editor * {@link com.aranroig.listeners.EventsApi} ({@code events}). The client editor
* reads it to render the browsable documentation panel, so it is the single * reads it to render the browsable documentation panel, so it is the single
* source of truth shown to players.</p> * source of truth shown to players.</p>

View File

@@ -1,7 +1,12 @@
package com.aranroig.listeners; package com.aranroig.listeners;
import com.aranroig.wrapper.ChatLogger; import com.aranroig.wrapper.ChatLogger;
import com.aranroig.wrapper.ServerCommandApi;
import com.aranroig.wrapper.WorldApi; import com.aranroig.wrapper.WorldApi;
import com.aranroig.wrapper.EntityApi;
import com.aranroig.wrapper.HudApi;
import com.aranroig.wrapper.ItemApi;
import com.aranroig.wrapper.ScoreboardApi;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents; import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents; import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
@@ -90,8 +95,8 @@ public final class ScriptRuntimeManager {
* run}. Any listeners the player registered previously are dropped. * run}. Any listeners the player registered previously are dropped.
* *
* @param player the player who pressed <em>Run Script</em> * @param player the player who pressed <em>Run Script</em>
* @return the fresh runtime with {@code print}, {@code world} and * @return the fresh runtime with the Minecraft API tables, {@code run},
* {@code events} already registered on its Lua state * {@code print} and {@code events} already registered
*/ */
public static ScriptRuntime startRun(ServerPlayer player) { public static ScriptRuntime startRun(ServerPlayer player) {
stop(player); stop(player);
@@ -105,7 +110,12 @@ public final class ScriptRuntimeManager {
ScriptRuntime runtime = new ScriptRuntime(lua, player); ScriptRuntime runtime = new ScriptRuntime(lua, player);
lua.push(ChatLogger.print(player)); lua.push(ChatLogger.print(player));
lua.setGlobal("print"); lua.setGlobal("print");
ServerCommandApi.register(lua, player);
WorldApi.register(lua, player); WorldApi.register(lua, player);
EntityApi.register(lua, player);
ScoreboardApi.register(lua, player);
HudApi.register(lua, player);
ItemApi.register(lua, player);
EventsApi.register(lua, runtime); EventsApi.register(lua, runtime);
return runtime; return runtime;
} }

View File

@@ -0,0 +1,388 @@
package com.aranroig.project;
import com.aranroig.Codecraft;
import com.aranroig.SavedProjectData;
import com.aranroig.editor.EditorFile;
import com.aranroig.editor.ProjectPath;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.server.MinecraftServer;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
* The project as physical files on the server's machine: the file called
* {@code lib/gui/theme} lives at {@code config/codecraft/lib/gui/theme.lua},
* folders and all, so scripts can be edited, versioned and copied with
* whatever tools live outside the game. Names on disk keep the {@code .lua}
* extension even though the project's own names dropped it — an editor
* outside the game should know what it is looking at.
*
* <h2>Writing</h2>
*
* <p>An explicit save writes through at once; keystrokes do not wait for the
* disk — they land in a pending map that a daemon thread drains a beat after
* the typing settles, so a crash loses at most that much typing and the
* server thread never blocks on a file. Everything still in the queue is
* written before the server stops.</p>
*
* <p>Reading happens fresh from disk every time the editor is opened, so a
* script changed with an external editor between sessions is picked up too.
* (A file open in the editor keeps the game's copy as its authority, as
* always — external edits to a document somebody is typing in are the live
* editing protocol's problem, not this class's.)</p>
*
* <h2>Threading</h2>
*
* <p>Callers are on the server thread. The pending map is guarded by its own
* lock and every actual disk operation by {@link #DISK_LOCK}, which lets the
* writer thread and a synchronous save or flush disagree only about ordering,
* never about the same file at the same time.</p>
*/
public final class ProjectStore {
/** Scripts keep this on disk; project names carry it only when they picked one up before files dropped it. */
private static final String EXTENSION = ProjectPath.LEGACY_EXTENSION;
/** How long after the last keystroke the queued writes hit the disk. */
private static final long WRITE_DELAY_MS = 1_000;
/** Guards the disk itself: no two writers touch the same file at once. */
private static final Object DISK_LOCK = new Object();
/** Text changed but not written yet; the newest text per file wins. */
private static final Map<String, String> PENDING = new HashMap<>();
private static boolean flushScheduled = false;
/** Single daemon writer: the server thread never waits for the disk. */
private static final ScheduledExecutorService IO = Executors.newSingleThreadScheduledExecutor(runnable -> {
Thread thread = new Thread(runnable, "codecraft-project-writer");
thread.setDaemon(true);
return thread;
});
private ProjectStore() {
}
/** The folder the project lives at: {@code config/codecraft}. */
public static Path root() {
return FabricLoader.getInstance().getConfigDir().resolve(Codecraft.MOD_ID);
}
/**
* Moves old worlds' projects out of their saved data into the config
* folder when a server starts, and writes everything still queued to disk
* before it stops. Call once from {@link com.aranroig.Codecraft#onInitialize()}.
*/
public static void install() {
ServerLifecycleEvents.SERVER_STARTED.register(ProjectStore::migrateWorldData);
ServerLifecycleEvents.SERVER_STOPPING.register(server -> flushNow());
}
// ── Reading ───────────────────────────────────────────────────────────
/**
* Every script of the project, read fresh from disk: whatever was edited
* with an external editor since the last time the editor was opened is in
* here too. Typing that has not reached the disk yet wins over the older
* copy the file holds there, and a file that is nothing but typing — saved
* by a keystroke and not flushed yet — counts as one. Folders exist while
* something is in them: a file is what makes the project, not a directory.
*/
public static List<EditorFile> loadAll() {
Map<String, String> texts = new LinkedHashMap<>();
Path root = root();
if (Files.isDirectory(root)) {
try (Stream<Path> walk = Files.walk(root)) {
List<Path> paths = walk
.filter(Files::isRegularFile)
.filter(p -> p.getFileName().toString().endsWith(EXTENSION))
.sorted()
.toList();
for (Path path : paths) {
String text = readFromDisk(path);
if (text == null) continue; // unreadable: skip rather than lose the rest
texts.put(nameOf(path), text);
}
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not list the project files in {}", root, e);
}
}
synchronized (PENDING) {
texts.putAll(PENDING);
}
List<EditorFile> files = new ArrayList<>(texts.size());
for (Map.Entry<String, String> entry : texts.entrySet()) {
files.add(new EditorFile(entry.getKey(), entry.getValue()));
}
return files;
}
/**
* The text of the file called {@code name}: what was typed and not written
* yet if there is such a thing, what the disk holds otherwise. Null when
* the project has no such file.
*/
public static String read(String name) {
synchronized (PENDING) {
String pending = PENDING.get(name);
if (pending != null) return pending;
}
Path path = pathOf(name);
if (path == null || !Files.isRegularFile(path)) return null;
return readFromDisk(path);
}
/** Whether the project holds a file called {@code name}, written or not. */
public static boolean exists(String name) {
synchronized (PENDING) {
if (PENDING.containsKey(name)) return true;
}
Path path = pathOf(name);
return path != null && Files.isRegularFile(path);
}
// ── Writing ───────────────────────────────────────────────────────────
/**
* Writes the file right now, saying whether that meant the project gained
* it. For explicit saves and files that must exist the moment they are
* spoken of; typing goes through {@link #scheduleWrite} instead.
*/
public static boolean write(String name, String text) {
return writeNow(name, text);
}
/**
* Records {@code text} for the disk to pick up soon, saying whether that
* meant the project gained the file. One keystroke's worth goes through
* here instead of {@link #write}: the writer thread catches up
* {@value #WRITE_DELAY_MS} after the typing settles, so a burst of keys
* becomes one file write and the server thread never waits on the disk.
*/
public static boolean scheduleWrite(String name, String text) {
Path target = pathOf(name);
if (target == null) {
Codecraft.LOGGER.warn("Refusing to store a project file called {}", name);
return false;
}
boolean brandNew;
boolean schedule;
synchronized (PENDING) {
brandNew = !PENDING.containsKey(name) && !Files.exists(target);
PENDING.put(name, text);
schedule = !flushScheduled;
flushScheduled = true;
}
if (schedule) {
IO.schedule(ProjectStore::flushPending, WRITE_DELAY_MS, TimeUnit.MILLISECONDS);
}
return brandNew;
}
/**
* Moves {@code oldName} to {@code newName} on disk and in the write queue,
* so a renamed file carries its latest text to its new name. A name the
* project already holds is not moved onto; callers refuse it first.
*/
public static void rename(String oldName, String newName) {
Path from = pathOf(oldName);
Path to = pathOf(newName);
if (from == null || to == null) return;
// Whatever is queued belongs to the file, not to its name: get it onto
// disk at the old path before the file changes hands.
String pending;
synchronized (PENDING) {
pending = PENDING.remove(oldName);
}
if (pending != null) writeNow(oldName, pending);
synchronized (DISK_LOCK) {
if (!Files.exists(from)) return; // nothing to move
try {
Path parent = to.getParent();
if (parent != null) Files.createDirectories(parent);
Files.move(from, to, StandardCopyOption.REPLACE_EXISTING);
pruneEmptyParents(from.getParent());
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not rename project file {} to {}", oldName, newName, e);
}
}
}
// ── Internals ─────────────────────────────────────────────────────────
/** Writes everything still queued: called before the server stops. */
private static void flushNow() {
flushPending();
}
private static void flushPending() {
Map<String, String> batch;
synchronized (PENDING) {
flushScheduled = false;
if (PENDING.isEmpty()) return;
batch = Map.copyOf(PENDING);
PENDING.clear();
}
for (Map.Entry<String, String> entry : batch.entrySet()) {
writeNow(entry.getKey(), entry.getValue());
}
}
/** Writes through a temporary file and moves it into place: an editor watching the folder never reads half a script. */
private static boolean writeNow(String name, String text) {
Path target = pathOf(name);
if (target == null) {
Codecraft.LOGGER.warn("Refusing to store a project file called {}", name);
return false;
}
synchronized (DISK_LOCK) {
boolean brandNew = !Files.exists(target);
try {
Path parent = target.getParent();
if (parent != null) Files.createDirectories(parent);
Path temp = target.resolveSibling(target.getFileName() + ".tmp");
Files.writeString(temp, text, StandardCharsets.UTF_8);
try {
Files.move(temp, target, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
} catch (AtomicMoveNotSupportedException e) {
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING);
}
return brandNew;
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not write project file {}", name, e);
return false;
}
}
}
private static String readFromDisk(Path path) {
try {
String text = Files.readString(path, StandardCharsets.UTF_8);
// Editors outside the game may write \r\n; the one in it speaks \n.
if (text.indexOf('\r') >= 0) text = text.replace("\r\n", "\n").replace('\r', '\n');
return text;
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not read project file {}", path, e);
return null;
}
}
/**
* The file {@code name} lives at under the project root, or null when it
* is not a name the store will touch. Names arrive over the network, so
* one that climbs out of the config folder through {@code ..} is refused
* here rather than after it has overwritten something outside it.
*/
private static Path pathOf(String name) {
if (name == null || name.isEmpty()) return null;
Path path = root();
int from = 0;
while (from < name.length()) {
int separator = name.indexOf(ProjectPath.SEPARATOR, from);
String segment = separator < 0 ? name.substring(from) : name.substring(from, separator);
if (!isSafeSegment(segment)) return null;
try {
path = path.resolve(segment);
} catch (InvalidPathException e) {
return null;
}
from = separator < 0 ? name.length() : separator + 1;
}
String fileName = path.getFileName().toString();
return fileName.endsWith(EXTENSION) ? path : path.resolveSibling(fileName + EXTENSION);
}
private static boolean isSafeSegment(String segment) {
if (segment.isEmpty() || segment.equals(".") || segment.equals("..")) return false;
for (int i = 0; i < segment.length(); i++) {
char c = segment.charAt(i);
if (c == '\0' || c == '\\') return false;
}
return true;
}
/** The project's name for a file under the root: the path to it, with no extension. */
private static String nameOf(Path path) {
String relative = root().relativize(path).toString().replace(File.separatorChar, ProjectPath.SEPARATOR);
return relative.endsWith(EXTENSION)
? relative.substring(0, relative.length() - EXTENSION.length())
: relative;
}
/** Removes the folders a rename left empty: in this project a folder exists while something is in it. */
private static void pruneEmptyParents(Path folder) {
Path root = root();
try {
Path current = folder;
while (current != null && current.startsWith(root) && !current.equals(root)) {
try (Stream<Path> children = Files.list(current)) {
if (children.findAny().isPresent()) break;
}
Path parent = current.getParent();
Files.deleteIfExists(current);
current = parent;
}
} catch (IOException e) {
// An empty folder that outlives the rename is a cosmetic problem.
}
}
/**
* The project is one per server now, not one per world save, so a world
* whose scripts still live in its saved data gets them moved into the
* config folder the first time it starts after the update — unless the
* folder already holds a project, which wins. The world keeps its copy
* untouched: what is left behind is a backup.
*/
private static void migrateWorldData(MinecraftServer server) {
if (hasScripts()) return;
List<EditorFile> files = SavedProjectData.getSavedBlockData(server).getEditorFiles();
if (files.isEmpty()) return;
int moved = 0;
for (EditorFile file : files) {
if (write(file.getName(), file.getText())) moved++;
}
Codecraft.LOGGER.info("Migrated {} project file{} from world data to {}",
moved, moved == 1 ? "" : "s", root());
}
private static boolean hasScripts() {
Path root = root();
if (!Files.isDirectory(root)) return false;
try (Stream<Path> walk = Files.walk(root)) {
return walk.anyMatch(p -> Files.isRegularFile(p) && p.getFileName().toString().endsWith(EXTENSION));
} catch (IOException e) {
return true; // cannot tell: leave the world's copy alone
}
}
}

View File

@@ -0,0 +1,155 @@
package com.aranroig.wrapper;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySpawnReason;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.network.chat.Component;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/** Entity queries and basic operations available to a running Lua script. */
public final class EntityApi {
private EntityApi() {
}
public static void register(Lua lua, ServerPlayer owner) {
lua.newTable();
int table = lua.getTop();
lua.push((L, args) -> nearby(L, owner, args)); lua.setField(table, "nearby");
lua.push((L, args) -> spawn(L, owner, args)); lua.setField(table, "spawn");
lua.push((L, args) -> get(L, owner, args)); lua.setField(table, "get");
lua.push((L, args) -> teleport(L, owner, args)); lua.setField(table, "teleport");
lua.push((L, args) -> remove(L, owner, args)); lua.setField(table, "remove");
lua.push((L, args) -> setName(L, owner, args)); lua.setField(table, "set_name");
lua.push((L, args) -> setHealth(L, owner, args)); lua.setField(table, "set_health");
lua.setGlobal("entities");
}
private static LuaValue[] nearby(Lua lua, ServerPlayer owner, LuaValue[] args) {
double radius = args.length > 0 && args[0].type() == Lua.LuaType.NUMBER ? args[0].toNumber() : 16.0;
if (!Double.isFinite(radius) || radius < 0 || radius > 128) return fail(lua, "radius must be between 0 and 128");
String filter = args.length > 1 && args[1].type() == Lua.LuaType.STRING ? normalizeId(args[1].toString()) : null;
if (args.length > 1 && filter == null) return fail(lua, "entity type must be a valid id");
if (filter != null && !BuiltInRegistries.ENTITY_TYPE.containsKey(Identifier.parse(filter))) return fail(lua, "unknown entity type");
double r = radius;
List<String> ids = new ArrayList<>();
for (Entity entity : owner.level().getEntities(owner, owner.getBoundingBox().inflate(r), candidate ->
candidate.distanceToSqr(owner) <= r * r
&& (filter == null || BuiltInRegistries.ENTITY_TYPE.getKey(candidate.getType()).toString().equals(filter)))) {
ids.add(entity.getUUID().toString());
}
return new LuaValue[]{LuaTables.array(lua, ids)};
}
private static LuaValue[] spawn(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 4 || args[0].type() != Lua.LuaType.STRING) {
return fail(lua, "usage: entities.spawn(type, x, y, z)");
}
Identifier id = identifier(args[0].toString());
Double x = decimal(args[1]), y = decimal(args[2]), z = decimal(args[3]);
if (id == null || !BuiltInRegistries.ENTITY_TYPE.containsKey(id)) return fail(lua, "unknown entity type");
if (x == null || y == null || z == null) return fail(lua, "x, y and z must be numbers");
if (Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000 || y < owner.level().getMinY() || y >= owner.level().getMaxY()) {
return fail(lua, "position is outside the world bounds");
}
EntityType<?> type = BuiltInRegistries.ENTITY_TYPE.getOptional(id).orElse(null);
if (type == null) return fail(lua, "unknown entity type");
if (!type.canSummon()) return fail(lua, "that entity type cannot be summoned");
Entity entity = type.create(owner.level(), EntitySpawnReason.COMMAND);
if (entity == null || entity instanceof ServerPlayer) return fail(lua, "could not create that entity");
entity.setPos(x, y, z);
entity.setYRot(owner.getYRot());
if (!owner.level().addFreshEntity(entity)) return fail(lua, "the entity could not be added to the world");
return new LuaValue[]{lua.from(entity.getUUID().toString())};
}
private static LuaValue[] get(Lua lua, ServerPlayer owner, LuaValue[] args) {
Entity entity = entity(owner, args);
if (entity == null) return new LuaValue[]{lua.fromNull(), lua.from("entity not found")};
return new LuaValue[]{lua.from(BuiltInRegistries.ENTITY_TYPE.getKey(entity.getType()).toString()),
lua.from(entity.getX()), lua.from(entity.getY()), lua.from(entity.getZ()),
lua.from(entity.getName().getString())};
}
private static LuaValue[] teleport(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 4) return fail(lua, "usage: entities.teleport(uuid, x, y, z)");
Entity entity = entity(owner, args);
if (entity == null) return fail(lua, "entity not found");
Double x = decimal(args[1]), y = decimal(args[2]), z = decimal(args[3]);
if (x == null || y == null || z == null) return fail(lua, "x, y and z must be numbers");
if (Math.abs(x) > 30_000_000 || Math.abs(z) > 30_000_000 || y < entity.level().getMinY() || y >= entity.level().getMaxY()) {
return fail(lua, "position is outside the world bounds");
}
entity.teleportTo(x, y, z);
return success(lua);
}
private static LuaValue[] remove(Lua lua, ServerPlayer owner, LuaValue[] args) {
Entity entity = entity(owner, args);
if (entity == null) return fail(lua, "entity not found");
if (entity instanceof ServerPlayer) return fail(lua, "players cannot be removed");
entity.discard();
return success(lua);
}
private static LuaValue[] setName(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 2 || args[1].type() != Lua.LuaType.STRING) return fail(lua, "usage: entities.set_name(uuid, name)");
Entity entity = entity(owner, args);
if (entity == null) return fail(lua, "entity not found");
entity.setCustomName(Component.literal(args[1].toString()));
entity.setCustomNameVisible(true);
return success(lua);
}
private static LuaValue[] setHealth(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 2) return fail(lua, "usage: entities.set_health(uuid, health)");
Entity entity = entity(owner, args);
if (!(entity instanceof LivingEntity living)) return fail(lua, "living entity not found");
Double health = decimal(args[1]);
if (health == null || health < 0 || health > living.getMaxHealth()) return fail(lua, "health must be between 0 and max health");
living.setHealth(health.floatValue());
return success(lua);
}
private static Entity entity(ServerPlayer owner, LuaValue[] args) {
if (args.length == 0 || args[0].type() != Lua.LuaType.STRING) return null;
try {
UUID uuid = UUID.fromString(args[0].toString());
for (ServerLevel level : owner.level().getServer().getAllLevels()) {
Entity entity = level.getEntityInAnyDimension(uuid);
if (entity != null) return entity;
}
return null;
} catch (IllegalArgumentException e) {
return null;
}
}
private static Identifier identifier(String input) {
return Identifier.tryParse(input.indexOf(':') < 0 ? "minecraft:" + input : input);
}
private static String normalizeId(String input) {
Identifier id = identifier(input);
return id == null ? null : id.toString();
}
private static Double decimal(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
double number = value.toNumber();
return Double.isFinite(number) ? number : null;
}
private static LuaValue[] success(Lua lua) { return new LuaValue[]{lua.from(true)}; }
private static LuaValue[] fail(Lua lua, String reason) { return new LuaValue[]{lua.from(false), lua.from(reason)}; }
}

View File

@@ -0,0 +1,141 @@
package com.aranroig.wrapper;
import net.minecraft.network.chat.Component;
import net.minecraft.network.protocol.game.ClientboundClearTitlesPacket;
import net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetSubtitleTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetTitleTextPacket;
import net.minecraft.network.protocol.game.ClientboundSetTitlesAnimationPacket;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.resources.Identifier;
import net.minecraft.server.bossevents.CustomBossEvent;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
/** Title, action-bar and boss-bar feedback for online players. */
public final class HudApi {
private HudApi() {
}
public static void register(Lua lua, ServerPlayer owner) {
lua.newTable();
int table = lua.getTop();
lua.push((L, args) -> text(L, owner, args, "title")); lua.setField(table, "title");
lua.push((L, args) -> text(L, owner, args, "subtitle")); lua.setField(table, "subtitle");
lua.push((L, args) -> text(L, owner, args, "action_bar")); lua.setField(table, "action_bar");
lua.push((L, args) -> times(L, owner, args)); lua.setField(table, "title_times");
lua.push((L, args) -> clear(L, owner, args)); lua.setField(table, "clear_titles");
lua.push((L, args) -> bossbar(L, owner, args, "add")); lua.setField(table, "bossbar_add");
lua.push((L, args) -> bossbar(L, owner, args, "remove")); lua.setField(table, "bossbar_remove");
lua.push((L, args) -> bossbar(L, owner, args, "value")); lua.setField(table, "bossbar_value");
lua.push((L, args) -> bossbar(L, owner, args, "max")); lua.setField(table, "bossbar_max");
lua.push((L, args) -> bossbar(L, owner, args, "visible")); lua.setField(table, "bossbar_visible");
lua.setGlobal("hud");
}
private static LuaValue[] text(Lua lua, ServerPlayer owner, LuaValue[] args, String kind) {
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) return fail(lua, "usage: hud." + kind + "(text [, player])");
ServerPlayer target = player(owner, args, 1);
if (target == null) return fail(lua, "player is not online");
Component text = Component.literal(args[0].toString());
switch (kind) {
case "title" -> target.connection.send(new ClientboundSetTitleTextPacket(text));
case "subtitle" -> target.connection.send(new ClientboundSetSubtitleTextPacket(text));
case "action_bar" -> target.connection.send(new ClientboundSetActionBarTextPacket(text));
}
return success(lua);
}
private static LuaValue[] times(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 3) return fail(lua, "usage: hud.title_times(fade_in, stay, fade_out [, player])");
Integer fadeIn = integer(args[0]), stay = integer(args[1]), fadeOut = integer(args[2]);
if (fadeIn == null || stay == null || fadeOut == null || fadeIn < 0 || stay < 0 || fadeOut < 0) {
return fail(lua, "title times must be non-negative whole numbers of ticks");
}
ServerPlayer target = player(owner, args, 3);
if (target == null) return fail(lua, "player is not online");
target.connection.send(new ClientboundSetTitlesAnimationPacket(fadeIn, stay, fadeOut));
return success(lua);
}
private static LuaValue[] clear(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length > 0 && args[0].type() != Lua.LuaType.NIL && args[0].type() != Lua.LuaType.BOOLEAN) return fail(lua, "reset must be true or false");
boolean reset = args.length > 0 && args[0].type() == Lua.LuaType.BOOLEAN && args[0].toBoolean();
ServerPlayer target = player(owner, args, 1);
if (target == null) return fail(lua, "player is not online");
target.connection.send(new ClientboundClearTitlesPacket(reset));
return success(lua);
}
private static LuaValue[] bossbar(Lua lua, ServerPlayer owner, LuaValue[] args, String operation) {
String usage = switch (operation) {
case "add" -> "hud.bossbar_add(id, name [, max [, player]])";
case "remove" -> "hud.bossbar_remove(id)";
case "value", "max" -> "hud.bossbar_" + operation + "(id, value)";
default -> "hud.bossbar_visible(id, visible [, player])";
};
if (args.length < (operation.equals("remove") ? 1 : 2) || args[0].type() != Lua.LuaType.STRING) return fail(lua, "usage: " + usage);
Identifier id = Identifier.tryParse(args[0].toString().indexOf(':') < 0 ? "codecraft:" + args[0] : args[0].toString());
if (id == null) return fail(lua, "boss bar id must be a valid resource id");
var bossbars = owner.level().getServer().getCustomBossEvents();
CustomBossEvent event = bossbars.get(id);
switch (operation) {
case "add" -> {
if (args[1].type() != Lua.LuaType.STRING) return fail(lua, "boss bar name must be a string");
if (args.length > 2 && args[2].type() != Lua.LuaType.NIL && args[2].type() != Lua.LuaType.NUMBER) return fail(lua, "max must be a number");
int max = args.length > 2 && args[2].type() != Lua.LuaType.NIL ? safeInteger(args[2]) : 100;
if (max < 1 || max > 1_000_000) return fail(lua, "boss bar max must be between 1 and 1000000");
if (event != null) return fail(lua, "boss bar already exists");
ServerPlayer target = player(owner, args, 3);
if (target == null) return fail(lua, "player is not online");
event = bossbars.create(owner.getRandom(), id, Component.literal(args[1].toString()));
event.setMax(max);
event.addPlayer(target);
return success(lua);
}
case "remove" -> {
if (event == null) return fail(lua, "boss bar not found");
bossbars.remove(event);
return success(lua);
}
case "value", "max" -> {
if (event == null) return fail(lua, "boss bar not found");
int value = safeInteger(args[1]);
if (value < 0 || value > 1_000_000) return fail(lua, "boss bar value must be between 0 and 1000000");
if (operation.equals("value")) {
if (value > event.max()) return fail(lua, "boss bar value cannot exceed its max");
event.setValue(value);
} else {
if (value < 1) return fail(lua, "boss bar max must be at least 1");
event.setMax(value);
if (event.value() > value) event.setValue(value);
}
return success(lua);
}
case "visible" -> {
if (args[1].type() != Lua.LuaType.BOOLEAN) return fail(lua, "visible must be true or false");
if (event == null) return fail(lua, "boss bar not found");
ServerPlayer target = player(owner, args, 2);
if (target == null) return fail(lua, "player is not online");
if (args[1].toBoolean()) event.addPlayer(target); else event.removePlayer(target);
return success(lua);
}
default -> { return fail(lua, "unknown boss bar operation"); }
}
}
private static Integer integer(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
long number = value.toInteger();
return number < Integer.MIN_VALUE || number > Integer.MAX_VALUE ? null : (int) number;
}
private static ServerPlayer player(ServerPlayer owner, LuaValue[] args, int index) {
if (args.length <= index || args[index].type() == Lua.LuaType.NIL) return owner;
if (args[index].type() != Lua.LuaType.STRING) return null;
return owner.level().getServer().getPlayerList().getPlayerByName(args[index].toString());
}
private static int safeInteger(LuaValue value) { Integer n = integer(value); return n == null ? -1 : n; }
private static LuaValue[] success(Lua lua) { return new LuaValue[]{lua.from(true)}; }
private static LuaValue[] fail(Lua lua, String reason) { return new LuaValue[]{lua.from(false), lua.from(reason)}; }
}

View File

@@ -0,0 +1,133 @@
package com.aranroig.wrapper;
import net.minecraft.core.NonNullList;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.resources.Identifier;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.Items;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
/** Item registry and online player inventory helpers. */
public final class ItemApi {
private ItemApi() {
}
public static void register(Lua lua, ServerPlayer owner) {
lua.newTable();
int table = lua.getTop();
lua.push((L, args) -> give(L, owner, args)); lua.setField(table, "give");
lua.push((L, args) -> count(L, owner, args)); lua.setField(table, "count");
lua.push((L, args) -> clear(L, owner, args)); lua.setField(table, "clear");
lua.push((L, args) -> getSlot(L, owner, args)); lua.setField(table, "get_slot");
lua.push((L, args) -> setSlot(L, owner, args)); lua.setField(table, "set_slot");
lua.setGlobal("items");
}
private static LuaValue[] give(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 2 || !string(args[0])) return fail(lua, "usage: items.give(item, count [, player])");
Item item = item(args[0].toString());
Integer count = integer(args[1]);
ServerPlayer target = player(owner, args, 2);
if (item == null) return fail(lua, "unknown item id");
if (count == null || count < 1 || count > 2304) return fail(lua, "count must be between 1 and 2304");
if (target == null) return fail(lua, "player is not online");
ItemStack stack = new ItemStack(item, count);
target.getInventory().add(stack);
if (!stack.isEmpty()) target.drop(stack, false);
target.containerMenu.broadcastChanges();
return success(lua);
}
private static LuaValue[] count(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: items.count(item [, player])");
Item item = item(args[0].toString());
ServerPlayer target = player(owner, args, 1);
if (item == null) return fail(lua, "unknown item id");
if (target == null) return fail(lua, "player is not online");
int total = 0;
Inventory inventory = target.getInventory();
for (ItemStack stack : inventory.getNonEquipmentItems()) {
if (!stack.isEmpty() && stack.getItem() == item) total += stack.getCount();
}
return new LuaValue[]{lua.from((long) total)};
}
private static LuaValue[] clear(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: items.clear(item [, player])");
Item item = item(args[0].toString());
ServerPlayer target = player(owner, args, 1);
if (item == null) return fail(lua, "unknown item id");
if (target == null) return fail(lua, "player is not online");
int removed = 0;
Inventory inventory = target.getInventory();
for (ItemStack stack : inventory.getNonEquipmentItems()) {
if (!stack.isEmpty() && stack.getItem() == item) {
removed += stack.getCount();
stack.setCount(0);
}
}
inventory.setChanged();
target.containerMenu.broadcastChanges();
return new LuaValue[]{lua.from(true), lua.from((long) removed)};
}
private static LuaValue[] getSlot(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 1) return fail(lua, "usage: items.get_slot(slot [, player])");
Integer slot = integer(args[0]);
ServerPlayer target = player(owner, args, 1);
if (slot == null || slot < 0 || slot >= 36) return fail(lua, "slot must be between 0 and 35");
if (target == null) return fail(lua, "player is not online");
ItemStack stack = target.getInventory().getNonEquipmentItems().get(slot);
if (stack.isEmpty()) return new LuaValue[]{lua.fromNull()};
return new LuaValue[]{lua.from(BuiltInRegistries.ITEM.getKey(stack.getItem()).toString()), lua.from((long) stack.getCount())};
}
private static LuaValue[] setSlot(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 3 || !string(args[1])) return fail(lua, "usage: items.set_slot(slot, item, count [, player])");
Integer slot = integer(args[0]), count = integer(args[2]);
ServerPlayer target = player(owner, args, 3);
if (slot == null || slot < 0 || slot >= 36) return fail(lua, "slot must be between 0 and 35");
if (count == null || count < 0 || count > 99) return fail(lua, "count must be between 0 and 99");
if (target == null) return fail(lua, "player is not online");
Inventory inventory = target.getInventory();
NonNullList<ItemStack> slots = inventory.getNonEquipmentItems();
if (count == 0) {
slots.set(slot, ItemStack.EMPTY);
} else {
Item item = item(args[1].toString());
if (item == null) return fail(lua, "unknown item id");
if (count > item.getDefaultMaxStackSize()) {
return fail(lua, "count exceeds this item's stack size");
}
slots.set(slot, new ItemStack(item, count));
}
inventory.setChanged();
target.containerMenu.broadcastChanges();
return success(lua);
}
private static ServerPlayer player(ServerPlayer owner, LuaValue[] args, int index) {
if (args.length <= index || args[index].type() == Lua.LuaType.NIL) return owner;
if (!string(args[index])) return null;
return owner.level().getServer().getPlayerList().getPlayerByName(args[index].toString());
}
private static Item item(String input) {
Identifier id = Identifier.tryParse(input.indexOf(':') < 0 ? "minecraft:" + input : input);
Item item = id == null ? null : BuiltInRegistries.ITEM.getOptional(id).orElse(null);
return item == Items.AIR ? null : item;
}
private static Integer integer(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
long number = value.toInteger();
return number < Integer.MIN_VALUE || number > Integer.MAX_VALUE ? null : (int) number;
}
private static boolean string(LuaValue value) { return value != null && value.type() == Lua.LuaType.STRING; }
private static LuaValue[] success(Lua lua) { return new LuaValue[]{lua.from(true)}; }
private static LuaValue[] fail(Lua lua, String reason) { return new LuaValue[]{lua.from(false), lua.from(reason)}; }
}

View File

@@ -0,0 +1,23 @@
package com.aranroig.wrapper;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaTableValue;
import party.iroiro.luajava.value.LuaValue;
import java.util.Collection;
/** Small helpers for returning ordinary Lua tables from Java callbacks. */
final class LuaTables {
private LuaTables() {
}
static LuaValue array(Lua lua, Collection<?> values) {
lua.newTable();
LuaTableValue table = new LuaTableValue(lua, Lua.LuaType.TABLE);
int index = 1;
for (Object value : values) {
table.set(index++, value);
}
return table;
}
}

View File

@@ -0,0 +1,124 @@
package com.aranroig.wrapper;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.scores.DisplaySlot;
import net.minecraft.world.scores.Objective;
import net.minecraft.world.scores.ScoreHolder;
import net.minecraft.world.scores.criteria.ObjectiveCriteria;
import net.minecraft.world.scores.criteria.ObjectiveCriteria.RenderType;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
import java.util.Locale;
import java.util.regex.Pattern;
/** Objective and score operations for the server scoreboard. */
public final class ScoreboardApi {
private static final Pattern OBJECTIVE_NAME = Pattern.compile("[A-Za-z0-9_.+-]{1,16}");
private ScoreboardApi() {
}
public static void register(Lua lua, ServerPlayer owner) {
lua.newTable();
int table = lua.getTop();
lua.push((L, args) -> create(L, owner, args)); lua.setField(table, "create_objective");
lua.push((L, args) -> remove(L, owner, args)); lua.setField(table, "remove_objective");
lua.push((L, args) -> set(L, owner, args, false)); lua.setField(table, "set");
lua.push((L, args) -> set(L, owner, args, true)); lua.setField(table, "add");
lua.push((L, args) -> get(L, owner, args)); lua.setField(table, "get");
lua.push((L, args) -> reset(L, owner, args)); lua.setField(table, "reset");
lua.push((L, args) -> display(L, owner, args)); lua.setField(table, "display");
lua.setGlobal("scoreboard");
}
private static LuaValue[] create(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: scoreboard.create_objective(name [, criterion [, display_name]])");
String name = args[0].toString();
if (!OBJECTIVE_NAME.matcher(name).matches()) return fail(lua, "objective name must be 1 to 16 letters, numbers, dots, underscores, pluses or hyphens");
var scoreboard = owner.level().getServer().getScoreboard();
if (scoreboard.getObjective(name) != null) return fail(lua, "objective already exists");
if (args.length > 1 && !string(args[1])) return fail(lua, "criterion must be a string");
if (args.length > 2 && !string(args[2])) return fail(lua, "display name must be a string");
String criterionName = args.length > 1 && string(args[1]) ? args[1].toString() : "dummy";
ObjectiveCriteria criteria = ObjectiveCriteria.byName(criterionName).orElse(null);
if (criteria == null) return fail(lua, "unknown scoreboard criterion");
String display = args.length > 2 && string(args[2]) ? args[2].toString() : name;
scoreboard.addObjective(name, criteria, Component.literal(display), criteria.getDefaultRenderType(), false, null);
return success(lua);
}
private static LuaValue[] remove(Lua lua, ServerPlayer owner, LuaValue[] args) {
Objective objective = objective(owner, args);
if (objective == null) return fail(lua, "objective not found");
owner.level().getServer().getScoreboard().removeObjective(objective);
return success(lua);
}
private static LuaValue[] set(Lua lua, ServerPlayer owner, LuaValue[] args, boolean add) {
if (args.length < 3 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard." + (add ? "add" : "set") + "(player, objective, value)");
Integer value = integer(args[2]);
if (value == null) return fail(lua, "score must be an integer");
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[1].toString());
if (objective == null) return fail(lua, "objective not found");
var score = owner.level().getServer().getScoreboard().getOrCreatePlayerScore(ScoreHolder.forNameOnly(args[0].toString()), objective);
if (add) score.add(value); else score.set(value);
return success(lua);
}
private static LuaValue[] get(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 2 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard.get(player, objective)");
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[1].toString());
if (objective == null) return new LuaValue[]{lua.fromNull(), lua.from("objective not found")};
var score = owner.level().getServer().getScoreboard().getPlayerScoreInfo(ScoreHolder.forNameOnly(args[0].toString()), objective);
return score == null ? new LuaValue[]{lua.fromNull()} : new LuaValue[]{lua.from((long) score.value())};
}
private static LuaValue[] reset(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 1 || !string(args[0])) return fail(lua, "usage: scoreboard.reset(player [, objective])");
var scoreboard = owner.level().getServer().getScoreboard();
ScoreHolder player = ScoreHolder.forNameOnly(args[0].toString());
if (args.length < 2 || args[1].type() == Lua.LuaType.NIL) {
scoreboard.resetAllPlayerScores(player);
return success(lua);
}
if (!string(args[1])) return fail(lua, "objective must be a string");
Objective objective = scoreboard.getObjective(args[1].toString());
if (objective == null) return fail(lua, "objective not found");
scoreboard.resetSinglePlayerScore(player, objective);
return success(lua);
}
private static LuaValue[] display(Lua lua, ServerPlayer owner, LuaValue[] args) {
if (args.length < 2 || !string(args[0]) || !string(args[1])) return fail(lua, "usage: scoreboard.display(objective, slot)");
Objective objective = owner.level().getServer().getScoreboard().getObjective(args[0].toString());
if (objective == null) return fail(lua, "objective not found");
DisplaySlot slot = slot(args[1].toString());
if (slot == null) return fail(lua, "slot must be list, sidebar, or below_name");
owner.level().getServer().getScoreboard().setDisplayObjective(slot, objective);
return success(lua);
}
private static Objective objective(ServerPlayer owner, LuaValue[] args) {
return args.length > 0 && string(args[0]) ? owner.level().getServer().getScoreboard().getObjective(args[0].toString()) : null;
}
private static DisplaySlot slot(String raw) {
return switch (raw.toLowerCase(Locale.ROOT)) {
case "list" -> DisplaySlot.LIST;
case "sidebar" -> DisplaySlot.SIDEBAR;
case "below_name" -> DisplaySlot.BELOW_NAME;
default -> null;
};
}
private static boolean string(LuaValue value) { return value != null && value.type() == Lua.LuaType.STRING; }
private static Integer integer(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) return null;
long n = value.toInteger();
return n < Integer.MIN_VALUE || n > Integer.MAX_VALUE ? null : (int) n;
}
private static LuaValue[] success(Lua lua) { return new LuaValue[]{lua.from(true)}; }
private static LuaValue[] fail(Lua lua, String reason) { return new LuaValue[]{lua.from(false), lua.from(reason)}; }
}

View File

@@ -0,0 +1,46 @@
package com.aranroig.wrapper;
import net.minecraft.server.level.ServerPlayer;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
/**
* Registers the server command helper exposed to Lua scripts.
* Commands use the server source (without a player or position), including its
* full command permissions.
*/
public final class ServerCommandApi {
private ServerCommandApi() {
}
/** Registers the global {@code run(command)} function. */
public static void register(Lua lua, ServerPlayer player) {
lua.push((L, args) -> execute(L, player, args));
lua.setGlobal("run");
}
private static LuaValue[] execute(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) {
return fail(lua, "usage: run(\"command\")");
}
String command = args[0].toString().trim();
if (command.isEmpty()) {
return fail(lua, "command cannot be empty");
}
runCommand(player, command);
return new LuaValue[]{ lua.from(true) };
}
/** Executes a command from the server source for wrapper APIs that need a vanilla command. */
static void runCommand(ServerPlayer player, String command) {
var server = player.level().getServer();
server.getCommands().performPrefixedCommand(server.createCommandSourceStack(), command);
}
private static LuaValue[] fail(Lua lua, String reason) {
return new LuaValue[]{ lua.from(false), lua.from(reason) };
}
}

View File

@@ -12,8 +12,10 @@ import net.minecraft.world.level.block.state.BlockState;
import party.iroiro.luajava.Lua; import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue; import party.iroiro.luajava.value.LuaValue;
import java.util.ArrayList;
/** /**
* The {@code world} table given to user scripts: placing, removing and reading blocks. * The {@code world} table given to user scripts: block access and basic world state.
* *
* <p>Coordinates are absolute world coordinates in the dimension the executing player * <p>Coordinates are absolute world coordinates in the dimension the executing player
* stands in. They are not limited by the player's reach, so a script can edit any block * stands in. They are not limited by the player's reach, so a script can edit any block
@@ -50,6 +52,27 @@ public class WorldApi {
lua.push((L, args) -> getBlock(L, player, args)); lua.push((L, args) -> getBlock(L, player, args));
lua.setField(world, "get_block"); lua.setField(world, "get_block");
lua.push((L, args) -> getDimension(L, player, args));
lua.setField(world, "get_dimension");
lua.push((L, args) -> getTime(L, player, args));
lua.setField(world, "get_time");
lua.push((L, args) -> setTime(L, player, args));
lua.setField(world, "set_time");
lua.push((L, args) -> getWeather(L, player, args));
lua.setField(world, "get_weather");
lua.push((L, args) -> setWeather(L, player, args));
lua.setField(world, "set_weather");
lua.push((L, args) -> getBiome(L, player, args));
lua.setField(world, "get_biome");
lua.push((L, args) -> players(L, player, args));
lua.setField(world, "players");
lua.setGlobal("world"); lua.setGlobal("world");
} }
@@ -161,6 +184,59 @@ public class WorldApi {
return new LuaValue[]{ lua.from(BlockStateParser.serialize(level.getBlockState(pos))) }; return new LuaValue[]{ lua.from(BlockStateParser.serialize(level.getBlockState(pos))) };
} }
private static LuaValue[] getDimension(Lua lua, ServerPlayer player, LuaValue[] args) {
return new LuaValue[]{lua.from(player.level().dimension().identifier().toString())};
}
private static LuaValue[] getTime(Lua lua, ServerPlayer player, LuaValue[] args) {
return new LuaValue[]{lua.from(player.level().getOverworldClockTime())};
}
private static LuaValue[] setTime(Lua lua, ServerPlayer player, LuaValue[] args) {
long ticks = args.length > 0 ? longNumber(args[0]) : -1;
if (ticks < 0 || ticks > Integer.MAX_VALUE) {
return fail(lua, "ticks must be between 0 and 2147483647");
}
ServerCommandApi.runCommand(player, "time set " + ticks);
return success(lua);
}
private static LuaValue[] getWeather(Lua lua, ServerPlayer player, LuaValue[] args) {
String weather = player.level().isThundering() ? "thunder" : player.level().isRaining() ? "rain" : "clear";
return new LuaValue[]{lua.from(weather)};
}
private static LuaValue[] setWeather(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 1 || args[0].type() != Lua.LuaType.STRING) {
return fail(lua, "usage: world.set_weather(\"clear\" | \"rain\" | \"thunder\" [, duration])");
}
String weather = args[0].toString();
if (!weather.equals("clear") && !weather.equals("rain") && !weather.equals("thunder")) {
return fail(lua, "weather must be clear, rain or thunder");
}
long duration = args.length > 1 ? longNumber(args[1]) : 6000L;
if (duration < 1 || duration > 1_000_000_000L) return fail(lua, "duration must be between 1 and 1000000000 ticks");
ServerCommandApi.runCommand(player, "weather " + weather + " " + duration);
return success(lua);
}
private static LuaValue[] getBiome(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 3) return missing(lua, "usage: world.get_biome(x, y, z)");
BlockPos pos = position(args);
if (pos == null) return missing(lua, "x, y and z must be numbers");
ServerLevel level = player.level();
String problem = blockProblem(level, pos);
if (problem != null) return missing(lua, problem);
String biome = level.getBiome(pos).unwrapKey().map(key -> key.identifier().toString()).orElse("unknown");
return new LuaValue[]{lua.from(biome)};
}
private static LuaValue[] players(Lua lua, ServerPlayer player, LuaValue[] args) {
ArrayList<String> names = new ArrayList<>();
player.level().getServer().getPlayerList().getPlayers().forEach(serverPlayer -> names.add(serverPlayer.getScoreboardName()));
return new LuaValue[]{LuaTables.array(lua, names)};
}
/** /**
* Reads {@code x}, {@code y} and {@code z} from the first three arguments. * Reads {@code x}, {@code y} and {@code z} from the first three arguments.
* *
@@ -188,6 +264,12 @@ public class WorldApi {
} }
} }
private static long longNumber(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) return -1;
long n = value.toInteger();
return n;
}
/** /**
* Precondition shared by the three functions. * Precondition shared by the three functions.
* *

View File

@@ -0,0 +1,6 @@
accessWidener v2 official
# The editor builds its own monospace Font (see EditorFonts): it needs to
# read vanilla's default glyph set (minecraft:default) off the FontManager.
accessible field net/minecraft/client/Minecraft fontManager Lnet/minecraft/client/gui/font/FontManager;
accessible method net/minecraft/client/gui/font/FontManager getFontSetRaw (Lnet/minecraft/resources/Identifier;)Lnet/minecraft/client/gui/font/FontSet;

View File

@@ -2,7 +2,7 @@
"topics": [ "topics": [
{ {
"title": "world", "title": "world",
"blurb": "Read and write blocks in the running player's dimension.", "blurb": "Read and write blocks, inspect world state, and change time or weather in the executing player’s dimension.",
"functions": [ "functions": [
{ {
"name": "world.set_block", "name": "world.set_block",
@@ -132,6 +132,303 @@
"code": "local block = world.get_block(10, 64, -3)\nif block then\n world.set_block(20, 70, 5, block)\nend" "code": "local block = world.get_block(10, 64, -3)\nif block then\n world.set_block(20, 70, 5, block)\nend"
} }
] ]
},
{
"name": "world.get_dimension",
"signature": "world.get_dimension()",
"summary": "Returns the current dimension id, such as minecraft:overworld.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.get_time",
"signature": "world.get_time()",
"summary": "Returns the current world clock time in ticks.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.set_time",
"signature": "world.set_time(ticks)",
"summary": "Sets the world clock to the given tick value.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.get_weather",
"signature": "world.get_weather()",
"summary": "Returns clear, rain or thunder.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.set_weather",
"signature": "world.set_weather(weather [, duration])",
"summary": "Sets weather to clear, rain or thunder for the given number of ticks (default 6000).",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.get_biome",
"signature": "world.get_biome(x, y, z)",
"summary": "Returns the biome id at the given loaded position.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
},
{
"name": "world.players",
"signature": "world.players()",
"summary": "Returns a Lua array of online player names.",
"params": [],
"returns": "A value on success, or false/nil followed by a reason when the call fails.",
"notes": [
"Coordinates are absolute world coordinates."
]
}
]
},
{
"title": "entities",
"blurb": "Find, spawn and manipulate entities in the executing player’s current dimension.",
"functions": [
{
"name": "entities.nearby",
"signature": "entities.nearby([radius [, type]])",
"summary": "Returns a Lua array of UUID strings for loaded entities near the script owner (default radius 16, maximum 128).",
"params": [],
"returns": "A UUID array, or false followed by a reason."
},
{
"name": "entities.spawn",
"signature": "entities.spawn(type, x, y, z)",
"summary": "Spawns a summonable entity at an absolute position and returns its UUID.",
"params": [],
"returns": "The new entity UUID, or false followed by a reason."
},
{
"name": "entities.get",
"signature": "entities.get(uuid)",
"summary": "Looks up an entity and returns type id, x, y, z and its displayed name.",
"params": [],
"returns": "Five values, or nil followed by a reason."
},
{
"name": "entities.teleport",
"signature": "entities.teleport(uuid, x, y, z)",
"summary": "Moves an entity to an absolute position in its current dimension.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "entities.remove",
"signature": "entities.remove(uuid)",
"summary": "Removes an entity. Players cannot be removed.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "entities.set_name",
"signature": "entities.set_name(uuid, name)",
"summary": "Sets a visible custom name on an entity.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "entities.set_health",
"signature": "entities.set_health(uuid, health)",
"summary": "Sets a living entity’s health, from zero to its maximum health.",
"params": [],
"returns": "true, or false followed by a reason."
}
]
},
{
"title": "scoreboard",
"blurb": "Create scoreboard objectives and change or display player scores.",
"functions": [
{
"name": "scoreboard.create_objective",
"signature": "scoreboard.create_objective(name [, criterion [, display_name]])",
"summary": "Creates an objective. The criterion defaults to dummy.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "scoreboard.remove_objective",
"signature": "scoreboard.remove_objective(name)",
"summary": "Removes an objective and its scores.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "scoreboard.set",
"signature": "scoreboard.set(player, objective, value)",
"summary": "Sets a player’s integer score.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "scoreboard.add",
"signature": "scoreboard.add(player, objective, value)",
"summary": "Adds an integer to a player’s score.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "scoreboard.get",
"signature": "scoreboard.get(player, objective)",
"summary": "Reads a player’s score.",
"params": [],
"returns": "The integer score, or nil if no score exists."
},
{
"name": "scoreboard.reset",
"signature": "scoreboard.reset(player [, objective])",
"summary": "Clears one objective score or all scores for a player.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "scoreboard.display",
"signature": "scoreboard.display(objective, slot)",
"summary": "Displays an objective in list, sidebar or below_name.",
"params": [],
"returns": "true, or false followed by a reason."
}
]
},
{
"title": "hud",
"blurb": "Show titles, subtitles, action-bar messages and boss bars to the player running the script.",
"functions": [
{
"name": "hud.title",
"signature": "hud.title(text [, player])",
"summary": "Shows a large title to the named online player, or to the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.subtitle",
"signature": "hud.subtitle(text [, player])",
"summary": "Shows a subtitle to the named online player, or to the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.action_bar",
"signature": "hud.action_bar(text [, player])",
"summary": "Shows an action-bar message to the named online player, or to the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.title_times",
"signature": "hud.title_times(fade_in, stay, fade_out [, player])",
"summary": "Sets title timing in ticks for the named online player, or the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.clear_titles",
"signature": "hud.clear_titles([reset [, player]])",
"summary": "Clears the named online player’s title and subtitle, or the script owner’s by default.",
"params": [],
"returns": "true."
},
{
"name": "hud.bossbar_add",
"signature": "hud.bossbar_add(id, name [, max [, player]])",
"summary": "Creates a boss bar and shows it to the named online player, or to the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.bossbar_remove",
"signature": "hud.bossbar_remove(id)",
"summary": "Removes a boss bar.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.bossbar_value",
"signature": "hud.bossbar_value(id, value)",
"summary": "Sets a boss bar’s current value.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.bossbar_max",
"signature": "hud.bossbar_max(id, value)",
"summary": "Sets a boss bar’s maximum value.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "hud.bossbar_visible",
"signature": "hud.bossbar_visible(id, visible [, player])",
"summary": "Shows or hides a boss bar for the named online player, or the script owner by default.",
"params": [],
"returns": "true, or false followed by a reason."
}
]
},
{
"title": "items",
"blurb": "Give, count, clear and edit the main inventory of an online player.",
"functions": [
{
"name": "items.give",
"signature": "items.give(item, count [, player])",
"summary": "Gives items to the named online player, or to the script owner by default. Overflow drops at the player.",
"params": [],
"returns": "true, or false followed by a reason."
},
{
"name": "items.count",
"signature": "items.count(item [, player])",
"summary": "Counts matching items in the player’s main inventory.",
"params": [],
"returns": "An integer count, or false followed by a reason."
},
{
"name": "items.clear",
"signature": "items.clear(item [, player])",
"summary": "Removes matching items from the player’s main inventory.",
"params": [],
"returns": "true and the number removed, or false followed by a reason."
},
{
"name": "items.get_slot",
"signature": "items.get_slot(slot [, player])",
"summary": "Reads a main inventory slot from 0 through 35.",
"params": [],
"returns": "Item id and count, nil if empty, or false followed by a reason."
},
{
"name": "items.set_slot",
"signature": "items.set_slot(slot, item, count [, player])",
"summary": "Replaces a main inventory slot. A count of zero clears the slot.",
"params": [],
"returns": "true, or false followed by a reason."
} }
] ]
}, },
@@ -291,6 +588,41 @@
} }
] ]
}, },
{
"title": "run",
"blurb": "Run a Minecraft command with the server command source.",
"functions": [
{
"name": "run",
"signature": "run(command)",
"summary": "Runs a Minecraft command as the server.",
"params": [
{
"name": "command",
"type": "string",
"optional": false,
"description": "Minecraft command to execute, with or without a leading slash."
}
],
"returns": "true if submitted, or false followed by a reason if the input is invalid.",
"notes": [
"Commands run with the server command source's full permissions.",
"Commands have no player position or entity, because they run from the server command source.",
"A true return means the command was submitted, not that it succeeded."
],
"examples": [
{
"title": "Change the time",
"code": "run(\"time set day\")"
},
{
"title": "Validate the argument",
"code": "local ok, reason = run(42)\nif not ok then\n print(reason)\nend"
}
]
}
]
},
{ {
"title": "print", "title": "print",
"blurb": "Send text to the chat of the player running the script.", "blurb": "Send text to the chat of the player running the script.",

View File

@@ -32,6 +32,7 @@
"environment": "client" "environment": "client"
} }
], ],
"access_widener": "codecraft.accesswidener",
"depends": { "depends": {
"fabricloader": ">=0.19.3", "fabricloader": ">=0.19.3",
"minecraft": "~26.2", "minecraft": "~26.2",