Compare commits

7 Commits

Author SHA1 Message Date
Gitea OpenCode Agent
af64e9140c Respond to issue #16 comments
Some checks failed
build / build (pull_request) Failing after 58s
build / build (push) Failing after 1m5s
2026-10-13 18:23:57 +00:00
Gitea OpenCode Agent
7fa45c8f49 Fix issue #16: Update README.md
Some checks failed
build / build (push) Has been cancelled
build / build (pull_request) Failing after 56s
2026-10-13 18:21:12 +00:00
fe084e1843 More things editor is now more stable
Some checks failed
build / build (push) Failing after 50s
2026-10-08 14:00:22 +02:00
b7e416d335 Mes coses divertides
Some checks failed
build / build (push) Failing after 52s
2026-10-08 01:54:02 +02:00
5897870725 Shell and folders
Some checks failed
build / build (push) Failing after 1m37s
2026-10-07 19:13:25 +02:00
7a115445ab Thingo 2026-10-06 17:59:26 +02:00
f2d09b8a9c Thing 2026-10-06 17:59:21 +02:00
80 changed files with 12500 additions and 439 deletions

64
AGENTS.md Normal file
View File

@@ -0,0 +1,64 @@
# AGENTS.md
Codecraft is a Fabric mod (mod id `codecraft`, group `com.aranroig`) that lets players write and run Lua code from an in-game code editor. The Lua runtime is [luajava](https://iroiro.party/luajava/) (`party.iroiro.luajava:luajava` + `luaj`, pure-Java LuaJ, no native libs).
## Commands
- `./gradlew build` — compile and build the mod jar (output in `build/libs/`). This is the only verification available; there are no tests.
- `./gradlew runClient` — launch the dev client with the mod loaded.
- `./gradlew runDatagen` — regenerate data (lang files) into `src/main/generated/`.
- Requires JDK 25. CI (`.github/workflows/build.yml`) builds on ubuntu-24.04 with JDK 25 (Microsoft distribution).
## Fast task-oriented reading
Do not read the whole source tree just to get oriented. Start with the files named in the task, then follow only the callers, callees, and data types needed to understand that change. Use `rg` to find a symbol or payload's other endpoints when needed. Check `git status --short` first and preserve pre-existing user changes; avoid touching unrelated files.
Use this map to find the likely starting point:
- **Editor input, layout, and panes:** `TextEditorScreen`, `EditorScreen`, `Widget`, `EditorTopBar`, `EditorFileTree`, `EditorPaneContainer`, `EditorFileView` under `src/client/java/com/aranroig/client/editor/`.
- **Text editing, completion, and syntax colors:** `EditorFileView`, `LiveDocument`, `EditHistory`, `CompletionProvider`, and `LuaHighlighter` in that same package. For edit networking, follow the corresponding payloads to `DocumentManager`.
- **Project files, collaboration, and persistence:** `Codecraft` registers packet handlers; `DocumentManager` owns live shared documents; `ProjectStore` reads/writes files; `ProjectPath` defines file names; `SavedProjectData` only handles legacy migration. Follow only the subsystem involved in the task.
- **Lua execution and API behavior:** `Codecraft` handles the run request; `ScriptRuntimeManager` owns server-side runtimes and event dispatch; `ScriptRuntime` owns one Lua state; API bindings are in `src/main/java/com/aranroig/wrapper/` and `listeners/`. Read `docs/lua-api.md` first for documented user-facing behavior.
- **In-game Lua documentation and completion libraries:** `docs/lua-api.md` is the human-authored reference; `src/main/resources/data/codecraft/docs/lua-api.json` is the packaged data; `LuaApiDocs`, `DocLibraries`, and `CompletionProvider` load or expose it in the editor. For translation changes, edit `CodecraftEnglishLangProvider`, not generated output.
- **Terminal pane and server shell:** `EditorTerminalPane` and `TerminalEmulator` are client-side; `ShellManager` and `ShellSession` are server-side; shell payloads connect them.
- **Mod setup, versions, and metadata:** `gradle.properties`, `build.gradle`, `src/main/resources/fabric.mod.json`, and the mixin configs. Do not inspect editor code for a build or metadata-only task.
Generated files under `src/main/generated/` should only be inspected when the generated output itself is relevant. Change its provider/input and regenerate it instead of editing it by hand.
## Versions
All versions live in `gradle.properties` (check https://fabricmc.net/develop): Minecraft `26.2`, loader `0.19.3`, loom `1.17-SNAPSHOT`, Fabric API `0.153.0+26.2`. Java release/target is 25. Mod version comes from `mod_version` and is expanded into `fabric.mod.json` at build time — never hardcode the version there.
## Source layout
Loom uses `splitEnvironmentSourceSets()`:
- `src/main/java` — common/server code. Entrypoint `com.aranroig.Codecraft` registers payloads and handles them server-side; Lua execution and its API bindings also run here.
- `src/client/java` — client-only code. Entrypoints `com.aranroig.client.CodecraftClient` (keybind, default `J`, toggles the editor) and `com.aranroig.client.CodecraftDataGenerator` (datagen).
- `src/main/resources` — `fabric.mod.json`, mixins config, assets.
- `src/main/generated` — datagen output (e.g. `assets/codecraft/lang/en_us.json`). Do not hand-edit; add translations in `CodecraftEnglishLangProvider` and run `runDatagen`.
## Architecture
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(...)`.
- **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`): custom widgets, not vanilla widgets. `EditorScreen` routes input to hit-tested `Widget`s. `EditorManager` owns editor actions; `EditorFileTree`, `EditorTopBar`, and `EditorPaneContainer` make up the main layout. The pane container manages one or more `EditorFileView`s; edits are tracked per pane and shared through the live-document payloads. See the task-oriented map above before opening more UI classes.
- **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload`; `Codecraft` reads the entrypoint from `ProjectStore` and starts a fresh per-player runtime through `ScriptRuntimeManager`. Lua runs on the server thread. `docs/lua-api.md` documents the exposed API; the server bindings live under `src/main/java/com/aranroig/wrapper/` and `listeners/`.
## Conventions
- Use `Codecraft.id(path)` / `Identifier.fromNamespaceAndPath(MOD_ID, path)` for all ids, and the `Codecraft.LOGGER` (slf4j) instead of `System.out.println` for new logging.
- Data classes that cross both persistence and network layers (see `EditorFile`) carry both a Mojang `Codec` and a `StreamCodec`; `RunInfo` currently only has a stream codec.
- A file's name is the **path** it lives at: `lib/gui/theme`, `/`-separated, no extension. `com.aranroig.editor.ProjectPath` is the only thing that reads one; to the server and to the live-document map a name is still an opaque unique key. `EditorFileTree` groups by the folders in those names (folders exist while something is in them, and folding one is client-side view state on `EditorManager`), and `ProjectPath.ENTRYPOINT` (`main`) is what a run executes.
- Records are used for payloads/simple data; match the style of the file you're editing (entrypoint classes from the Fabric template use tabs, editor code uses 4 spaces).
- Translation keys follow `key.codecraft.*` / `key.category.codecraft.*`.
- Mixin configs: `codecraft.mixins.json` (common, package `com.aranroig.mixin`) and `codecraft.client.mixins.json` (client). `ExampleMixin` / `ExampleClientMixin` are template leftovers.
## Status / gotchas
- `EditorManager.stop()` is currently empty. `com.aranroig.editor.Project` remains a stub; file lists are still represented as `List<EditorFile>`.
- Lua execution, event listeners, API bindings, live document collaboration, project loading, persistence, and the terminal shell are implemented. Check the relevant task-map entries before assuming one of these is still a TODO.
- Some TODOs/comments are written in Spanish/Catalan; leave them unless resolving them.
- Minecraft 26.2 uses the newer class/mapping names (`Identifier`, `GuiGraphicsExtractor`, `MouseButtonEvent`, `Component`, etc.) — don't rename them back to older MCP/Yarn-era names.

201
README.md
View File

@@ -1,9 +1,204 @@
# codecraft # codecraft
## Setup A [Fabric](https://fabricmc.net/) mod for Minecraft that lets players write and run
Lua from an in-game code editor. Press `J` (default, rebindable under
*Options → Controls → Codecraft*) to open the editor, write a script, and hit
**Run Script**: the code runs **on the server** and can change the world through a small
scripting API.
For setup instructions, please see the [Fabric Documentation page](https://docs.fabricmc.net/develop/getting-started/creating-a-project#setting-up) related to the IDE that you are using. ```lua
for y = 64, 67 do
world.set_block(10, y, -3, "minecraft:cobblestone")
end
```
Scripts are plain files in a project that lives on the server, so your work is a folder
of `.lua` files you can version, diff and edit outside the game — and several players can
type in the same file at the same time.
The full API reference lives in [docs/lua-api.md](docs/lua-api.md), and it is browsable
in-game from **Help → Lua API Documentation** or with **F1** on a function while editing.
## Features
**In-game editor** — a custom editor screen with multiple panes (split horizontally or
vertically), a file tree with folders, Lua syntax highlighting, autocompletion with
snippets, find and replace, undo/redo, and selectable colour themes.
**Server-side Lua** — every script runs on the server thread, so its effects are
authoritative for everyone in the world and the same script behaves the same wherever it
is written. A script can also keep listening after it finishes, reacting to item use,
broken blocks, chat, joins, leaves and every server tick. There are no permission or
reach checks, so this is for players you already trust.
**A project on disk** — the project lives in `config/codecraft/` as plain `.lua` files
mirroring the paths shown in the file tree (`lib/gui/theme` →
`config/codecraft/lib/gui/theme.lua`). Explicit saves write through at once; keystrokes
are flushed a beat after typing settles, and everything is read back fresh when the
editor opens, so external edits are picked up too.
**Real-time collaboration** — the server is the single authority on every open document.
Keystrokes are broadcast and rebased between players, so editing the same file together
does not lose anyone's work, and each file shows who else is in it.
**Terminal** — the editor has a terminal pane attached to a shell on the machine the
server runs on.
> **Note:** that terminal hands out a real shell to anyone who can open the editor. It is
> meant for single-player games and servers among friends, not for a public server.
## The Lua API
Scripts get a small, documented set of tables for touching the game:
| Table | What it does |
| ----- | ------------ |
| `print(...)`, `run(command)` | Message the player's chat, run a server command |
| `world` | Set, remove and read blocks, plus dimension, time, weather, biome and the online player list |
| `entities` | Find, spawn, inspect, teleport, rename and heal entities |
| `items` | Give, count, clear and edit inventory slots |
| `scoreboard` | Objectives, scores and display slots |
| `hud` | Titles, action-bar messages and boss bars |
| `events` | Listen for item use, broken blocks, chat, joins, leaves and ticks |
The file called `main` is the entrypoint — **Run Script** executes it, replacing the
previous run and its listeners. The runtime is LuaJ (Lua 5.1) with only the base library
loaded, and scripts run to completion on the server thread, so keep loops reasonable.
## Requirements
- Minecraft **26.2**
- Fabric Loader **0.19.3** or newer, with **Fabric API**
- Java **25** or newer
Versions are pinned in [`gradle.properties`](gradle.properties).
## Building from source
Requires JDK 25.
```sh
./gradlew build # compile and build the mod jar into build/libs/
./gradlew runClient # launch a dev client with the mod loaded
./gradlew runDatagen # regenerate data (lang files) into src/main/generated/
```
Loom uses split source sets: `src/main/java` holds the common/server code (payload
handlers, the project store, the Lua runtime and its API bindings) and `src/client/java`
holds the client code (keybind, editor UI, datagen). Flow is client editor → custom
payloads → server → persisted project.
`src/main/generated/` is datagen output — change its provider (for translations,
`CodecraftEnglishLangProvider`) and regenerate it instead of editing it by hand.
For setting up a development workspace in your IDE, see the
[Fabric documentation](https://docs.fabricmc.net/develop/getting-started/creating-a-project#setting-up).
## License ## License
This template is available under the CC0 license. Feel free to learn from it and incorporate it in your own projects. Distributed under the CC0-1.0 license (see [LICENSE](LICENSE)). The project builds on the
[Fabric example mod](https://github.com/FabricMC/fabric-example-mod) template, which is
also CC0.
```snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
snickers
```

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

379
docs/lua-api.md Normal file
View File

@@ -0,0 +1,379 @@
# Lua scripting
Scripts are written in the in-game editor (`J` by default, rebindable under
*Options → Controls* → *Codecraft*) and run **on the server**. The top bar's
**Run Script** executes `main.lua`, which is the entrypoint.
This same documentation is browsable in-game from the editor:
**Help → Lua API Documentation**, or press **F1** on a function while editing.
The browser has a search box above its function list — press **Ctrl+F** and
type to filter functions by name or description.
Because a script runs on the server thread from start to finish, everything it does
happens at once and the game waits for it to finish. Loops that place millions of
blocks will freeze the server, so keep them reasonable. A script can also keep
listening *after* it has finished, with [events](#events).
```lua
print("hello, player!")
```
## print(...)
Writes to the chat of the player who ran the script, tab-separated, like Minecraft
commands do.
```lua
print("blocks placed:", 12)
```
Whole numbers go through the Lua wrapper and are printed as `12.0`. To print them
without the decimal, concatenate them into a string:
```lua
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
Coordinates are **absolute world coordinates** — never relative to the player — in the
dimension the running player stands in. Press `F3` to read your own coordinates, then
use them in the script.
| Function | Returns |
| --------------------------------------- | --------------------------------------------------- |
| `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.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)
Places a block and updates neighbours and clients, like `/setblock` does. `block` is a
block id, with or without the `minecraft:` namespace, and may carry block states:
```lua
world.set_block(10, 64, -3, "minecraft:stone")
world.set_block(10, 65, -3, "gold_block") -- namespace optional
world.set_block(10, 66, -3, "minecraft:oak_stairs[facing=north]")
world.set_block(11, 66, -3, "minecraft:wall_torch[facing=south]") -- needs a wall behind it
```
The block is placed even if something is in the way. Blocks that cannot survive where
they are put (a torch without a wall, a flower without ground) drop themselves again,
and the call reports it as a failure.
Replacing a block that holds items, such as a chest, drops the contents like
`/setblock` does.
### world.remove_block(x, y, z[, drops])
Removes the block. Without `drops` the block just vanishes, silently and without items.
With `true` it breaks the way a player breaking it would: items, sound and particles.
```lua
world.remove_block(10, 64, -3) -- vanish
world.remove_block(10, 65, -3, true) -- break it, dropping items
```
### world.get_block(x, y, z)
Returns the block id at that position, including its block states, so the result can be
handed straight back to `world.set_block`:
```lua
print(world.get_block(10, 64, -3)) -- -> minecraft:grass_block[snowy=false]
```
Air is `"minecraft:air"`, a string, and every string is *true* in Lua — compare
against the id rather than testing the value:
```lua
local block = world.get_block(10, 64, -3)
if block ~= "minecraft:air" then
print("something is there: " .. block)
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
Listeners let a script react to the game *after* it has finished running. Register one
with `events.on_<event>(callback)`; from then on the callback runs whenever the event
happens.
| Registration | Callback signature |
| ----------------------------------- | ----------------------------------------------------------- |
| `events.on_use_item(cb)` | `cb(player, item, count, hand)` |
| `events.on_break_block(cb)` | `cb(player, x, y, z, block)` |
| `events.on_chat(cb)` | `cb(player, message)` |
| `events.on_player_join(cb)` | `cb(player)` |
| `events.on_player_leave(cb)` | `cb(player)` |
| `events.on_tick(cb)` | `cb(tick)` |
`player` is always the name of the player who caused the event. Other values depend on
the event:
- **on_use_item** — fires when a player right-clicks to use the item in their hand:
`item` is the item id (`"minecraft:stick"`), `count` the stack size, and `hand`
`"main"` or `"off"`. An empty hand does not fire. The click still does whatever it
would normally do — the listener only observes it.
- **on_break_block** — fires *after* the block is broken (`x, y, z` now hold air),
with the id of the block that was there.
- **on_chat** — fires with the plain text of the message. The message is sent to chat
as usual.
- **on_player_join / on_player_leave** — fire when a player joins or leaves, including
the running player themselves.
- **on_tick** — fires at the end of every server tick with the tick counter, a whole
number that grows by one every tick (20 ticks per second). Keep tick callbacks
cheap: they run twenty times a second, and a slow one lags the whole server.
Callbacks run on the server thread and have the same powers as the script that
registered them — they can call `print` and the Minecraft API tables. An error inside a
callback is printed to the owner's chat; it never stops the game or the other
listeners.
```lua
events.on_use_item(function(player, item, count, hand)
if item == "minecraft:stick" then
print(player .. " waved a stick (" .. hand .. " hand)")
end
end)
events.on_break_block(function(player, x, y, z, block)
if block == "minecraft:diamond_ore" then
print(player .. " struck diamond at " .. x .. ", " .. y .. ", " .. z)
end
end)
```
### Listening resets
Pressing **Run Script** replaces the previous run completely: all listeners from the
previous run are dropped, and only the ones the new run registers are active. If a run
registers none, the old listeners go quiet. Likewise, when the running player
disconnects their script stops with them — a script cannot outlive its owner.
If you run the same script twice, its listeners are *not* doubled — each run starts
from a clean slate.
## Examples
A pillar four blocks tall:
```lua
for y = 64, 67 do
world.set_block(10, y, -3, "minecraft:cobblestone")
end
```
A 7×7 platform:
```lua
for x = -3, 3 do
for z = -3, 3 do
world.set_block(10 + x, 64, -3 + z, "minecraft:stone_bricks")
end
end
```
A room with walls, a floor and an empty inside, i.e. hollowing out a box:
```lua
local x, y, z = 10, 64, -3 -- corner of the room
local width, height, depth = 7, 4, 7
for dx = 0, width - 1 do
for dy = 0, height - 1 do
for dz = 0, depth - 1 do
local shell = dx == 0 or dx == width - 1
or dy == 0 or dy == height - 1
or dz == 0 or dz == depth - 1
local px, py, pz = x + dx, y + dy, z + dz
if shell then
world.set_block(px, py, pz, "minecraft:stone_bricks")
else
world.remove_block(px, py, pz)
end
end
end
end
```
Copy the block type of one place to another:
```lua
local block = world.get_block(10, 64, -3)
if block then
world.set_block(20, 70, 5, block)
end
```
Clear an area of everything that is not air (leaves, grass, and so on):
```lua
for x = 0, 15 do
for y = 60, 80 do
for z = 0, 15 do
if world.get_block(x, y, z) ~= "minecraft:air" then
world.remove_block(x, y, z)
end
end
end
end
```
## Checking whether a call worked
Every block function returns a reason as its second value, which is worth printing
while a script misbehaves:
```lua
local ok, reason = world.set_block(10, 64, -3, "minecraft:stone")
if not ok then
print("could not place the block: " .. reason)
end
```
| Reason | What it means |
| ------------------------------------------ | ------------------------------------------------------------------------- |
| `usage: world.set_block(...)` | too few arguments |
| `x, y and z must be numbers` | a coordinate is missing, `nil`, or a string like `"10"` |
| `block must be a string, e.g. "minecraft:stone"` | the block was given as a number or table rather than a string |
| `'X' is not a block` | unknown block id, a misspelled state, or a tag such as `#minecraft:logs` |
| `y must be between -64 and 319, not 400` | outside the world's build height |
| `the chunk at x, z is not loaded` | too far away from any player, and not force-loaded |
| `'X' does not fit at x, y, z` | the block was placed and removed itself again (no support block) |
| `there is nothing to remove at x, y, z` | the target block is already air |
## Limits
- No reach or permission checks: a script can change any block in a **loaded** chunk of
the running player's dimension. Keep an eye on what you run.
- Only loaded chunks can be read or edited — those around players, or force-loaded.
- Block entity data is not exposed: a placed chest is empty, and a sign has no text.
- Only `main.lua` is executed. Code in the other project files is not loaded, so
`require` does not find them yet.
- The Lua runtime is LuaJ (Lua 5.1) with only the base library loaded: `tostring`,
`tonumber`, `type`, `pcall`, `pairs`, `ipairs`, `assert`, `error` are available, but
the `string`, `math`, `table` and `coroutine` libraries are not, so `math.floor(2.7)`
fails with *attempt to index a nil value*.

0
gradlew vendored Normal file → Executable file
View File

View File

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

View File

@@ -1,5 +1,7 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.docs.FunctionDoc;
/** /**
* A single autocomplete suggestion. * A single autocomplete suggestion.
* *
@@ -8,8 +10,25 @@ package com.aranroig.client.editor;
* but can differ (e.g. snippets with a trailing "(" etc.). * but can differ (e.g. snippets with a trailing "(" etc.).
* @param detail Short right-aligned annotation shown in the dropdown (e.g. "method", "keyword"). * @param detail Short right-aligned annotation shown in the dropdown (e.g. "method", "keyword").
* @param kind Category used for the icon/colour badge. * @param kind Category used for the icon/colour badge.
* @param docs Optional documentation rendered as a multi-line box below the
* popup for the highlighted item; null for items without docs.
*/ */
public record CompletionItem(String label, String insert, String detail, Kind kind) { public record CompletionItem(String label, String insert, String detail, Kind kind, Docs docs) {
/** Convenience constructor for items without documentation. */
public CompletionItem(String label, String insert, String detail, Kind kind) {
this(label, insert, detail, kind, null);
}
/**
* The API documentation attached to a completion.
*
* @param name Fully qualified name (e.g. {@code world.set_block} or {@code world}).
* @param blurb Description of a plain table; null for documented functions.
* @param function The full function doc; null for plain tables.
*/
public record Docs(String name, String blurb, FunctionDoc function) {
}
public enum Kind { public enum Kind {
KEYWORD, // language keywords KEYWORD, // language keywords
@@ -35,4 +54,15 @@ public record CompletionItem(String label, String insert, String detail, Kind ki
public static CompletionItem snippet(String label, String insert, String detail) { public static CompletionItem snippet(String label, String insert, String detail) {
return new CompletionItem(label, insert, detail, Kind.SNIPPET); return new CompletionItem(label, insert, detail, Kind.SNIPPET);
} }
/** A method/function documented in the Lua API catalog. */
public static CompletionItem documentedMethod(String label, String insert, FunctionDoc function) {
return new CompletionItem(label, insert, "method", Kind.METHOD,
new Docs(function.name(), null, function));
}
/** A global table documented in the Lua API catalog. */
public static CompletionItem documentedType(String name, String blurb) {
return new CompletionItem(name, name, "type", Kind.TYPE, new Docs(name, blurb, null));
}
} }

View File

@@ -8,9 +8,13 @@ import java.util.regex.Pattern;
* Generates autocomplete suggestions for Lua code given the current text * Generates autocomplete suggestions for Lua code given the current text
* buffer and cursor position. The provider combines: * buffer and cursor position. The provider combines:
* <ol> * <ol>
* <li>A static list of Lua keywords, built-in globals, and standard library members.</li> * <li>A static list of Lua keywords, built-in globals, and
* {@link LuaSnippets snippets}.</li>
* <li>Words already present in the buffer (user-defined functions/variables).</li> * <li>Words already present in the buffer (user-defined functions/variables).</li>
* <li>Library member completion after a "." or ":" trigger.</li> * <li>Library member completion after a "." or ":" trigger, backed by the
* {@link LuaLibrary} instances loaded in {@link #registerLibraries()} —
* Lua's own standard library plus the codecraft globals generated from
* the {@link com.aranroig.docs.LuaApiDocs} catalog.</li>
* </ol> * </ol>
* *
* None of this requires a real LSP – it is "good-enough" IDE-lite completion * None of this requires a real LSP – it is "good-enough" IDE-lite completion
@@ -28,6 +32,11 @@ public class CompletionProvider {
static { static {
List<CompletionItem> items = new ArrayList<>(); List<CompletionItem> items = new ArrayList<>();
// ── Codecraft globals, generated from the Lua API docs catalog ─────
// First in the list so their documented versions win over the plain
// duplicates below when labels collide.
items.addAll(DocLibraries.topLevelItems());
// ── Lua keywords ───────────────────────────────────────────────── // ── Lua keywords ─────────────────────────────────────────────────
for (String kw : new String[]{ for (String kw : new String[]{
"and", "break", "do", "else", "elseif", "end", "and", "break", "do", "else", "elseif", "end",
@@ -40,7 +49,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", "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 + "("));
@@ -52,172 +61,30 @@ public class CompletionProvider {
}) items.add(CompletionItem.type(lib)); }) items.add(CompletionItem.type(lib));
// ── Common snippets ─────────────────────────────────────────────── // ── Common snippets ───────────────────────────────────────────────
items.add(CompletionItem.snippet("fun", items.addAll(LuaSnippets.all());
"function ()\n \nend",
"anonymous function"));
items.add(CompletionItem.snippet("function",
"function name()\n \nend",
"named function"));
items.add(CompletionItem.snippet("lfun",
"local function name()\n \nend",
"local function"));
items.add(CompletionItem.snippet("if",
"if then\n \nend",
"if block"));
items.add(CompletionItem.snippet("ifel",
"if then\n \nelse\n \nend",
"if / else"));
items.add(CompletionItem.snippet("ifelseif",
"if then\n \nelseif then\n \nelse\n \nend",
"if / elseif / else"));
items.add(CompletionItem.snippet("for",
"for i = 1, do\n \nend",
"numeric for"));
items.add(CompletionItem.snippet("forin",
"for k, v in pairs() do\n \nend",
"generic for (pairs)"));
items.add(CompletionItem.snippet("fori",
"for i, v in ipairs() do\n \nend",
"generic for (ipairs)"));
items.add(CompletionItem.snippet("while",
"while do\n \nend",
"while loop"));
items.add(CompletionItem.snippet("repeat",
"repeat\n \nuntil ",
"repeat / until"));
items.add(CompletionItem.snippet("pcall",
"local ok, err = pcall(function()\n \nend)",
"protected call"));
items.add(CompletionItem.snippet("class",
"local ClassName = {}\nClassName.__index = ClassName\n\nfunction ClassName.new()\n local self = setmetatable({}, ClassName)\n return self\nend\n\nreturn ClassName",
"OOP class template"));
items.add(CompletionItem.snippet("require",
"local = require(\"\")",
"require module"));
items.add(CompletionItem.snippet("print",
"print()",
"print(…)"));
items.add(CompletionItem.snippet("local",
"local = ",
"local variable"));
items.add(CompletionItem.snippet("return",
"return ",
"return statement"));
STATIC_ITEMS = Collections.unmodifiableList(items); STATIC_ITEMS = Collections.unmodifiableList(items);
// ── Library member tables ───────────────────────────────────────── LIBRARY_MEMBERS = Collections.unmodifiableMap(registerLibraries());
Map<String, List<CompletionItem>> libs = new LinkedHashMap<>(); }
// string.* /**
List<CompletionItem> stringLib = new ArrayList<>(); * Loads the libraries whose members are offered after a dot or colon.
for (String[] m : new String[][]{ * Codecraft-provided tables come from the {@link com.aranroig.docs.LuaApiDocs}
{"byte", "byte(", "string.byte(s [,i [,j]])"}, * catalog, so documenting a function in {@code lua-api.json} is all it takes
{"char", "char(", "string.char(…)"}, * to make it complete in the editor. To expose a plain Lua table, implement
{"dump", "dump(", "string.dump(func)"}, * {@link LuaLibrary} and add an instance here.
{"find", "find(", "string.find(s, pattern [,init])"}, */
{"format", "format(", "string.format(fmt, …)"}, private static Map<String, List<CompletionItem>> registerLibraries() {
{"gmatch", "gmatch(", "string.gmatch(s, pattern)"}, List<LuaLibrary> libraries = new ArrayList<>();
{"gsub", "gsub(", "string.gsub(s, pattern, repl)"}, libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library
{"len", "len(", "string.len(s)"}, libraries.addAll(DocLibraries.libraries()); // codecraft globals, from the docs
{"lower", "lower(", "string.lower(s)"},
{"match", "match(", "string.match(s, pattern [,init])"},
{"rep", "rep(", "string.rep(s, n [,sep])"},
{"reverse", "reverse(", "string.reverse(s)"},
{"sub", "sub(", "string.sub(s, i [,j])"},
{"upper", "upper(", "string.upper(s)"},
}) stringLib.add(CompletionItem.method(m[0] + "(", m[1]));
libs.put("string", stringLib);
// table.* Map<String, List<CompletionItem>> members = new LinkedHashMap<>();
List<CompletionItem> tableLib = new ArrayList<>(); for (LuaLibrary library : libraries) {
for (String[] m : new String[][]{ members.put(library.name(), library.members());
{"concat", "concat(", "table.concat(t [,sep [,i [,j]]])"}, }
{"insert", "insert(", "table.insert(t [,pos], value)"}, return members;
{"move", "move(", "table.move(a1, f, e, t [,a2])"},
{"pack", "pack(", "table.pack(…)"},
{"remove", "remove(", "table.remove(t [,pos])"},
{"sort", "sort(", "table.sort(t [,comp])"},
{"unpack", "unpack(", "table.unpack(t [,i [,j]])"},
}) tableLib.add(CompletionItem.method(m[0] + "(", m[1]));
libs.put("table", tableLib);
// math.*
List<CompletionItem> mathLib = new ArrayList<>();
for (String[] m : new String[][]{
{"abs", "abs(", "math.abs(x)"},
{"ceil", "ceil(", "math.ceil(x)"},
{"cos", "cos(", "math.cos(x)"},
{"exp", "exp(", "math.exp(x)"},
{"floor", "floor(", "math.floor(x)"},
{"fmod", "fmod(", "math.fmod(x, y)"},
{"log", "log(", "math.log(x [,base])"},
{"max", "max(", "math.max(x, …)"},
{"min", "min(", "math.min(x, …)"},
{"modf", "modf(", "math.modf(x)"},
{"pow", "pow(", "math.pow(x, y)"},
{"random", "random(", "math.random([m [,n]])"},
{"randomseed", "randomseed(", "math.randomseed(x)"},
{"sin", "sin(", "math.sin(x)"},
{"sqrt", "sqrt(", "math.sqrt(x)"},
{"tan", "tan(", "math.tan(x)"},
{"tointeger", "tointeger(", "math.tointeger(x)"},
{"type", "type(", "math.type(x)"},
{"huge", "huge", "math.huge (∞)"},
{"pi", "pi", "math.pi"},
{"maxinteger", "maxinteger", "math.maxinteger"},
{"mininteger", "mininteger", "math.mininteger"},
}) mathLib.add(CompletionItem.method(m[0], m[1]));
libs.put("math", mathLib);
// io.*
List<CompletionItem> ioLib = new ArrayList<>();
for (String[] m : new String[][]{
{"close", "close(", "io.close([file])"},
{"flush", "flush()", "io.flush()"},
{"input", "input(", "io.input([file])"},
{"lines", "lines(", "io.lines([filename])"},
{"open", "open(", "io.open(filename [,mode])"},
{"output", "output(", "io.output([file])"},
{"popen", "popen(", "io.popen(prog [,mode])"},
{"read", "read(", "io.read(…)"},
{"tmpfile", "tmpfile()", "io.tmpfile()"},
{"type", "type(", "io.type(obj)"},
{"write", "write(", "io.write(…)"},
}) ioLib.add(CompletionItem.method(m[0], m[1]));
libs.put("io", ioLib);
// os.*
List<CompletionItem> osLib = new ArrayList<>();
for (String[] m : new String[][]{
{"clock", "clock()", "os.clock()"},
{"date", "date(", "os.date([format [,time]])"},
{"difftime", "difftime(", "os.difftime(t2, t1)"},
{"execute", "execute(", "os.execute([command])"},
{"exit", "exit(", "os.exit([code])"},
{"getenv", "getenv(", "os.getenv(varname)"},
{"remove", "remove(", "os.remove(filename)"},
{"rename", "rename(", "os.rename(oldname, newname)"},
{"setlocale","setlocale(","os.setlocale(locale [,category])"},
{"time", "time(", "os.time([table])"},
{"tmpname", "tmpname()", "os.tmpname()"},
}) osLib.add(CompletionItem.method(m[0], m[1]));
libs.put("os", osLib);
// coroutine.*
List<CompletionItem> coLib = new ArrayList<>();
for (String[] m : new String[][]{
{"create", "create(", "coroutine.create(f)"},
{"isyieldable", "isyieldable()", "coroutine.isyieldable()"},
{"resume", "resume(", "coroutine.resume(co [,…])"},
{"running", "running()", "coroutine.running()"},
{"status", "status(", "coroutine.status(co)"},
{"wrap", "wrap(", "coroutine.wrap(f)"},
{"yield", "yield(", "coroutine.yield(…)"},
}) coLib.add(CompletionItem.method(m[0], m[1]));
libs.put("coroutine", coLib);
LIBRARY_MEMBERS = Collections.unmodifiableMap(libs);
} }
// Lua identifier chars (no $ unlike Java) // Lua identifier chars (no $ unlike Java)
@@ -333,4 +200,4 @@ public class CompletionProvider {
if (i + 1 >= nameEnd) return null; // nothing before the separator if (i + 1 >= nameEnd) return null; // nothing before the separator
return buffer.substring(i + 1, nameEnd); return buffer.substring(i + 1, nameEnd);
} }
} }

View File

@@ -0,0 +1,94 @@
package com.aranroig.client.editor;
import com.aranroig.docs.FunctionDoc;
import com.aranroig.docs.LuaApiDocs;
import com.aranroig.docs.Topic;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Autocomplete data for every codecraft-provided Lua global, generated from the
* {@link LuaApiDocs} catalog ({@code data/codecraft/docs/lua-api.json}) instead
* of hand-maintained lists — anything documented in the in-game docs panel is
* completed in the editor automatically, with its full documentation rendered
* as a multi-line box below the completion popup.
*
* <p>Functions whose name is dotted ({@code world.set_block}) become members of
* the table before the first dot; functions with a bare name ({@code run},
* {@code print}) are offered as top-level completions.</p>
*/
public final class DocLibraries {
private DocLibraries() {
}
/** One {@link LuaLibrary} per documented table, for completion after a dot. */
public static List<LuaLibrary> libraries() {
Map<String, List<CompletionItem>> members = new LinkedHashMap<>();
for (FunctionDoc function : LuaApiDocs.functions()) {
String table = tableOf(function.name());
if (table.isEmpty()) continue; // bare globals are top-level items
members.computeIfAbsent(table, t -> new ArrayList<>())
.add(CompletionItem.documentedMethod(
memberOf(function.name()), memberOf(function.name()) + "(", function));
}
List<LuaLibrary> libraries = new ArrayList<>();
for (Map.Entry<String, List<CompletionItem>> entry : members.entrySet()) {
String name = entry.getKey();
List<CompletionItem> items = List.copyOf(entry.getValue());
libraries.add(new LuaLibrary() {
@Override public String name() { return name; }
@Override public List<CompletionItem> members() { return items; }
});
}
return libraries;
}
/**
* Top-level completion items from the catalog: documented tables as types
* (with the topic blurb) and bare documented functions as methods.
*/
public static List<CompletionItem> topLevelItems() {
List<CompletionItem> items = new ArrayList<>();
Set<String> seenTables = new LinkedHashSet<>();
for (FunctionDoc function : LuaApiDocs.functions()) {
String table = tableOf(function.name());
if (table.isEmpty()) {
items.add(CompletionItem.documentedMethod(
function.name(), function.name() + "(", function));
} else if (seenTables.add(table)) {
String blurb = blurbOf(table);
items.add(CompletionItem.documentedType(table, blurb.isEmpty() ? null : blurb));
}
}
return items;
}
// ── Derivation helpers ────────────────────────────────────────────────
/** The table part of a dotted function name, or "" when it is a bare global. */
private static String tableOf(String functionName) {
int dot = functionName.indexOf('.');
return dot < 0 ? "" : functionName.substring(0, dot);
}
/** The member part of a dotted function name (the whole name when bare). */
private static String memberOf(String functionName) {
int dot = functionName.indexOf('.');
return dot < 0 ? functionName : functionName.substring(dot + 1);
}
/** The blurb of the topic whose title names the table, "" when unknown. */
private static String blurbOf(String table) {
for (Topic topic : LuaApiDocs.topics()) {
if (topic.title().equals(table)) return topic.blurb().replace('\n', ' ').trim();
}
return "";
}
}

View File

@@ -0,0 +1,226 @@
package com.aranroig.client.editor;
import com.aranroig.editor.Edit;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.UUID;
/**
* What a file view remembers so Ctrl+Z and Ctrl+Shift+Z have something to
* take back and give forward again.
*
* <p>Each remembered change is kept as an {@link Edit} — the same walk over
* the text the editor sends around — that undoes (or redoes) it, written
* against the buffer as the view holds it. That is what lets undo survive
* somebody else editing the same file: every edit that arrives from them
* rewrites the remembered walks along with the buffer ({@link
* #rebaseAgainst}), so taking a change back lands on it wherever the text
* around it has drifted.</p>
*
* <p>Among the player's own changes the stacks need no rewriting: undo walks
* them last-to-first, and each remembered step was taken out of exactly the
* buffer the step before it puts back.</p>
*/
final class EditHistory {
/**
* One remembered change: the walk that undoes (or redoes) it, and the
* caret and selection to come back with it.
*/
record Entry(Edit operation, int caret, int selectionAnchor) {}
/** How far back undo — and redo — reach. */
private static final int MAX_ENTRIES = 512;
/**
* Changes this close together that keep writing on, erase back or delete
* forward count as one gesture: a single Ctrl+Z takes the word away
* instead of one letter at a time.
*/
private static final long MERGE_INTERVAL_MS = 500;
/**
* The author remembered walks carry. They never go out on the wire — an
* undo is sent as an edit with this client's real id — they only name
* them so that, when one is transformed against an incoming edit, it is
* never mistaken for another player's.
*/
private static final UUID AUTHOR = new UUID(0L, 0L);
/** Changes to take back, oldest first: the last one is the next to undo. */
private final Deque<Entry> undo = new ArrayDeque<>();
/** What undo gave back, oldest first: the last one is the next to redo. */
private final Deque<Entry> redo = new ArrayDeque<>();
private long sequence;
private long lastEditAt;
/**
* Remembers a change the player just made. {@code deleted} is what came
* out of the buffer at {@code position} and {@code inserted} what went in
* its place; the caret and selection say where undo should bring them
* back. Whatever was waiting to be redone falls away: the story carries
* on from here.
*/
void recordLocalEdit(int position, String deleted, String inserted, int caret, int selectionAnchor) {
if (deleted.isEmpty() && inserted.isEmpty()) return;
redo.clear();
long now = System.currentTimeMillis();
boolean sameGesture = now - lastEditAt <= MERGE_INTERVAL_MS;
lastEditAt = now;
Edit step = Edit.replace(AUTHOR, sequence++, position, inserted.length(), deleted);
if (sameGesture && mergeIntoLast(step)) return;
undo.addLast(new Entry(step, caret, selectionAnchor));
trim(undo);
}
/** The next change to take back, or {@code null} once there is none. */
Entry takeUndo() {
lastEditAt = 0; // typing after an undo belongs to a gesture of its own
return undo.pollLast();
}
/** The next change to put back in, or {@code null} once there is none. */
Entry takeRedo() {
lastEditAt = 0;
return redo.pollLast();
}
/** Puts a change that undo took onto the redo stack. */
void putRedo(Entry entry) {
redo.addLast(entry);
trim(redo);
}
/** Puts a change that redo undid back onto the undo stack. */
void putUndo(Entry entry) {
undo.addLast(entry);
trim(undo);
}
/**
* Somebody else's edit is about to be applied to the buffer. Everything
* remembered was written against the text as it stands before that, so
* every walk — and every caret it would restore — is rewritten against
* the text as it will stand after.
*/
void rebaseAgainst(Edit incoming) {
if (incoming.isEmpty()) return;
rebase(undo, incoming);
rebase(redo, incoming);
}
/** Forgets everything: the buffer is about to become somebody else's text. */
void clear() {
undo.clear();
redo.clear();
}
// ── Folding one gesture into a single step ────────────────────────────
/**
* Folds {@code step} into the last remembered change when the two are one
* gesture carried on: typing forward, erasing back, or the Delete key
* eating forward. The caret of the earlier step is kept — that is where
* the gesture started. False when this step stands on its own.
*/
private boolean mergeIntoLast(Edit step) {
Entry last = undo.peekLast();
if (last == null) return false;
Edit previous = last.operation();
int[] cutBefore = cutOf(previous);
int[] cut = cutOf(step);
if (cutBefore != null && cut != null && adjacent(cutBefore, cut)) {
return replaceLast(new Entry(Edit.deletion(AUTHOR, sequence++,
Math.min(cutBefore[0], cut[0]), cutBefore[1] + cut[1]),
last.caret(), last.selectionAnchor()));
}
Writing wroteBefore = writtenOf(previous);
Writing wrote = writtenOf(step);
if (wroteBefore != null && wrote != null) {
if (wrote.at() == wroteBefore.at() + wroteBefore.text().length())
return replaceLast(rejoined(last, wroteBefore.at(), wroteBefore.text() + wrote.text()));
if (wroteBefore.at() == wrote.at() + wrote.text().length())
return replaceLast(rejoined(last, wrote.at(), wrote.text() + wroteBefore.text()));
if (wrote.at() == wroteBefore.at())
return replaceLast(rejoined(last, wroteBefore.at(), wroteBefore.text() + wrote.text()));
}
return false;
}
private boolean replaceLast(Entry merged) {
undo.pollLast();
undo.addLast(merged);
return true;
}
/** A last step replaced by one that writes both runs back in their order. */
private Entry rejoined(Entry last, int at, String text) {
return new Entry(Edit.insertion(AUTHOR, sequence++, at, text), last.caret(), last.selectionAnchor());
}
/** Whether two erased runs touch: end to end, or the very same place again. */
private static boolean adjacent(int[] first, int[] second) {
return first[0] + first[1] == second[0]
|| second[0] + second[1] == first[0]
|| first[0] == second[0];
}
/** {@code {position, length}} when the walk erases one run of the text, else {@code null}. */
private static int[] cutOf(Edit edit) {
List<Edit.Component> components = edit.components();
int position = 0;
for (int i = 0; i < components.size(); i++) {
Edit.Component component = components.get(i);
if (component instanceof Edit.Retain retain) position += retain.count();
else if (component instanceof Edit.Delete delete && i == components.size() - 1)
return new int[]{position, delete.count()};
else return null;
}
return null;
}
/** Where and what, when the walk writes one run and erases nothing, else {@code null}. */
private static Writing writtenOf(Edit edit) {
List<Edit.Component> components = edit.components();
int position = 0;
for (int i = 0; i < components.size(); i++) {
Edit.Component component = components.get(i);
if (component instanceof Edit.Retain retain) position += retain.count();
else if (component instanceof Edit.Insert insert && i == components.size() - 1)
return new Writing(position, insert.text());
else return null;
}
return null;
}
/** One run an undo step writes back. */
private record Writing(int at, String text) {}
// ── Following the other editors ───────────────────────────────────────
private static void rebase(Deque<Entry> remembered, Edit incoming) {
List<Entry> rewritten = new ArrayList<>(remembered.size());
for (Entry entry : remembered) {
rewritten.add(new Entry(
entry.operation().transformAgainst(incoming),
incoming.shiftPosition(entry.caret()),
entry.selectionAnchor() < 0 ? -1 : incoming.shiftPosition(entry.selectionAnchor())));
}
remembered.clear();
remembered.addAll(rewritten);
}
private static void trim(Deque<Entry> remembered) {
while (remembered.size() > MAX_ENTRIES) remembered.removeFirst();
}
}

File diff suppressed because it is too large Load Diff

View File

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

View File

@@ -0,0 +1,317 @@
package com.aranroig.client.editor;
import com.aranroig.editor.EditorFile;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/** A small, non-modal find control anchored to the top-right of the editor. */
final class EditorFindBar extends Widget {
private static final int HEIGHT = 22;
private static final int PAD = 5;
private static final int BUTTON_WIDTH = 17;
private EditorFileView target;
private Widget restoreFocus;
private String query = "";
private int queryCursor;
private int querySelectionAnchor = -1;
private int activeOffset = -1;
private Font font;
private String cachedText;
private String cachedQuery;
private List<Integer> cachedOffsets = List.of();
EditorFindBar(EditorManager editorManager) {
super(editorManager);
setZIndex(3);
}
void open(EditorScreen screen, EditorFileView pane) {
boolean alreadyOpenForPane = editorScreen == screen && screen.widgets.contains(this) && target == pane;
if (!alreadyOpenForPane) {
target = pane;
restoreFocus = pane;
query = pane.searchSeed();
queryCursor = query.length();
querySelectionAnchor = query.isEmpty() ? -1 : 0;
activeOffset = -1;
}
if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
screen.selectedWidget = this;
if (!query.isEmpty()) selectFromCaret(true);
}
boolean isTarget(EditorFileView pane) {
return editorManager.isFindVisible(this) && target == pane;
}
EditorFileView targetPane() { return target; }
List<Integer> matchOffsets(EditorFileView pane) {
if (pane == null || !isTarget(pane) || query.isEmpty()) return List.of();
EditorFile file = pane.getCurrentEditorFile();
if (file == null) return List.of();
String text = pane.textForSearch();
if (text.equals(cachedText) && query.equals(cachedQuery)) return cachedOffsets;
String lower = text.toLowerCase(Locale.ROOT);
String needle = query.toLowerCase(Locale.ROOT);
List<Integer> offsets = new ArrayList<>();
int from = 0;
while (from <= lower.length() - needle.length()) {
int offset = lower.indexOf(needle, from);
if (offset < 0) break;
offsets.add(offset);
from = offset + Math.max(1, needle.length());
}
cachedText = text;
cachedQuery = query;
cachedOffsets = offsets;
return cachedOffsets;
}
int activeMatchOffset(EditorFileView pane) {
return isTarget(pane) ? activeOffset : -1;
}
int queryLength(EditorFileView pane) {
return isTarget(pane) ? query.length() : 0;
}
private int barWidth() {
return Math.max(120, Math.min(360, editorScreen.width - 16));
}
private int barX() { return Math.max(4, editorScreen.width - barWidth() - 8); }
private int barY() { return 16; }
private int inputX() { return barX() + PAD; }
private int inputEndX() { return barX() + barWidth() - (BUTTON_WIDTH * 3 + 42); }
private int previousX() { return barX() + barWidth() - BUTTON_WIDTH * 3 - 2; }
private int nextX() { return previousX() + BUTTON_WIDTH; }
private int closeX() { return nextX() + BUTTON_WIDTH; }
@Override
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
font = editorScreen.getFont();
int x = barX(), y = barY(), w = barWidth();
int bottom = y + HEIGHT;
graphics.fill(x + 2, y + 2, x + w + 2, bottom + 2, 0x55000000);
graphics.fill(x, y, x + w, bottom, editorManager.theme().raisedBackground());
graphics.fill(x, y, x + w, y + 1, editorManager.theme().border());
graphics.fill(x, bottom - 1, x + w, bottom, editorManager.theme().border());
graphics.fill(x, y, x + 1, bottom, editorManager.theme().border());
graphics.fill(x + w - 1, y, x + w, bottom, editorManager.theme().border());
int inputLeft = inputX();
int inputRight = Math.max(inputLeft + 30, inputEndX());
graphics.fill(inputLeft, y + 3, inputRight, bottom - 3, editorManager.theme().background());
graphics.fill(inputLeft, y + 3, inputLeft + 2, bottom - 3,
query.isEmpty() ? editorManager.theme().border() : editorManager.theme().accent());
String shown = query.isEmpty() ? "Find" : query;
int textY = y + (HEIGHT - font.lineHeight) / 2;
int textX = inputLeft + 7;
int shift = queryShift(inputRight - textX - 3);
graphics.enableScissor(textX, y + 2, inputRight - 3, bottom - 2);
if (querySelectionAnchor >= 0 && querySelectionAnchor != queryCursor) {
int selectionStart = Math.min(querySelectionAnchor, queryCursor);
int selectionEnd = Math.max(querySelectionAnchor, queryCursor);
int selectionX0 = textX - shift + font.width(query.substring(0, selectionStart));
int selectionX1 = textX - shift + font.width(query.substring(0, selectionEnd));
graphics.fill(selectionX0, y + 4, selectionX1, bottom - 4, editorManager.theme().selection());
}
graphics.text(font, shown, textX - shift, textY,
query.isEmpty() ? editorManager.theme().mutedText() : editorManager.theme().text(), false);
if (editorScreen.selectedWidget == this && !query.isEmpty()
&& (System.currentTimeMillis() / 500) % 2 == 0) {
int caretX = textX - shift
+ font.width(query.substring(0, Math.min(queryCursor, query.length())));
graphics.fill(caretX, y + 5, caretX + 1, bottom - 5, editorManager.theme().cursor());
}
graphics.disableScissor();
List<Integer> matches = matchOffsets(target);
int activeIndex = matches.indexOf(activeOffset);
String count = matches.isEmpty() ? (query.isEmpty() ? "" : "0/0")
: (activeIndex + 1) + "/" + matches.size();
int countWidth = font.width(count);
graphics.text(font, count, previousX() - countWidth - 3, textY,
matches.isEmpty() && !query.isEmpty() ? editorManager.theme().danger() : editorManager.theme().mutedText(), false);
drawButton(graphics, "↑", previousX(), mouseX, mouseY);
drawButton(graphics, "↓", nextX(), mouseX, mouseY);
drawButton(graphics, "×", closeX(), mouseX, mouseY);
}
private int queryShift(int availableWidth) {
int caretWidth = font.width(query.substring(0, Math.min(queryCursor, query.length())));
return Math.max(0, caretWidth - availableWidth + 4);
}
private void drawButton(GuiGraphicsExtractor graphics, String label, int x, int mouseX, int mouseY) {
int y = barY();
boolean hovered = mouseX >= x && mouseX < x + BUTTON_WIDTH && mouseY >= y && mouseY < y + HEIGHT;
if (hovered) graphics.fill(x, y + 2, x + BUTTON_WIDTH, y + HEIGHT - 2, editorManager.theme().hoverBackground());
graphics.text(font, label, x + (BUTTON_WIDTH - font.width(label)) / 2,
y + (HEIGHT - font.lineHeight) / 2, editorManager.theme().text(), false);
}
@Override
public boolean inside(double x, double y) {
return x >= barX() && x < barX() + barWidth() && y >= barY() && y < barY() + HEIGHT;
}
@Override
public boolean handleKeyPressed(KeyEvent event) {
int key = event.key();
if (event.hasControlDown() && key == 65) {
querySelectionAnchor = 0;
queryCursor = query.length();
return true;
}
switch (key) {
case 256 -> { close(); return true; } // Escape
case 259 -> { // Backspace
if (hasQuerySelection()) {
removeQuerySelection();
changedQuery();
} else if (queryCursor > 0) {
query = query.substring(0, queryCursor - 1) + query.substring(queryCursor);
queryCursor--;
changedQuery();
}
return true;
}
case 261 -> { // Delete
if (hasQuerySelection()) {
removeQuerySelection();
changedQuery();
} else if (queryCursor < query.length()) {
query = query.substring(0, queryCursor) + query.substring(queryCursor + 1);
changedQuery();
}
return true;
}
case 263 -> { queryCursor = hasQuerySelection() ? Math.min(querySelectionAnchor, queryCursor) : Math.max(0, queryCursor - 1); querySelectionAnchor = -1; return true; }
case 262 -> { queryCursor = hasQuerySelection() ? Math.max(querySelectionAnchor, queryCursor) : Math.min(query.length(), queryCursor + 1); querySelectionAnchor = -1; return true; }
case 268 -> { queryCursor = 0; querySelectionAnchor = -1; return true; }
case 269 -> { queryCursor = query.length(); querySelectionAnchor = -1; return true; }
case 265 -> { move(-1); return true; } // Up
case 264 -> { move(1); return true; } // Down
case 257 -> { move(event.hasShiftDown() ? -1 : 1); return true; } // Enter
default -> { return true; }
}
}
@Override
public boolean handleCharTyped(CharacterEvent event) {
int cp = event.codepoint();
if (cp >= 32 && cp != 127) {
String chars = Character.toString(cp);
if (hasQuerySelection()) removeQuerySelection();
query = query.substring(0, queryCursor) + chars + query.substring(queryCursor);
queryCursor += chars.length();
changedQuery();
}
return true;
}
private void changedQuery() {
querySelectionAnchor = -1;
activeOffset = -1;
selectFromCaret(true);
}
private boolean hasQuerySelection() {
return querySelectionAnchor >= 0 && querySelectionAnchor != queryCursor;
}
private void removeQuerySelection() {
int start = Math.min(querySelectionAnchor, queryCursor);
int end = Math.max(querySelectionAnchor, queryCursor);
query = query.substring(0, start) + query.substring(end);
queryCursor = start;
querySelectionAnchor = -1;
}
private void selectFromCaret(boolean forward) {
List<Integer> matches = matchOffsets(target);
if (matches.isEmpty() || target == null) {
activeOffset = -1;
if (target != null) target.clearSearchSelection();
return;
}
int caret = target.searchAnchorOffset();
int selected = forward ? matches.getFirst() : matches.getLast();
for (int offset : matches) {
if (offset <= caret && offset + query.length() >= caret) {
selected = offset;
break;
}
if (forward && offset >= caret) {
selected = offset;
break;
}
if (!forward && offset < caret) selected = offset;
}
select(selected);
}
private void move(int direction) {
List<Integer> matches = matchOffsets(target);
if (matches.isEmpty()) return;
int index = matches.indexOf(activeOffset);
if (index < 0) index = direction > 0 ? -1 : 0;
index = (index + direction + matches.size()) % matches.size();
select(matches.get(index));
}
private void select(int offset) {
activeOffset = offset;
if (target != null) target.selectSearchMatch(offset, query.length());
}
private int inputCaretAt(int mouseX) {
int textX = inputX() + 7;
int inputRight = Math.max(textX + 1, inputEndX());
int shift = queryShift(inputRight - textX - 3);
int x = mouseX + shift;
int best = 0;
for (int i = 1; i <= query.length(); i++) {
if (x >= textX + font.width(query.substring(0, i))) best = i;
}
return best;
}
@Override
public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return true;
int mx = (int) event.x(), my = (int) event.y();
if (my < barY() || my >= barY() + HEIGHT) return true;
if (mx >= closeX() && mx < closeX() + BUTTON_WIDTH) {
close();
} else if (mx >= nextX() && mx < nextX() + BUTTON_WIDTH) {
move(1);
} else if (mx >= previousX() && mx < previousX() + BUTTON_WIDTH) {
move(-1);
} else {
queryCursor = inputCaretAt(mx);
querySelectionAnchor = -1;
}
return true;
}
private void close() {
editorManager.closeFind(this, restoreFocus);
}
@Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
@Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
@Override public boolean handleMouseScrolled(double scrollY) { return true; }
}

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

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

View File

@@ -0,0 +1,38 @@
package com.aranroig.client.editor;
/**
* Something that lives in the editor's pane area: a file being edited
* ({@link EditorFileView}) or the server shell ({@link EditorTerminalPane}).
*
* <p>{@link EditorPaneContainer} provides an optional header with the title
* and pane controls, plus draggable sashes around each pane. Subclasses can
* choose whether to show a header, which title and controls it has, and what
* cleanup to do when it closes.</p>
*/
public abstract class EditorPane extends Widget {
protected EditorPane(EditorManager editorManager) {
super(editorManager);
}
/** The text of the header above this pane. */
public abstract String paneTitle();
/** Whether this pane needs a header at all. */
public boolean showHeader() {
return true;
}
/**
* Whether the header offers the split-right / split-below buttons. File
* panes can be split; the shell is one shell, so its header only holds the
* close button.
*/
public boolean showSplitButtons() {
return true;
}
/** The header's close button was pressed and this pane is going away. */
public void onPaneClosed() {
}
}

View File

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

View File

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

View File

@@ -0,0 +1,320 @@
package com.aranroig.client.editor;
import com.aranroig.editor.EditorFile;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/** Modal find, project search, and file picker for the editor. */
final class EditorSearchPopup extends Widget {
enum Mode { FIND, PROJECT, FILE }
private record Result(EditorFile file, int offset, int length, int line, String preview) {}
private static final int MAX_RESULTS = 200;
private static final int ROW_HEIGHT = 14;
private static final int PAD = 8;
private Mode mode;
private String query = "";
private int queryCursor;
private int selected;
private int scroll;
private int lastFindStart = -1;
private String lastFindQuery = "";
private Widget restoreFocus;
private Font font;
EditorSearchPopup(EditorManager editorManager) {
super(editorManager);
setZIndex(3);
}
void open(EditorScreen screen, Mode mode, Widget restoreFocus) {
this.mode = mode;
this.restoreFocus = restoreFocus == this && this.restoreFocus != null ? this.restoreFocus : restoreFocus;
this.query = mode == Mode.FIND && restoreFocus instanceof EditorFileView view ? view.searchSeed() : "";
this.queryCursor = query.length();
this.selected = 0;
this.scroll = 0;
this.lastFindStart = -1;
this.lastFindQuery = "";
setSize(0, 0, -1, -1);
if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
screen.selectedWidget = this;
if (mode == Mode.FIND && !query.isEmpty()) findFromCaret(true);
}
private String title() {
return switch (mode) {
case FIND -> "Find in file";
case PROJECT -> "Find in project";
case FILE -> "Go to file";
};
}
private List<Result> results() {
List<Result> found = new ArrayList<>();
String needle = query.toLowerCase(Locale.ROOT);
if (mode == Mode.FIND) {
EditorFileView pane = editorManager.activePane();
EditorFile file = pane == null ? null : pane.getCurrentEditorFile();
if (file == null || needle.isEmpty()) return found;
addTextMatches(found, file, pane.textForSearch(), needle);
return found;
}
for (EditorFile file : editorManager.getFiles()) {
if (mode == Mode.FILE) {
if (needle.isEmpty() || file.getName().toLowerCase(Locale.ROOT).contains(needle)) {
found.add(new Result(file, -1, 0, 0, file.getName()));
if (found.size() >= MAX_RESULTS) break;
}
} else if (!needle.isEmpty()) {
addTextMatches(found, file, editorManager.textForSearch(file), needle);
if (found.size() >= MAX_RESULTS) break;
}
}
return found;
}
private static void addTextMatches(List<Result> results, EditorFile file, String text, String needle) {
String lower = text.toLowerCase(Locale.ROOT);
int from = 0;
while (results.size() < MAX_RESULTS) {
int offset = lower.indexOf(needle, from);
if (offset < 0) break;
int lineStart = offset == 0 ? 0 : text.lastIndexOf('\n', offset - 1) + 1;
int lineEnd = text.indexOf('\n', offset);
if (lineEnd < 0) lineEnd = text.length();
int lineNumber = 1;
for (int i = 0; i < lineStart; i++) if (text.charAt(i) == '\n') lineNumber++;
String line = text.substring(lineStart, lineEnd).strip();
if (line.length() > 120) line = line.substring(0, 117) + "...";
results.add(new Result(file, offset, needle.length(), lineNumber, line));
from = offset + Math.max(1, needle.length());
}
}
private int panelWidth() { return Math.min(520, Math.max(260, editorScreen.width - 32)); }
private int panelX() { return (editorScreen.width - panelWidth()) / 2; }
private int panelY() { return Math.max(18, editorScreen.height / 5); }
private int panelHeight() { return Math.min(editorScreen.height - 32, 250); }
private int inputY() { return panelY() + 31; }
private int listY() { return inputY() + 23; }
private int maxVisibleRows() { return Math.max(1, (panelY() + panelHeight() - PAD - listY()) / ROW_HEIGHT); }
@Override
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
font = editorScreen.getFont();
int x = panelX(), y = panelY(), w = panelWidth(), h = panelHeight();
graphics.fill(0, 0, editorScreen.width, editorScreen.height, editorManager.theme().overlay());
graphics.fill(x + 2, y + 2, x + w + 2, y + h + 2, 0x55000000);
graphics.fill(x, y, x + w, y + h, editorManager.theme().background());
graphics.fill(x, y, x + w, y + 1, editorManager.theme().border());
graphics.fill(x, y + h - 1, x + w, y + h, editorManager.theme().border());
graphics.fill(x, y, x + 1, y + h, editorManager.theme().border());
graphics.fill(x + w - 1, y, x + w, y + h, editorManager.theme().border());
graphics.text(font, title(), x + PAD, y + PAD, editorManager.theme().text(), false);
int ix = x + PAD, iw = w - PAD * 2;
graphics.fill(ix, inputY(), ix + iw, inputY() + 18, editorManager.theme().raisedBackground());
graphics.fill(ix, inputY(), ix + iw, inputY() + 1, editorManager.theme().accent());
String shown = query.isEmpty() ? "Type to search…" : query;
graphics.text(font, shown, ix + 5, inputY() + 5,
query.isEmpty() ? editorManager.theme().mutedText() : editorManager.theme().text(), false);
if (!query.isEmpty() && (System.currentTimeMillis() / 500) % 2 == 0) {
int caretX = ix + 5 + font.width(query.substring(0, Math.min(queryCursor, query.length())));
graphics.fill(caretX, inputY() + 4, caretX + 1, inputY() + 15, editorManager.theme().cursor());
}
List<Result> rows = results();
if (selected >= rows.size()) selected = Math.max(0, rows.size() - 1);
if (selected < scroll) scroll = selected;
if (selected >= scroll + maxVisibleRows()) scroll = selected - maxVisibleRows() + 1;
graphics.enableScissor(x + 1, listY(), x + w - 1, y + h - PAD);
int shownRows = Math.min(rows.size() - scroll, maxVisibleRows());
for (int i = 0; i < shownRows; i++) {
int index = scroll + i;
Result result = rows.get(index);
int rowY = listY() + i * ROW_HEIGHT;
if (index == selected) graphics.fill(x + 1, rowY, x + w - 1, rowY + ROW_HEIGHT, editorManager.theme().selection());
String label;
if (mode == Mode.FILE) label = result.file().getName();
else label = result.file().getName() + ":" + result.line() + " " + result.preview();
int available = w - PAD * 2 - 4;
if (font.width(label) > available) {
while (!label.isEmpty() && font.width(label + "…") > available) label = label.substring(0, label.length() - 1);
label += "…";
}
graphics.text(font, label, x + PAD, rowY + 3,
index == selected ? editorManager.theme().text() : editorManager.theme().mutedText(), false);
}
graphics.disableScissor();
String count = mode == Mode.FIND
? (rows.isEmpty() ? "No matches" : (selected + 1) + " / " + rows.size() + " · Enter next, Shift+Enter previous")
: rows.size() + (rows.size() == MAX_RESULTS ? "+" : "") + " results · ↑↓ select, Enter open, Esc close";
graphics.text(font, count, x + PAD, y + h - font.lineHeight - 4, editorManager.theme().hint(), false);
}
@Override
public boolean handleKeyPressed(KeyEvent event) {
int key = event.key();
boolean ctrl = event.hasControlDown();
if (ctrl && key == 65) { queryCursor = query.length(); return true; }
switch (key) {
case 256 -> { close(); return true; }
case 259 -> { // Backspace
if (queryCursor > 0) {
query = query.substring(0, queryCursor - 1) + query.substring(queryCursor);
queryCursor--;
changedQuery();
}
return true;
}
case 261 -> {
if (queryCursor < query.length()) {
query = query.substring(0, queryCursor) + query.substring(queryCursor + 1);
changedQuery();
}
return true;
}
case 263 -> { queryCursor = Math.max(0, queryCursor - 1); return true; }
case 262 -> { queryCursor = Math.min(query.length(), queryCursor + 1); return true; }
case 268 -> { queryCursor = 0; return true; }
case 269 -> { queryCursor = query.length(); return true; }
case 265 -> { moveSelection(-1); return true; }
case 264 -> { moveSelection(1); return true; }
case 257 -> {
if (mode == Mode.FIND) findFromCaret(!event.hasShiftDown());
else openSelected();
return true;
}
}
return true;
}
@Override
public boolean handleCharTyped(CharacterEvent event) {
int cp = event.codepoint();
if (cp >= 32 && cp != 127) {
String chars = Character.toString(cp);
query = query.substring(0, queryCursor) + chars + query.substring(queryCursor);
queryCursor += chars.length();
changedQuery();
}
return true;
}
private void changedQuery() {
selected = 0;
scroll = 0;
if (mode == Mode.FIND) {
lastFindQuery = "";
findFromCaret(true);
}
}
private void moveSelection(int direction) {
List<Result> rows = results();
if (rows.isEmpty()) return;
selected = (selected + direction + rows.size()) % rows.size();
if (mode == Mode.FIND) selectFindResult(rows.get(selected));
}
private void findFromCaret(boolean forward) {
List<Result> rows = results();
if (rows.isEmpty()) return;
EditorFileView pane = editorManager.activePane();
int caret = pane == null ? 0 : pane.searchAnchorOffset();
int start = forward ? 0 : rows.size() - 1;
if (query.equalsIgnoreCase(lastFindQuery) && lastFindStart >= 0) {
for (int i = 0; i < rows.size(); i++) {
int index = forward ? (selected + 1 + i) % rows.size() : (selected - 1 - i + rows.size() * 2) % rows.size();
if (rows.get(index).offset() >= 0) { start = index; break; }
}
} else {
// Prefer the occurrence under the caret (or the selection that
// seeded Ctrl+F); subsequent Enter presses walk from that match.
boolean located = false;
for (int i = 0; i < rows.size(); i++) {
Result result = rows.get(i);
if (result.offset() <= caret && result.offset() + result.length() >= caret) {
start = i;
located = true;
break;
}
}
if (!located && forward) {
for (int i = 0; i < rows.size(); i++) if (rows.get(i).offset() >= caret) { start = i; break; }
} else if (!located) {
for (int i = rows.size() - 1; i >= 0; i--) if (rows.get(i).offset() < caret) { start = i; break; }
}
}
selected = start;
lastFindQuery = query;
lastFindStart = rows.get(selected).offset();
selectFindResult(rows.get(selected));
}
private void selectFindResult(Result result) {
EditorFileView pane = editorManager.activePane();
if (pane != null && result.offset() >= 0) pane.selectSearchMatch(result.offset(), result.length());
}
private void openSelected() {
List<Result> rows = results();
if (selected < 0 || selected >= rows.size()) return;
Result result = rows.get(selected);
close();
editorManager.openFile(result.file());
if (mode == Mode.PROJECT) {
EditorFileView pane = editorManager.activePane();
if (pane != null) pane.selectSearchMatch(result.offset(), result.length());
}
}
private void close() {
editorManager.closeSearch(this, restoreFocus);
}
@Override
public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
if (event.button() != 0) return true;
int x = panelX(), y = panelY(), w = panelWidth();
int mx = (int) event.x(), my = (int) event.y();
if (mx < x || mx >= x + w || my < y || my >= y + panelHeight()) {
close();
return true;
}
if (my >= listY()) {
int index = scroll + (my - listY()) / ROW_HEIGHT;
if (index >= 0 && index < results().size()) {
selected = index;
if (mode == Mode.FIND) selectFindResult(results().get(index));
else openSelected();
}
}
return true;
}
@Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
@Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
@Override
public boolean handleMouseScrolled(double scrollY) {
List<Result> rows = results();
if (rows.isEmpty()) return true;
selected = Math.max(0, Math.min(rows.size() - 1, selected - (int) Math.signum(scrollY)));
if (mode == Mode.FIND) selectFindResult(rows.get(selected));
return true;
}
}

View File

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

View File

@@ -0,0 +1,120 @@
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)),
DRACULA("Dracula", new Palette(
0xFF282A36, 0xFF21222C, 0xFF343746, 0xFF44475A, 0xFF383A4A,
0xFFF8F8F2, 0xFFB8B8C8, 0xFF515366, 0xFFBD93F9, 0xFFD0AEFF,
0xFF44475A, 0xFF515366, 0xFFFF5555,
0xFFFFB86C, 0xFFFFCC8A, 0xFF9A714C, 0xFF8BE9FD, 0xFF6272A4,
0xFFF8F8F2, 0x66F8F8F2,
0xFFF8F8F2, 0xFFFF79C6, 0xFF8BE9FD, 0xFFF1FA8C, 0xFFBD93F9,
0xFF6272A4, 0xFFFFB86C, 0xFF50FA7B, 0xFF6272A4,
0xFF191A21, 0xFFB8B8C8, 0xFF191A21, 0xB0000000)),
SOLARIZED_DARK("Solarized Dark", new Palette(
0xFF002B36, 0xFF00232C, 0xFF073642, 0xFF164550, 0xFF0B3A45,
0xFFEEE8D5, 0xFF93A1A1, 0xFF586E75, 0xFF268BD2, 0xFF4AA3DF,
0xFF164550, 0xFF1D5360, 0xFFDC322F,
0xFFB58900, 0xFFD0A629, 0xFF806000, 0xFF2AA198, 0xFF657B83,
0xFFEEE8D5, 0x66EEE8D5,
0xFF839496, 0xFF859900, 0xFF268BD2, 0xFF2AA198, 0xFFCB4B16,
0xFF586E75, 0xFFB58900, 0xFF6C71C4, 0xFF657B83,
0xFF00232C, 0xFF93A1A1, 0xFF00232C, 0xB0000000)),
SOLARIZED_LIGHT("Solarized Light", new Palette(
0xFFFDF6E3, 0xFFEEE8D5, 0xFFF5EEDB, 0xFFE5DDC8, 0xFFF0E8D3,
0xFF586E75, 0xFF839496, 0xFFB7AE98, 0xFF268BD2, 0xFF4AA3DF,
0xFFE5DDC8, 0xFFDAD1BA, 0xFFDC322F,
0xFFB58900, 0xFFD0A629, 0xFF806000, 0xFF2AA198, 0xFF657B83,
0xFF586E75, 0x66586E75,
0xFF586E75, 0xFF859900, 0xFF268BD2, 0xFF2AA198, 0xFFCB4B16,
0xFF93A1A1, 0xFFB58900, 0xFF6C71C4, 0xFF839496,
0xFFEEE8D5, 0xFF839496, 0xFFEEE8D5, 0xB0000000)),
GRUVBOX_DARK("Gruvbox Dark", new Palette(
0xFF282828, 0xFF1D2021, 0xFF32302F, 0xFF3C3836, 0xFF353230,
0xFFEBDBB2, 0xFFA89984, 0xFF504945, 0xFF83A598, 0xFF9DB9AD,
0xFF504945, 0xFF665C54, 0xFFFB4934,
0xFFD79921, 0xFFE7B84A, 0xFF8F6416, 0xFF8EC07C, 0xFF928374,
0xFFEBDBB2, 0x66EBDBB2,
0xFFEBDBB2, 0xFFFB4934, 0xFF8EC07C, 0xFFB8BB26, 0xFFD79921,
0xFF928374, 0xFF83A598, 0xFFD3869B, 0xFF928374,
0xFF1D2021, 0xFFA89984, 0xFF1D2021, 0xB0000000)),
TOKYO_NIGHT("Tokyo Night", new Palette(
0xFF1A1B26, 0xFF16161E, 0xFF24283B, 0xFF2F3549, 0xFF292E42,
0xFFC0CAF5, 0xFF787C99, 0xFF414868, 0xFF7AA2F7, 0xFF91B4FF,
0xFF364A82, 0xFF414F78, 0xFFF7768E,
0xFFE0AF68, 0xFFF0C77E, 0xFF977647, 0xFF7DCFFF, 0xFF565F89,
0xFFC0CAF5, 0x66C0CAF5,
0xFFC0CAF5, 0xFFBB9AF7, 0xFF7DCFFF, 0xFF9ECE6A, 0xFFFF9E64,
0xFF565F89, 0xFF7AA2F7, 0xFF2AC3DE, 0xFF565F89,
0xFF15161E, 0xFF787C99, 0xFF15161E, 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

@@ -0,0 +1,178 @@
package com.aranroig.client.editor;
import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent;
import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull;
/** Modal theme chooser opened from View → Change theme. */
final class EditorThemePopup extends Widget {
private static final int PAD = 9;
private static final int ROW_HEIGHT = 17;
private static final int MAX_PANEL_HEIGHT = 236;
private Widget restoreFocus;
private EditorTheme originalTheme;
private int selected;
private int scroll;
private Font font;
EditorThemePopup(EditorManager editorManager) {
super(editorManager);
setZIndex(4);
}
void open(EditorScreen screen, Widget restoreFocus) {
this.restoreFocus = restoreFocus;
originalTheme = editorManager.currentTheme();
selected = originalTheme.ordinal();
scroll = 0;
setSize(0, 0, -1, -1);
if (editorScreen != screen || !screen.widgets.contains(this)) addToEditorScreen(screen);
screen.selectedWidget = this;
}
private int panelWidth() { return Math.min(300, Math.max(1, editorScreen.width - 24)); }
private int panelHeight() { return Math.max(1, Math.min(MAX_PANEL_HEIGHT, editorScreen.height - 24)); }
private int panelX() { return (editorScreen.width - panelWidth()) / 2; }
private int panelY() { return (editorScreen.height - panelHeight()) / 2; }
private int listTop() { return panelY() + 30; }
private int listBottom() { return panelY() + panelHeight() - 24; }
private int visibleRows() { return Math.max(1, (listBottom() - listTop()) / ROW_HEIGHT); }
@Override
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
font = editorScreen.getFont();
int x = panelX(), y = panelY(), w = panelWidth(), h = panelHeight();
int right = x + w, bottom = y + h;
graphics.fill(0, 0, editorScreen.width, editorScreen.height, editorManager.theme().overlay());
graphics.fill(x + 2, y + 2, right + 2, bottom + 2, 0x55000000);
graphics.fill(x, y, right, bottom, editorManager.theme().background());
graphics.fill(x, y, right, y + 1, editorManager.theme().border());
graphics.fill(x, bottom - 1, right, bottom, editorManager.theme().border());
graphics.fill(x, y, x + 1, bottom, editorManager.theme().border());
graphics.fill(right - 1, y, right, bottom, editorManager.theme().border());
graphics.text(font, "Choose editor theme", x + PAD, y + 8, editorManager.theme().text(), false);
graphics.fill(x + 1, y + 24, right - 1, y + 25, editorManager.theme().border());
EditorTheme[] themes = EditorTheme.values();
ensureVisible(themes.length);
graphics.enableScissor(x + 1, listTop(), right - 1, listBottom());
int shownRows = Math.min(visibleRows(), themes.length - scroll);
for (int i = 0; i < shownRows; i++) {
int index = scroll + i;
EditorTheme theme = themes[index];
int rowY = listTop() + i * ROW_HEIGHT;
if (index == selected) {
graphics.fill(x + 1, rowY, right - 1, rowY + ROW_HEIGHT, editorManager.theme().selection());
graphics.fill(x + 1, rowY, x + 3, rowY + ROW_HEIGHT, editorManager.theme().accent());
}
EditorTheme.Palette palette = theme.palette();
graphics.fill(x + PAD, rowY + 4, x + PAD + 14, rowY + 13, palette.background());
graphics.fill(x + PAD + 10, rowY + 4, x + PAD + 14, rowY + 8, palette.accent());
String label = theme.displayName() + (theme == editorManager.currentTheme() ? " (current)" : "");
graphics.text(font, label, x + PAD + 22, rowY + 4,
index == selected ? editorManager.theme().text() : editorManager.theme().mutedText(), false);
}
graphics.disableScissor();
String hint = "↑↓ or ←→ select · Enter apply · Esc close";
graphics.text(font, hint, x + PAD, bottom - font.lineHeight - 6, editorManager.theme().hint(), false);
}
@Override
public boolean handleKeyPressed(KeyEvent event) {
int key = event.key();
switch (key) {
case 256 -> close(); // Escape
case 257, 32 -> applySelection(); // Enter or Space
case 265, 263 -> moveSelection(-1); // Up or Left
case 264, 262 -> moveSelection(1); // Down or Right
case 268 -> { selected = 0; ensureVisible(EditorTheme.values().length); previewSelection(); }
case 269 -> { selected = EditorTheme.values().length - 1; ensureVisible(EditorTheme.values().length); previewSelection(); }
default -> { }
}
return true;
}
private void moveSelection(int amount) {
int count = EditorTheme.values().length;
selected = (selected + amount + count) % count;
ensureVisible(count);
previewSelection();
}
private void previewSelection() {
editorManager.previewTheme(EditorTheme.values()[selected]);
}
private void ensureVisible(int count) {
int rows = visibleRows();
if (selected < scroll) scroll = selected;
else if (selected >= scroll + rows) scroll = selected - rows + 1;
scroll = Math.max(0, Math.min(scroll, Math.max(0, count - rows)));
}
private void applySelection() {
editorManager.setTheme(EditorTheme.values()[selected]);
editorManager.closeThemePicker(this, restoreFocus);
}
private void close() {
editorManager.previewTheme(originalTheme);
editorManager.closeThemePicker(this, restoreFocus);
}
@Override public boolean handleCharTyped(CharacterEvent event) { return true; }
@Override
public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
int x = panelX(), y = panelY(), w = panelWidth();
int mx = (int) event.x(), my = (int) event.y();
if (mx < x || mx >= x + w || my < y || my >= y + panelHeight()) {
close();
return true;
}
if (my >= listTop() && my < listBottom()) {
int index = scroll + (my - listTop()) / ROW_HEIGHT;
if (index >= 0 && index < EditorTheme.values().length) {
selected = index;
applySelection();
}
}
return true;
}
@Override public boolean handleMouseDragged(MouseButtonEvent event) { return true; }
@Override public boolean handleMouseReleased(MouseButtonEvent event) { return true; }
@Override
public boolean handleMouseScrolled(double scrollY) {
int maxScroll = Math.max(0, EditorTheme.values().length - visibleRows());
scroll = Math.max(0, Math.min(maxScroll, scroll - (int) Math.signum(scrollY)));
boolean selectionChanged = false;
if (selected < scroll) {
selected = scroll;
selectionChanged = true;
} else if (selected >= scroll + visibleRows()) {
selected = scroll + visibleRows() - 1;
selectionChanged = true;
}
if (selectionChanged) previewSelection();
return true;
}
@Override
public boolean inside(double x, double y) {
// Own the whole screen so clicks outside the dialog dismiss it without
// activating an editor control underneath.
return x >= getStartX() && x <= getEndX() && y >= getStartY() && y <= getEndY();
}
}

View File

@@ -1,5 +1,6 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.editor.EditorPresence;
import net.minecraft.client.gui.Font; import net.minecraft.client.gui.Font;
import net.minecraft.client.gui.GuiGraphicsExtractor; import net.minecraft.client.gui.GuiGraphicsExtractor;
import net.minecraft.client.input.CharacterEvent; import net.minecraft.client.input.CharacterEvent;
@@ -19,29 +20,19 @@ 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); }
static MenuItem separator() { return new MenuItem("", true); } static MenuItem separator() { return new MenuItem("", true); }
} }
private static final String[] TAB_LABELS = { "File", "Edit", "Run" }; private static final String[] TAB_LABELS = { "File", "Edit", "Run", "View", "Help" };
private static final List<List<MenuItem>> TAB_ITEMS = List.of( private static final List<List<MenuItem>> TAB_ITEMS = List.of(
// File // File
List.of( List.of(
MenuItem.item("New File"), MenuItem.item("New File"),
MenuItem.item("Open..."), MenuItem.item("New Folder..."),
MenuItem.item("Save"), MenuItem.item("Save"),
MenuItem.item("Save As..."), MenuItem.item("Save As..."),
MenuItem.separator(), MenuItem.separator(),
@@ -65,6 +56,21 @@ public class EditorTopBar extends Widget {
MenuItem.item("Stop"), MenuItem.item("Stop"),
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Build Project") MenuItem.item("Build Project")
),
// View
List.of(
MenuItem.item("Toggle Sidebar"),
MenuItem.separator(),
MenuItem.item("Split Right"),
MenuItem.item("Split Below"),
MenuItem.separator(),
MenuItem.item("Close Pane"),
MenuItem.separator(),
MenuItem.item("Change theme...")
),
// Help
List.of(
MenuItem.item("Lua API Documentation")
) )
); );
@@ -74,13 +80,43 @@ public class EditorTopBar extends Widget {
/** Mouse position, updated each frame from the screen. */ /** Mouse position, updated each frame from the screen. */
private int mouseX, mouseY; private int mouseX, mouseY;
// ── Shell button ──────────────────────────────────────────────────────
// The one action that deserves to be a button instead of a menu item.
private static final String SHELL_LABEL = ">_ Shell";
private int shellButtonWidth(Font font) { return font.width(SHELL_LABEL) + TAB_PADDING_X * 2 + 2; }
private int shellButtonX0(Font font) { return getEndX() - shellButtonWidth(font); }
private boolean insideShellButton(int mx, int my, Font font) {
return mx >= shellButtonX0(font) && mx < getEndX()
&& my >= getStartY() && my < getStartY() + BAR_HEIGHT;
}
private void drawShellButton(GuiGraphicsExtractor graphics, Font font) {
int x0 = shellButtonX0(font);
int y0 = getStartY();
int y1 = y0 + BAR_HEIGHT;
boolean open = editorManager.isShellOpen();
boolean hovered = insideShellButton(mouseX, mouseY, font);
graphics.fill(x0, y0, getEndX(), y1,
open ? editorManager.theme().activeBackground()
: 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.
if (open) graphics.fill(x0, y1 - 1, getEndX(), y1, editorManager.theme().accent());
}
// ── Drawing ─────────────────────────────────────────────────────────── // ── Drawing ───────────────────────────────────────────────────────────
public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) { public void draw(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY, double delta) {
// 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;
@@ -98,14 +134,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) {
@@ -114,8 +151,45 @@ public class EditorTopBar extends Widget {
tabX = tabEndX; tabX = tabEndX;
} }
drawShellButton(graphics, font);
drawCollaborators(graphics, font);
} }
/**
* Who else is in the file you are looking at, on the right of the bar: a
* coloured dot and a name each, in the colour their caret is drawn in.
* Nothing here means nobody else has this file open.
*/
private void drawCollaborators(GuiGraphicsExtractor graphics, Font font) {
List<EditorPresence> editors = editorManager.collaborators();
if (editors.isEmpty()) return;
List<EditorPresence> shown = editors.size() > MAX_COLLABORATOR_LABELS
? editors.subList(0, MAX_COLLABORATOR_LABELS)
: editors;
String more = editors.size() > shown.size() ? "+" + (editors.size() - shown.size()) : "";
int width = font.width(more);
for (EditorPresence editor : shown) width += font.width(editor.name()) + 13;
// Right-aligned, but never over the menu labels — and leaving the
// shell button its own space at the end of the bar.
int x = Math.max(getStartX() + 120, getEndX() - shellButtonWidth(font) - width);
int y = getStartY() + TAB_PADDING_Y;
for (EditorPresence editor : shown) {
graphics.fill(x, y + 1, x + 3, y + font.lineHeight - 1, editor.color());
graphics.text(font, editor.name(), x + 5, y, editor.color(), false);
x += font.width(editor.name()) + 13;
}
if (!more.isEmpty()) {
graphics.text(font, more, x, y, editorManager.theme().text(), false);
}
}
private static final int MAX_COLLABORATOR_LABELS = 4;
@Override @Override
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
return false; return false;
@@ -127,7 +201,7 @@ public class EditorTopBar extends Widget {
} }
@Override @Override
public boolean handleMouseClicked(MouseButtonEvent event) { public boolean handleMouseClicked(MouseButtonEvent event, boolean doubleClick) {
int button = event.button(); int button = event.button();
double mx = event.x(); double mx = event.x();
double my = event.y(); double my = event.y();
@@ -151,6 +225,13 @@ public class EditorTopBar extends Widget {
tabX = tabEndX; tabX = tabEndX;
} }
// The shell button, at the end of the bar.
if (insideShellButton(imx, imy, font())) {
openTab = -1;
editorManager.toggleShell();
return true;
}
// Click on a dropdown item? // Click on a dropdown item?
if (openTab >= 0) { if (openTab >= 0) {
int result = getClickedItemIndex(imx, imy, openTab); int result = getClickedItemIndex(imx, imy, openTab);
@@ -193,29 +274,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(item),
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;
} }
@@ -231,11 +313,19 @@ public class EditorTopBar extends Widget {
// TODO: wire these to your EditorManager // TODO: wire these to your EditorManager
switch (item.label()) { switch (item.label()) {
case "New File" -> editorManager.newFile(); case "New File" -> editorManager.newFile();
case "New Folder..." -> editorManager.newFolder();
case "Save" -> editorManager.save(); case "Save" -> editorManager.save();
case "Undo" -> editorManager.undo(); case "Undo" -> editorManager.undo();
case "Redo" -> editorManager.redo(); case "Redo" -> editorManager.redo();
case "Find..." -> editorManager.openFind();
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 Below" -> editorManager.splitBelow();
case "Close Pane" -> editorManager.closeActivePane();
case "Lua API Documentation" -> editorManager.openDocs();
case "Change theme..." -> editorManager.openThemePicker();
// 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());
} }
@@ -245,14 +335,20 @@ 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(item)) + TAB_PADDING_X * 2 + 8);
} }
} }
return maxW; return maxW;
} }
private String displayLabel(MenuItem item) {
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++) {
@@ -311,4 +407,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

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

View File

@@ -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"
@@ -64,7 +52,7 @@ public class LuaHighlighter {
private static final Set<String> LIBRARIES = Set.of( private static final Set<String> LIBRARIES = Set.of(
"string", "table", "math", "io", "os", "string", "table", "math", "io", "os",
"coroutine", "package", "utf8", "debug" "coroutine", "package", "utf8", "debug", "world"
); );
// ── Public types ────────────────────────────────────────────────────── // ── Public types ──────────────────────────────────────────────────────
@@ -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,22 @@
package com.aranroig.client.editor;
import java.util.List;
/**
* A named Lua global table that supports member completion after a "." or ":"
* trigger — Lua's own standard libraries ({@code string}, {@code math}, …) and
* the tables codecraft itself injects ({@code world}, {@code events}).
*
* <p>Codecraft's own tables do not implement this by hand: they are generated
* from the Lua API docs catalog by {@link DocLibraries}. To make a new plain
* Lua table's members appear in the autocomplete popup, implement this
* interface and add an instance to {@link CompletionProvider}.</p>
*/
public interface LuaLibrary {
/** The global table name, e.g. {@code "math"} for {@code math.floor}. */
String name();
/** Members offered when the user types {@code name.} in the editor. */
List<CompletionItem> members();
}

View File

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

View File

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

View File

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

View File

@@ -1,17 +1,57 @@
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;
/** True while the left mouse button is held down during a drag-select. */ /** True while the left mouse button is held down during a drag-select. */
public TextEditorScreen() { public TextEditorScreen(EditorManager editorManager) {
super(Component.literal("Codecraft Editor")); super(Component.literal("Codecraft Editor"));
this.editorManager = editorManager;
} }
/**
* Closing the editor leaves the live editing session, so the other players
* stop seeing this caret and stop sending theirs.
*/
@Override
public void onClose() {
editorManager.onEditorClosed(this);
super.onClose();
}
@Override
public boolean keyPressed(KeyEvent event) {
if (event.hasControlDown()) {
if (event.key() == 70 && event.hasShiftDown()) { // Ctrl+Shift+F
editorManager.openSearch(EditorSearchPopup.Mode.PROJECT);
return true;
}
if (event.key() == 80) { // Ctrl+P
editorManager.openSearch(EditorSearchPopup.Mode.FILE);
return true;
}
if (event.key() == 70 && (selectedWidget instanceof EditorFileView || selectedWidget instanceof EditorFindBar)) { // Ctrl+F
editorManager.openFind();
return true;
}
}
if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B
editorManager.toggleSidebar();
return true;
}
return super.keyPressed(event);
}
@Override @Override
public void extractRenderState( public void extractRenderState(
@@ -22,14 +62,16 @@ 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
widget.draw( // pick what the mouse hits. Painting in plain insertion order would let
graphics, // a later-added text-editor pane cover the top bar's dropdown menus, or
mouseX, // cover the docs modal a split pane was added after. List.sort is stable,
mouseY, // so widgets sharing a z-index keep the order they were added in.
delta List<Widget> ordered = new ArrayList<>(widgets);
); ordered.sort(Comparator.comparingInt(Widget::getZIndex));
for (Widget widget : ordered) {
widget.draw(graphics, mouseX, mouseY, delta);
} }
} }
}
}

View File

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

View File

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

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;
@@ -20,15 +29,34 @@ public class SavedProjectData extends SavedData {
} }
public SavedProjectData(List<EditorFile> editorFiles) { public SavedProjectData(List<EditorFile> editorFiles) {
this.editorFiles = editorFiles; // What the codec decodes is an immutable list: writing the project back
// out is fine with it, but while the server runs the project is added to
// — a new file, or one that first appeared as a keystroke — and adding to
// what the codec handed over throws. Keeping a copy of our own is what
// makes `getEditorFiles().add(...)` mean anything.
this.editorFiles = new ArrayList<>(editorFiles);
} }
/**
* The project's files. The list itself is mutable, so a file can be added to
* it; remember to {@link #setEditorFiles(List) set} it or at least
* {@link #markDirty()} when its contents change, or nothing is written out.
*/
public List<EditorFile> getEditorFiles() { public List<EditorFile> getEditorFiles() {
return editorFiles; return editorFiles;
} }
public void setEditorFiles(List<EditorFile> editorFiles) { public void setEditorFiles(List<EditorFile> editorFiles) {
this.editorFiles = editorFiles; this.editorFiles = new ArrayList<>(editorFiles);
setDirty();
}
/**
* Flags the data for saving after a file's contents were changed in place.
* Minecraft only writes it to disk periodically, so this is cheap enough to
* call on every keystroke.
*/
public void markDirty() {
setDirty(); setDirty();
} }
@@ -56,9 +84,9 @@ public class SavedProjectData extends SavedData {
return new SavedProjectData(); // Return a new instance if the level is null. return new SavedProjectData(); // Return a new instance if the level is null.
} }
// The first time the following 'computeIfAbsent' function is called, it creates a new 'SavedBlockData' // The first time the following 'computeIfAbsent' function is called, it creates a new 'SavedProjectData'
// instance and stores it inside the 'DimensionDataStorage'. // instance and stores it inside the 'DimensionDataStorage'.
// Subsequent calls to 'computeIfAbsent' returns the saved 'SavedBlockData' NBT on disk to the Codec in our type, // Subsequent calls to 'computeIfAbsent' returns the saved 'SavedProjectData' NBT on disk to the Codec in our type,
// using the Codec to decode the NBT into our saved data. // using the Codec to decode the NBT into our saved data.
return level.getDataStorage().computeIfAbsent(TYPE); return level.getDataStorage().computeIfAbsent(TYPE);
} }

View File

@@ -0,0 +1,414 @@
package com.aranroig.collab;
import com.aranroig.Codecraft;
import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence;
import com.aranroig.project.ProjectStore;
import com.aranroig.payloads.ClientboundDocumentEditPayload;
import com.aranroig.payloads.ClientboundDocumentStatePayload;
import com.aranroig.payloads.ClientboundEditAckPayload;
import com.aranroig.payloads.ClientboundPresencePayload;
import com.aranroig.payloads.ClientboundRenameFilePayload;
import com.aranroig.payloads.ClientboundSaveCodePayload;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* The server's copy of every document that players have open in the editor, and
* the single authority on what they contain.
*
* <h2>Live editing</h2>
*
* <p>A player who opens the editor is put in a <em>session</em> for the file
* they are looking at. Every keystroke they make arrives as an
* {@link Edit} written against a known version of the document; this class
* rebases it onto the current version — transforming it against the edits that
* landed in the meantime, and never against the sender's own edits, which are
* already in the buffer it was typed into — applies it, and hands it to the
* other players in that file. That is what lets several people type in the same
* file at once without losing each other's work.</p>
*
* <p>Each applied edit bumps the document's version, so every client can tell
* which version it holds. The server keeps the last few edits per document so
* an edit that arrives a little late can still be rebased; when one arrives
* too late for that, its author is simply sent the authoritative document
* again. The same thing happens whenever a client reports (through the ack
* hash) that its copy stopped matching.</p>
*
* <p>Carets are tracked per session too, and every session gets the caret
* positions of the other players, which is what lets the editor draw them.</p>
*
* <h2>Threading</h2>
*
* <p>All of this runs on the server thread: payload handlers and the connection
* events below are dispatched there, so the maps need no locking. 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 {
/** How many applied edits are kept per document for rebasing stale edits. */
private static final int HISTORY_PER_DOCUMENT = 128;
/** Caret colours, picked by player id so a player looks the same everywhere. */
private static final int[] PRESENCE_COLORS = {
0xFF4FC3F7, // light blue
0xFFFF8A65, // orange
0xFFAED581, // green
0xFFF06292, // pink
0xFFBA68C8, // purple
0xFFFFD54F, // amber
0xFF4DB6AC, // teal
0xFFE57373, // red
0xFF90A4AE, // grey
0xFFA1887F, // brown
};
private static final Map<String, Document> DOCUMENTS = new HashMap<>();
/** One entry per player with the editor open, keyed by player id. */
private static final Map<UUID, Session> SESSIONS = new HashMap<>();
private DocumentManager() {
}
/**
* Drops players from their editing sessions when they disconnect and
* throws the cached documents away when the world shuts down. Call once
* from {@link com.aranroig.Codecraft#onInitialize()}.
*/
public static void install() {
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> closeEditor(handler.player));
// Cached text must not outlive the world it came from.
ServerLifecycleEvents.SERVER_STOPPING.register(server -> {
DOCUMENTS.clear();
SESSIONS.clear();
});
}
// ── Sessions ──────────────────────────────────────────────────────────
/**
* Puts {@code player} in the live session of {@code file} and replies with
* its authoritative contents. Their previous file, if any, is dropped.
*/
public static void openDocument(ServerPlayer player, String file) {
MinecraftServer server = server(player);
if (server == null) return;
Session session = SESSIONS.computeIfAbsent(player.getUUID(), id -> new Session(player));
if (!file.equals(session.file)) {
session.file = file;
session.cursor = 0;
session.anchor = -1;
}
Document document = document(file);
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
broadcastPresence(server, file);
sendPresenceSnapshot(player);
}
/** Ends {@code player}'s editing session: called on close and on disconnect. */
public static void closeEditor(ServerPlayer player) {
Session session = SESSIONS.remove(player.getUUID());
if (session == null) return;
MinecraftServer server = server(player);
if (server != null && session.file != null) {
broadcastPresence(server, session.file);
}
}
// ── Document contents ─────────────────────────────────────────────────
/**
* Applies one of {@code player}'s keystrokes. The edit was written against
* version {@code baseVersion}; if the document moved on since then the edit
* is rebased onto what happened in between first.
*/
public static void applyEdit(ServerPlayer player, String file, int baseVersion, Edit edit) {
MinecraftServer server = server(player);
if (server == null) return;
Document document = document(file);
// Never take the client's word for who wrote an edit: rebasing skips
// the sender's own edits, so a spoofed author would apply one twice.
Edit applied = new Edit(player.getUUID(), edit.seq(), edit.components());
if (baseVersion > document.version || baseVersion < document.oldestRebaseVersion()) {
// Too far behind to rebase this edit without guessing: give the
// player the real document and let them retype on top of it.
ServerPlayNetworking.send(player, new ClientboundDocumentStatePayload(file, document.text, document.version));
return;
}
for (int version = baseVersion + 1; version <= document.version; version++) {
Edit earlier = document.appliedAt(version);
if (earlier == null) break;
if (earlier.author().equals(player.getUUID())) continue;
applied = applied.transformAgainst(earlier);
}
document.apply(applied);
boolean brandNew = ProjectStore.scheduleWrite(file, document.text);
ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
broadcastEdit(server, player.getUUID(), file, document.version, applied);
// A file nobody had saved yet came into the project with this keystroke,
// and the editors of it are the only ones the edit above reaches: tell
// everybody else the project has one more file.
if (brandNew) broadcastProjectFile(server, player, file, document.text);
}
/**
* Writes {@code text} over {@code file} as one edit (the explicit Save).
* Going through an edit rather than storing the buffer directly is what
* keeps the other editors converging instead of being clobbered, and it
* trims the parts both versions agree on so the change stays small.
*/
public static void replaceDocument(ServerPlayer player, String file, String text) {
MinecraftServer server = server(player);
if (server == null) return;
Document document = document(file);
String current = document.text;
if (current.equals(text)) {
// Nothing changed, but the player asked to save: the file still
// has to exist on disk (a brand-new file is saved before it has
// any edits flowing), and confirm the version they are on so they
// can check their copy against it.
ProjectStore.write(file, current);
ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, current.hashCode(), current.length()));
} else {
int prefix = commonPrefix(current, text);
int suffix = commonSuffix(current, text, prefix);
Edit edit = Edit.replace(player.getUUID(), document.nextSequence(),
prefix, current.length() - prefix - suffix, text.substring(prefix, text.length() - suffix));
// A whole-file save states what the file should contain, so it is
// applied to the server's current text instead of being rebased.
document.apply(edit);
ProjectStore.write(file, document.text);
ServerPlayNetworking.send(player,
new ClientboundEditAckPayload(file, document.version, document.text.hashCode(), document.text.length()));
broadcastEdit(server, player.getUUID(), file, document.version, edit);
}
// Saving is also how a file says it exists: the other editors add it to
// their sidebars, and the ones not looking at it are not left holding a
// copy a save behind.
broadcastProjectFile(server, player, file, document.text);
}
/**
* Moves {@code oldName} to {@code newName} everywhere the server knows it:
* on disk and in the write queue, in the cached document and in the
* sessions of everyone editing it — and the other editors' file lists are
* told. A name the project already holds is refused.
*/
public static void renameFile(ServerPlayer player, String oldName, String newName) {
MinecraftServer server = server(player);
if (server == null || oldName.equals(newName)) return;
if (ProjectStore.exists(newName)) return; // the name is taken
ProjectStore.rename(oldName, newName);
// The live document keeps its version history under the new name, so
// the editors of the file can carry on without refetching anything.
Document document = DOCUMENTS.remove(oldName);
if (document != null) DOCUMENTS.put(newName, document);
for (Session session : SESSIONS.values()) {
if (oldName.equals(session.file)) session.file = newName;
}
// Nobody is in the old name any more, and the new one holds them all.
broadcastPresence(server, oldName);
broadcastPresence(server, newName);
for (ServerPlayer other : server.getPlayerList().getPlayers()) {
if (other != player) {
ServerPlayNetworking.send(other, new ClientboundRenameFilePayload(oldName, newName));
}
}
}
// ── Carets ────────────────────────────────────────────────────────────
/** Records where {@code player}'s caret is in {@code file} and tells everyone. */
public static void updateCursor(ServerPlayer player, String file, int cursor, int anchor) {
Session session = SESSIONS.get(player.getUUID());
if (session == null || !file.equals(session.file)) return;
MinecraftServer server = server(player);
if (server == null) return;
session.cursor = Math.max(0, cursor);
session.anchor = anchor;
broadcastPresence(server, file);
}
// ── Internals ─────────────────────────────────────────────────────────
private static Document document(String file) {
Document document = DOCUMENTS.get(file);
if (document == null) {
String text = ProjectStore.read(file);
document = new Document(text == null ? "" : text);
DOCUMENTS.put(file, document);
}
return document;
}
/**
* Tells every editor but {@code author} that the project holds {@code file}
* with {@code text}. It is how one player's new file turns into a row in the
* others' sidebars, and what keeps a client that is not looking at the file
* from holding a copy a save behind.
*/
private static void broadcastProjectFile(MinecraftServer server, ServerPlayer author, String file, String text) {
for (ServerPlayer other : server.getPlayerList().getPlayers()) {
if (other == author) continue;
ServerPlayNetworking.send(other, new ClientboundSaveCodePayload(new EditorFile(file, text)));
}
}
private static void broadcastEdit(MinecraftServer server, UUID author, String file, int version, Edit edit) {
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
if (entry.getKey().equals(author) || !file.equals(entry.getValue().file)) continue;
ServerPlayNetworking.send(entry.getValue().player, new ClientboundDocumentEditPayload(file, version, edit));
}
}
/** Re-sends the carets of everyone in {@code file} to every open editor. */
private static void broadcastPresence(MinecraftServer server, String file) {
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
if (entry.getValue().file == null) continue;
sendPresence(entry.getValue().player, file, presenceIn(file, entry.getKey()));
}
}
/** Brings a player up to date with everywhere somebody is already editing. */
private static void sendPresenceSnapshot(ServerPlayer player) {
UUID self = player.getUUID();
List<String> files = new ArrayList<>();
for (Session session : SESSIONS.values()) {
if (session.file != null && !files.contains(session.file)) files.add(session.file);
}
for (String file : files) {
sendPresence(player, file, presenceIn(file, self));
}
}
private static void sendPresence(ServerPlayer to, String file, List<EditorPresence> editors) {
ServerPlayNetworking.send(to, new ClientboundPresencePayload(file, editors));
}
private static List<EditorPresence> presenceIn(String file, UUID exclude) {
List<EditorPresence> editors = new ArrayList<>();
for (Map.Entry<UUID, Session> entry : SESSIONS.entrySet()) {
Session session = entry.getValue();
if (entry.getKey().equals(exclude) || !file.equals(session.file)) continue;
editors.add(new EditorPresence(entry.getKey(), session.player.getScoreboardName(),
session.color, session.cursor, session.anchor));
}
return editors;
}
private static MinecraftServer server(ServerPlayer player) {
return player.level().getServer();
}
private static int commonPrefix(String left, String right) {
int max = Math.min(left.length(), right.length());
int i = 0;
while (i < max && left.charAt(i) == right.charAt(i)) i++;
return i;
}
private static int commonSuffix(String left, String right, int prefix) {
int max = Math.min(left.length(), right.length()) - prefix;
int i = 0;
while (i < max && left.charAt(left.length() - 1 - i) == right.charAt(right.length() - 1 - i)) i++;
return i;
}
// ── State ─────────────────────────────────────────────────────────────
/** The server's copy of one document, with the edits that produced it. */
private static final class Document {
private String text;
private int version;
/** Applied edits, oldest first; {@code history.get(0)} is version {@code firstRetainedVersion}. */
private final List<Edit> history = new ArrayList<>();
private int firstRetainedVersion = 1;
private Document(String text) {
this.text = text;
}
private void apply(Edit edit) {
text = edit.apply(text);
version++;
if (history.size() == HISTORY_PER_DOCUMENT) {
history.remove(0);
firstRetainedVersion++;
}
history.add(edit);
}
/** The edit that took the document to {@code targetVersion}, or null once forgotten. */
private Edit appliedAt(int targetVersion) {
int index = targetVersion - firstRetainedVersion;
if (index < 0 || index >= history.size()) return null;
return history.get(index);
}
/** Oldest base version that can still be rebased onto this document. */
private int oldestRebaseVersion() {
return firstRetainedVersion - 1;
}
private long nextSequence() {
return version + 1L;
}
}
/** One player with the editor open, and where they are pointing. */
private static final class Session {
private final ServerPlayer player;
private final int color;
private String file;
private int cursor;
private int anchor = -1;
private Session(ServerPlayer player) {
this.player = player;
this.color = PRESENCE_COLORS[Math.floorMod(player.getUUID().hashCode(), PRESENCE_COLORS.length)];
}
}
}

View File

@@ -0,0 +1,10 @@
package com.aranroig.docs;
/**
* A titled Lua snippet shown in the in-game documentation.
*
* @param title one-line caption, may be empty
* @param code the snippet, lines separated by {@code \n}
*/
public record ExampleDoc(String title, String code) {
}

View File

@@ -0,0 +1,25 @@
package com.aranroig.docs;
import java.util.List;
/**
* A single documented Lua function.
*
* @param name full dotted name, e.g. {@code "world.set_block"}
* @param signature the call as the player would read it, e.g. {@code world.set_block(x, y, z, block)}
* @param summary one or two sentences on what it does; {@code \n} separates paragraphs
* @param params positional parameters (empty for variadic helpers)
* @param returns what the call evaluates to
* @param notes gotchas, failure reasons, tips — each entry is one bullet
* @param examples runnable snippets
*/
public record FunctionDoc(
String name,
String signature,
String summary,
List<ParamDoc> params,
String returns,
List<String> notes,
List<ExampleDoc> examples
) {
}

View File

@@ -0,0 +1,126 @@
package com.aranroig.docs;
import com.aranroig.Codecraft;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* The in-game reference for every Lua global this mod exposes to user scripts.
*
* <p>The catalog is data, not code: it lives in
* {@code src/main/resources/data/codecraft/docs/lua-api.json} and is loaded from
* the mod resources on first access, so documentation can be edited (and, once
* packed, overridden) without touching Java. It describes the functions
* registered by the wrappers in {@code com.aranroig.wrapper} (including
* {@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
* reads it to render the browsable documentation panel, so it is the single
* source of truth shown to players.</p>
*
* <p>Keep it in sync with the wrapper implementations and {@code docs/lua-api.md}.</p>
*/
public final class LuaApiDocs {
/** Location of the catalog inside the mod resources. */
private static final String RESOURCE = "/data/codecraft/docs/lua-api.json";
private static List<Topic> cache;
private LuaApiDocs() {
}
/** All documented topics, in display order. */
public static synchronized List<Topic> topics() {
if (cache == null) {
cache = load();
}
return cache;
}
/** Flattened list of every documented function, across all topics. */
public static List<FunctionDoc> functions() {
return topics().stream().flatMap(t -> t.functions().stream()).toList();
}
// ── Loading ───────────────────────────────────────────────────────────
private static List<Topic> load() {
try (InputStream in = LuaApiDocs.class.getResourceAsStream(RESOURCE)) {
if (in == null) {
Codecraft.LOGGER.error("Lua API docs resource not found at {}", RESOURCE);
return List.of();
}
return parse(JsonParser.parseReader(
new InputStreamReader(in, StandardCharsets.UTF_8)).getAsJsonObject());
} catch (Exception e) {
Codecraft.LOGGER.error("Failed to load Lua API docs from {}", RESOURCE, e);
return List.of();
}
}
private static List<Topic> parse(JsonObject root) {
List<Topic> topics = new ArrayList<>();
for (JsonElement t : optArray(root, "topics")) {
JsonObject topic = t.getAsJsonObject();
List<FunctionDoc> functions = new ArrayList<>();
for (JsonElement f : optArray(topic, "functions")) {
functions.add(readFunction(f.getAsJsonObject()));
}
topics.add(new Topic(
str(topic, "title"),
str(topic, "blurb"),
List.copyOf(functions)));
}
return List.copyOf(topics);
}
private static FunctionDoc readFunction(JsonObject f) {
List<ParamDoc> params = new ArrayList<>();
for (JsonElement p : optArray(f, "params")) {
JsonObject param = p.getAsJsonObject();
params.add(new ParamDoc(
str(param, "name"),
str(param, "type"),
param.has("optional") && param.get("optional").getAsBoolean(),
str(param, "description")));
}
List<String> notes = new ArrayList<>();
for (JsonElement n : optArray(f, "notes")) {
notes.add(n.getAsString());
}
List<ExampleDoc> examples = new ArrayList<>();
for (JsonElement e : optArray(f, "examples")) {
JsonObject example = e.getAsJsonObject();
examples.add(new ExampleDoc(
str(example, "title"),
str(example, "code")));
}
return new FunctionDoc(
str(f, "name"),
str(f, "signature"),
str(f, "summary"),
List.copyOf(params),
str(f, "returns"),
List.copyOf(notes),
List.copyOf(examples));
}
private static String str(JsonObject object, String key) {
JsonElement value = object.get(key);
return value == null || value.isJsonNull() ? "" : value.getAsString();
}
private static JsonArray optArray(JsonObject object, String key) {
JsonElement value = object.get(key);
return value != null && value.isJsonArray() ? value.getAsJsonArray() : new JsonArray();
}
}

View File

@@ -0,0 +1,12 @@
package com.aranroig.docs;
/**
* One parameter of a documented Lua function.
*
* @param name parameter name as written in the signature, e.g. {@code "block"}
* @param type short type name shown to the user, e.g. {@code "string"} or {@code "number"}
* @param optional whether the parameter may be omitted
* @param description what the parameter means
*/
public record ParamDoc(String name, String type, boolean optional, String description) {
}

View File

@@ -0,0 +1,14 @@
package com.aranroig.docs;
import java.util.List;
/**
* Top-level grouping shown in the left-hand list of the in-game docs panel,
* e.g. the {@code world} table or the {@code print} helper.
*
* @param title short header, usually the Lua table name
* @param blurb one or two sentences describing the group; {@code \n} separates paragraphs
* @param functions the functions this topic documents
*/
public record Topic(String title, String blurb, List<FunctionDoc> functions) {
}

View File

@@ -0,0 +1,370 @@
package com.aranroig.editor;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.UUID;
/**
* A character-level change to a document: a walk over the text saying which
* characters to keep ({@link Retain}), which to remove ({@link Delete}) and what
* to write ({@link Insert}). Anything the walk does not mention is left alone.
*
* <p>Describing a change this way, instead of as one "replace this range with
* that text", is what makes shared editing possible. Two players can write
* against the same version of a file at the same time; before such a change is
* used anywhere other than where it was written it is <em>transformed</em>
* against the changes that went in first ({@link #transformAgainst(Edit)},
* {@link #transformPair(Edit, Edit)}), which re-expresses it against the text it
* is about to meet. Deleting around somebody else's freshly typed text, typing
* inside a selection they are throwing away, both merge instead of one of the
* two losing.</p>
*
* <p>{@code author} and {@code seq} survive every transform. They give two
* inserts at the same offset a total order, so every player ends up with the
* characters in the same sequence, and they tell the server which edits came
* from the sender itself (those are already in the buffer the sender typed
* into, so the server must not apply them twice).</p>
*/
public record Edit(UUID author, long seq, List<Edit.Component> components) {
/** One step of the walk over a document. */
public sealed interface Component permits Retain, Insert, Delete {
}
/** Keep {@code count} characters of the document as they are. */
public record Retain(int count) implements Component {
}
/** Write {@code text} at this point of the document. */
public record Insert(String text) implements Component {
}
/** Remove {@code count} characters from the document. */
public record Delete(int count) implements Component {
}
private static final StreamCodec<RegistryFriendlyByteBuf, Component> COMPONENT_CODEC = new StreamCodec<>() {
@Override
public Component decode(RegistryFriendlyByteBuf buf) {
return switch (buf.readByte()) {
case 1 -> new Insert(ByteBufCodecs.STRING_UTF8.decode(buf));
case 2 -> new Delete(ByteBufCodecs.VAR_INT.decode(buf));
default -> new Retain(ByteBufCodecs.VAR_INT.decode(buf));
};
}
@Override
public void encode(RegistryFriendlyByteBuf buf, Component component) {
if (component instanceof Insert insert) {
buf.writeByte(1);
ByteBufCodecs.STRING_UTF8.encode(buf, insert.text());
} else if (component instanceof Delete delete) {
buf.writeByte(2);
ByteBufCodecs.VAR_INT.encode(buf, delete.count());
} else {
buf.writeByte(0);
ByteBufCodecs.VAR_INT.encode(buf, ((Retain) component).count());
}
}
};
public static final StreamCodec<RegistryFriendlyByteBuf, Edit> STREAM_CODEC =
StreamCodec.composite(
UUIDUtil.STREAM_CODEC,
Edit::author,
ByteBufCodecs.VAR_LONG,
Edit::seq,
COMPONENT_CODEC.apply(ByteBufCodecs.list()),
Edit::components,
Edit::new
);
// ── Building edits ────────────────────────────────────────────────────
/** A change that leaves the document as it is. */
public static Edit none(UUID author, long seq) {
return new Edit(author, seq, List.of());
}
/** {@code text} written at {@code position}, nothing removed. */
public static Edit insertion(UUID author, long seq, int position, String text) {
return replace(author, seq, position, 0, text);
}
/** {@code count} characters removed at {@code position}, nothing written back. */
public static Edit deletion(UUID author, long seq, int position, int count) {
return replace(author, seq, position, count, "");
}
/**
* The shape the text editor produces with every keystroke: remove
* {@code deleteLength} characters at {@code position} and write
* {@code insert} there.
*/
public static Edit replace(UUID author, long seq, int position, int deleteLength, String insert) {
List<Component> components = new ArrayList<>(3);
if (position > 0) components.add(new Retain(position));
if (deleteLength > 0) components.add(new Delete(deleteLength));
if (!insert.isEmpty()) components.add(new Insert(insert));
return new Edit(author, seq, components);
}
public boolean isEmpty() {
for (Component component : components) {
if (component instanceof Insert || component instanceof Delete) return false;
}
return true;
}
/** How many characters of the document this edit reads; 0 for a pure insert. */
public int baseLength() {
int total = 0;
for (Component component : components) {
if (component instanceof Retain retain) total += retain.count();
else if (component instanceof Delete delete) total += delete.count();
}
return total;
}
// ── Applying ──────────────────────────────────────────────────────────
/**
* Runs this edit over {@code base}. Counts that do not fit the text are
* clamped rather than thrown at: a document that stopped matching its
* version is repaired by resyncing, not by crashing the editor.
*/
public String apply(String base) {
if (isEmpty()) return base;
StringBuilder result = new StringBuilder(base.length());
int index = 0;
for (Component component : components) {
if (component instanceof Retain retain) {
int count = Math.min(retain.count(), base.length() - index);
if (count <= 0) break;
result.append(base, index, index + count);
index += count;
} else if (component instanceof Delete delete) {
int count = Math.min(delete.count(), base.length() - index);
if (count <= 0) break;
index += count;
} else if (component instanceof Insert insert) {
result.append(insert.text());
}
}
if (index < base.length()) result.append(base, index, base.length());
return result.toString();
}
/**
* Where a caret at {@code caret} ends up once this edit is applied: text
* inserted before it pushes it along, text deleted around it collapses it
* onto the deletion point. Text inserted at the caret's own offset goes in
* front of it, which is where the editor expects its own typing to land.
*/
public int shiftPosition(int caret) {
int read = 0; // how far into the base document the walk has got
int written = 0;
for (Component component : components) {
if (read >= caret) break;
if (component instanceof Retain retain) {
int count = Math.min(retain.count(), caret - read);
read += count;
written += count;
} else if (component instanceof Delete delete) {
read += Math.min(delete.count(), caret - read);
// written does not move: the caret collapses onto the deletion
} else if (component instanceof Insert insert) {
written += insert.text().length();
}
}
return written;
}
// ── Undoing ───────────────────────────────────────────────────────────
/**
* The walk that takes this one back: run it over the text this edit
* produced and the earlier text comes out again. Removals become writes
* of exactly what was removed — which is why the text the edit ran over
* has to be at hand — and writes become removals of the same length.
* {@code base} is the text this edit was applied to, and counts that do
* not fit it are clamped the same way {@link #apply} clamps them.
*/
public Edit invert(String base) {
List<Component> inverse = new ArrayList<>(components.size());
int index = 0;
for (Component component : components) {
if (component instanceof Retain retain) {
int count = Math.min(retain.count(), base.length() - index);
if (count <= 0) break;
add(inverse, new Retain(count));
index += count;
} else if (component instanceof Delete delete) {
int count = Math.min(delete.count(), base.length() - index);
if (count <= 0) break;
add(inverse, new Insert(base.substring(index, index + count)));
index += count;
} else if (component instanceof Insert insert) {
add(inverse, new Delete(insert.text().length()));
}
}
return new Edit(author, seq, inverse);
}
// ── Transforming ──────────────────────────────────────────────────────
/**
* This edit re-expressed against a document that already contains
* {@code other}. Both are assumed to have been written against the same
* base document; applying the result after {@code other} has the effect this
* edit was meant to have there.
*/
public Edit transformAgainst(Edit other) {
return transformPair(this, other)[0];
}
/**
* Both edits expressed against each other's result: returns
* {@code [this↑other, other↑this]}. Applying {@code this↑other} after
* {@code other} gives the same document as applying {@code other↑this}
* after {@code this}, which is what every player's copy converging on
* rests upon.
*/
public static Edit[] transformPair(Edit left, Edit right) {
List<Component> leftResult = new ArrayList<>();
List<Component> rightResult = new ArrayList<>();
Deque<Component> leftOp = new ArrayDeque<>(left.components());
Deque<Component> rightOp = new ArrayDeque<>(right.components());
while (!leftOp.isEmpty() || !rightOp.isEmpty()) {
// Whichever edit ran out says nothing about what is left of the
// document, which is the same as keeping it.
Component l = leftOp.peekFirst();
Component r = rightOp.peekFirst();
boolean lVirtual = l == null;
boolean rVirtual = r == null;
if (l == null) l = new Retain(remaining(r));
if (r == null) r = new Retain(remaining(l));
if (l instanceof Insert lInsert && !(r instanceof Insert)) {
// Our text goes in before whatever the other edit does next. An
// insert is never swallowed by a concurrent deletion.
add(leftResult, lInsert);
add(rightResult, new Retain(lInsert.text().length()));
leftOp.pollFirst();
continue;
}
if (r instanceof Insert rInsert && !(l instanceof Insert)) {
add(rightResult, rInsert);
add(leftResult, new Retain(rInsert.text().length()));
rightOp.pollFirst();
continue;
}
if (l instanceof Insert lInsert && r instanceof Insert rInsert) {
// Two players typed at the same offset: authorship decides who
// ends up in front, the same way round in both directions.
if (left.precedes(right)) {
add(leftResult, lInsert);
add(rightResult, new Retain(lInsert.text().length()));
leftOp.pollFirst();
} else {
add(rightResult, rInsert);
add(leftResult, new Retain(rInsert.text().length()));
rightOp.pollFirst();
}
continue;
}
// Neither side writes text here: both steps cover the same stretch
// of the original document.
int count = Math.min(remaining(l), remaining(r));
boolean lDeletes = l instanceof Delete;
boolean rDeletes = r instanceof Delete;
if (lDeletes && !rDeletes) add(leftResult, new Delete(count)); // they deleted it; we still want it gone
else if (rDeletes && !lDeletes) add(rightResult, new Delete(count));
else if (!lDeletes && !rDeletes) {
add(leftResult, new Retain(count));
add(rightResult, new Retain(count));
}
// Both deleting: the characters are gone either way, nothing to say.
consume(leftOp, count, lVirtual);
consume(rightOp, count, rVirtual);
}
return new Edit[]{
new Edit(left.author, left.seq, leftResult),
new Edit(right.author, right.seq, rightResult),
};
}
/** Collects a component, merging it into the previous one where possible. */
private static void add(List<Component> components, Component component) {
if (component instanceof Retain retain && retain.count() == 0) return;
if (component instanceof Delete delete && delete.count() == 0) return;
if (component instanceof Insert insert && insert.text().isEmpty()) return;
int last = components.size() - 1;
if (last >= 0) {
Component previous = components.get(last);
if (previous instanceof Retain a && component instanceof Retain b) {
components.set(last, new Retain(a.count() + b.count()));
return;
}
if (previous instanceof Delete a && component instanceof Delete b) {
components.set(last, new Delete(a.count() + b.count()));
return;
}
if (previous instanceof Insert a && component instanceof Insert b) {
components.set(last, new Insert(a.text() + b.text()));
return;
}
}
components.add(component);
}
/** Characters a step covers: for inserts, the length of the text written. */
private static int remaining(Component component) {
if (component instanceof Retain retain) return retain.count();
if (component instanceof Delete delete) return delete.count();
return ((Insert) component).text().length();
}
/** Advances a walk by {@code count} characters, splitting the step it lands in. */
private static void consume(Deque<Component> components, int count, boolean virtual) {
if (virtual) return; // nothing there to advance; it is re-derived next round
Component head = components.pollFirst();
int left = remaining(head) - count;
if (left > 0) {
components.addFirst(head instanceof Retain ? new Retain(left) : new Delete(left));
}
}
/**
* Total order over two edits, used only to decide which of two inserts at
* the same offset comes first. It deliberately ignores positions, so it
* still says the same thing after both have been transformed.
*/
public boolean precedes(Edit other) {
int byAuthor = author.compareTo(other.author);
if (byAuthor != 0) return byAuthor < 0;
return seq < other.seq;
}
}

View File

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

View File

@@ -0,0 +1,43 @@
package com.aranroig.editor;
import net.minecraft.core.UUIDUtil;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import java.util.UUID;
/**
* Where one player is pointing inside a document they have open in the editor.
*
* <p>Offsets are character offsets into the document, the same coordinates the
* text editor uses for its own caret ({@code EditorFileView#cursorPos}), so a
* remote caret can be drawn with the same offset-to-pixel maths as the local
* one. {@code anchor} is {@code -1} when nothing is selected.</p>
*/
public record EditorPresence(UUID playerId, String name, int color, int cursor, int anchor) {
public static final StreamCodec<RegistryFriendlyByteBuf, EditorPresence> STREAM_CODEC =
StreamCodec.composite(
UUIDUtil.STREAM_CODEC,
EditorPresence::playerId,
ByteBufCodecs.STRING_UTF8,
EditorPresence::name,
ByteBufCodecs.VAR_INT,
EditorPresence::color,
ByteBufCodecs.VAR_INT,
EditorPresence::cursor,
ByteBufCodecs.VAR_INT,
EditorPresence::anchor,
EditorPresence::new
);
public boolean hasSelection() {
return anchor >= 0 && anchor != cursor;
}
}

View File

@@ -0,0 +1,55 @@
package com.aranroig.editor;
/**
* The name of a project file is the path it lives at: {@code lib/gui/theme},
* with '/' between the folders and no extension on the end. Nothing else has to
* know how a name is spelled — to the server it is only a key — so the sidebar
* can read the folders straight out of it instead of keeping a second structure
* that could end up disagreeing with the files it shows.
*/
public final class ProjectPath {
public static final char SEPARATOR = '/';
/** The file a run executes: the one called {@code main}, at the root of the project. */
public static final String ENTRYPOINT = "main";
/** Names written before files dropped the extension are still shown without it. */
public static final String LEGACY_EXTENSION = ".lua";
private ProjectPath() {
}
/**
* The folders in front of the file, without a trailing slash. Empty when the
* file sits at the root of the project, which is the same folder key the
* sidebar uses for everything not inside a folder.
*/
public static String folderOf(String path) {
int separator = path.lastIndexOf(SEPARATOR);
return separator < 0 ? "" : path.substring(0, separator);
}
/** The last segment of a path: the name of the file or folder itself. */
public static String nameOf(String path) {
int separator = path.lastIndexOf(SEPARATOR);
return separator < 0 ? path : path.substring(separator + 1);
}
/** The last segment without its extension: what the sidebar shows as a label. */
public static String displayNameOf(String path) {
return withoutExtension(nameOf(path));
}
/** Drops a trailing {@code .lua}. New names are written without one. */
public static String withoutExtension(String name) {
return name.endsWith(LEGACY_EXTENSION)
? name.substring(0, name.length() - LEGACY_EXTENSION.length())
: name;
}
/** Joins a folder and a name into a path. The folder may be the project root. */
public static String resolve(String folder, String name) {
return folder.isEmpty() ? name : folder + SEPARATOR + name;
}
}

View File

@@ -0,0 +1,55 @@
package com.aranroig.listeners;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
/**
* The {@code events} table given to user scripts for registering listeners.
*
* <p>Registers one {@code events.on_<name>(callback)} function per
* {@link GameEvent} onto a script's {@link Lua} state. Calling one stores the
* callback on the owning {@link ScriptRuntime}; it then fires whenever the game
* event happens, until the script is rerun (which resets the runtime) or the
* player disconnects.</p>
*
* <p>The argument handling mirrors {@link com.aranroig.wrapper.WorldApi}:
* misuse returns {@code false} followed by a reason so callers can write
* {@code if not events.on_...(...) then ... end}. A passed function value is
* captured directly — luajava pops JFunction arguments with {@link Lua#get()},
* which for a function yields a registry reference that stays valid while the
* state is open, so it can be called after the script has finished running.</p>
*/
public final class EventsApi {
private EventsApi() {
}
/**
* Registers the global {@code events} table on the script's Lua state.
*
* @param lua state to register on
* @param runtime the runtime that owns the state and stores the callbacks
*/
public static void register(Lua lua, ScriptRuntime runtime) {
lua.newTable();
int events = lua.getTop();
for (GameEvent event : GameEvent.values()) {
registerOne(lua, events, runtime, event);
}
lua.setGlobal("events");
}
private static void registerOne(Lua lua, int table, ScriptRuntime runtime, GameEvent event) {
String function = event.luaFunction();
lua.push((L, args) -> {
if (args.length < 1 || args[0].type() != Lua.LuaType.FUNCTION) {
return new LuaValue[]{ lua.from(false), lua.from("usage: events." + function + "(callback)") };
}
runtime.addListener(event, args[0]);
return new LuaValue[]{ lua.from(true) };
});
lua.setField(table, function);
}
}

View File

@@ -0,0 +1,49 @@
package com.aranroig.listeners;
/**
* The game events a Lua script can subscribe to with the {@code events} table.
*
* <p>The enum name is turned into the Lua registration function by
* {@link EventsApi}: {@link #USE_ITEM} becomes {@code events.on_use_item(fn)}
* and is the key a callback is stored under in {@link ScriptRuntime}. Keeping
* the names here means {@link EventsApi} (which registers the Lua functions)
* and {@link ScriptRuntimeManager} (which fires them from Fabric hooks) cannot
* drift apart.</p>
*/
public enum GameEvent {
/** Fires when a player right-clicks to use the item in their hand. */
USE_ITEM("use_item"),
/** Fires after a player has broken a block. */
BREAK_BLOCK("break_block"),
/** Fires when a player sends a chat message. */
CHAT("chat"),
/** Fires when a player finishes joining the game. */
PLAYER_JOIN("player_join"),
/** Fires when a player leaves the game. */
PLAYER_LEAVE("player_leave"),
/** Fires once per server tick, at the end of the tick. */
TICK("tick");
/** Suffix used after {@code on_} for the Lua-facing function name. */
private final String key;
GameEvent(String key) {
this.key = key;
}
/** {@code "use_item"} for {@link #USE_ITEM}; used as the listener-map key. */
public String key() {
return key;
}
/** The Lua function a player writes to subscribe, e.g. {@code on_use_item}. */
public String luaFunction() {
return "on_" + key;
}
}

View File

@@ -0,0 +1,119 @@
package com.aranroig.listeners;
import com.aranroig.Codecraft;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* One running Lua script and the game-event listeners it registered.
*
* <p>A runtime is created fresh every time a player presses <em>Run Script</em>
* (see {@link ScriptRuntimeManager#startRun(ServerPlayer)}) and lives until the
* player runs the script again — which replaces it — or disconnects. It owns the
* {@link Lua} state that {@code events.on_*(fn)} callbacks close over, so those
* callbacks are only valid while this runtime is alive; {@link #stop()} closes
* the state and releases them.</p>
*
* <h2>Why callbacks survive the script finishing</h2>
*
* <p>When Lua calls a Java function, luajava pops each argument with
* {@link Lua#get()}; for a function argument that returns a registry-backed
* {@link LuaValue} ({@code RefLuaValue}). Holding a strong Java reference to it
* (which the listener list below does) keeps it alive, and calling it later with
* {@link LuaValue#call(Object...)} re-pushes it from the registry and
* {@code pcall}s it. That reference dies as soon as the {@link Lua} state is
* closed, which is exactly the reset behaviour we want on a rerun.</p>
*
* <p>All methods run on the server thread — payload handling and every game
* event this bridges are server-thread — so there is no locking.</p>
*/
public final class ScriptRuntime {
private final Lua lua;
private final ServerPlayer owner;
private final Map<GameEvent, List<LuaValue>> listeners = new EnumMap<>(GameEvent.class);
ScriptRuntime(Lua lua, ServerPlayer owner) {
this.lua = lua;
this.owner = owner;
}
/** The Lua state to run the entrypoint on; globals are already registered. */
public Lua lua() {
return lua;
}
/** Runs the entrypoint. Errors are left to the caller to report to the player. */
public void run(String script) {
lua.run(script);
}
/**
* Registers one Lua callback for an event.
*
* <p>The value must be a function; the caller ({@link EventsApi}) checks
* that before handing it over. The reference is stored as-is and stays valid
* until {@link #stop()} closes the state.</p>
*/
void addListener(GameEvent event, LuaValue callback) {
listeners.computeIfAbsent(event, e -> new ArrayList<>()).add(callback);
}
/** Whether any script under this runtime listens for {@code event}. */
boolean hasListeners(GameEvent event) {
List<LuaValue> list = listeners.get(event);
return list != null && !list.isEmpty();
}
/**
* Fires every callback registered for {@code event}, passing {@code args}
* (Java strings/numbers converted to Lua scalars) positionally.
*
* <p>Iterates a snapshot so a callback may itself call {@code events.on_*}
* without disturbing this loop. A callback that throws is reported to the
* owner and logged, and the remaining callbacks still run — one bad listener
* never breaks the game loop or the others.</p>
*/
void dispatch(GameEvent event, Object... args) {
List<LuaValue> list = listeners.get(event);
if (list == null || list.isEmpty()) {
return;
}
for (LuaValue callback : List.copyOf(list)) {
try {
callback.call(args);
} catch (Throwable t) {
Codecraft.LOGGER.warn("Error in events." + event.luaFunction() + " callback", t);
reportError("events." + event.luaFunction() + ": " + t.getMessage());
}
}
}
/** Sends an error line to the owner's chat, if they are still connected. */
void reportError(String message) {
if (owner != null && !owner.hasDisconnected()) {
owner.sendSystemMessage(Component.literal("§ccodecraft error: " + message));
}
}
/**
* Releases the script: empties the listener list and closes the Lua state,
* which invalidates every callback that was stored. Called on rerun (before
* the replacement runtime is installed) and on disconnect.
*/
void stop() {
listeners.clear();
try {
lua.close();
} catch (RuntimeException e) {
Codecraft.LOGGER.warn("Error closing Lua state", e);
}
}
}

View File

@@ -0,0 +1,196 @@
package com.aranroig.listeners;
import com.aranroig.wrapper.ChatLogger;
import com.aranroig.wrapper.ServerCommandApi;
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.ServerTickEvents;
import net.fabricmc.fabric.api.event.player.PlayerBlockBreakEvents;
import net.fabricmc.fabric.api.event.player.UseItemCallback;
import net.fabricmc.fabric.api.message.v1.ServerMessageEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.network.chat.PlayerChatMessage;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.state.BlockState;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.luaj.LuaJ;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* The server-side owner of every running script and of the {@code events}
* listeners they register.
*
* <p>There is one {@link ScriptRuntime} per player who has run the script. The
* Fabric hooks that turn game activity into Lua callbacks are installed
* <em>once</em>, in {@link #install()}; each hook simply dispatches to whichever
* runtime is currently registered. That keeps reset cheap and complete:
* {@link #startRun(ServerPlayer)} stops the player's previous runtime (closing
* its Lua state, which drops its callbacks) and installs a fresh one, so
* re-running the script always starts from no listeners.</p>
*
* <h2>Threading</h2>
*
* <p>All state here is touched only on the server thread: run requests arrive on
* it, and every hooked game event (item use, block break, chat, join/leave,
* tick) fires on it. A script's {@code Lua} state is therefore never touched
* concurrently, and the disconnect hook is careful to drop a runtime that a
* later dispatch might otherwise reach.</p>
*/
public final class ScriptRuntimeManager {
private static final Map<UUID, ScriptRuntime> ACTIVE = new HashMap<>();
private ScriptRuntimeManager() {
}
/**
* Wires the Fabric game events to the dispatcher. Call once from
* {@link com.aranroig.Codecraft#onInitialize()}.
*/
public static void install() {
UseItemCallback.EVENT.register((player, level, hand) -> {
onUseItem(player, hand);
return InteractionResult.PASS;
});
PlayerBlockBreakEvents.AFTER.register((level, player, pos, state, blockEntity) ->
onBreakBlock(player, pos, state));
ServerMessageEvents.CHAT_MESSAGE.register((message, sender, params) ->
onChat(sender, message));
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) ->
onPlayerJoin(handler.player));
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> {
onPlayerLeave(handler.player);
// Free the leaving player's runtime; their callbacks can no longer
// act on a disconnected owner.
stop(handler.player);
});
ServerTickEvents.END_SERVER_TICK.register(ScriptRuntimeManager::onTick);
// Safety net: never leave Lua states open across a server shutdown.
ServerLifecycleEvents.SERVER_STOPPING.register(server -> stopAll());
}
/**
* Replaces {@code player}'s running script with a brand-new runtime and
* returns it, ready for the entrypoint to be {@linkplain ScriptRuntime#run
* run}. Any listeners the player registered previously are dropped.
*
* @param player the player who pressed <em>Run Script</em>
* @return the fresh runtime with the Minecraft API tables, {@code run},
* {@code print} and {@code events} already registered
*/
public static ScriptRuntime startRun(ServerPlayer player) {
stop(player);
ScriptRuntime runtime = newRuntime(player);
ACTIVE.put(player.getUUID(), runtime);
return runtime;
}
private static ScriptRuntime newRuntime(ServerPlayer player) {
Lua lua = new LuaJ();
ScriptRuntime runtime = new ScriptRuntime(lua, player);
lua.push(ChatLogger.print(player));
lua.setGlobal("print");
ServerCommandApi.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);
return runtime;
}
// ── Dispatch ──────────────────────────────────────────────────────────
private static void onUseItem(Player player, InteractionHand hand) {
if (!(player instanceof ServerPlayer)) {
return;
}
ItemStack stack = player.getItemInHand(hand);
if (stack.isEmpty()) {
return;
}
String item = BuiltInRegistries.ITEM.getKey(stack.getItem()).toString();
String handName = hand == InteractionHand.OFF_HAND ? "off" : "main";
dispatch(GameEvent.USE_ITEM, player.getScoreboardName(), item, (long) stack.getCount(), handName);
}
private static void onBreakBlock(Player player, BlockPos pos, BlockState state) {
if (!(player instanceof ServerPlayer)) {
return;
}
String block = BuiltInRegistries.BLOCK.getKey(state.getBlock()).toString();
dispatch(GameEvent.BREAK_BLOCK, player.getScoreboardName(),
(long) pos.getX(), (long) pos.getY(), (long) pos.getZ(), block);
}
private static void onChat(ServerPlayer player, PlayerChatMessage message) {
dispatch(GameEvent.CHAT, player.getScoreboardName(), message.signedContent());
}
private static void onPlayerJoin(ServerPlayer player) {
dispatch(GameEvent.PLAYER_JOIN, player.getScoreboardName());
}
private static void onPlayerLeave(ServerPlayer player) {
dispatch(GameEvent.PLAYER_LEAVE, player.getScoreboardName());
}
private static void onTick(MinecraftServer server) {
dispatch(GameEvent.TICK, (long) server.getTickCount());
}
/**
* Fires {@code event} on every runtime that listens for it. A runtime with
* no listener for the event is skipped, so idle scripts cost nothing per
* hook.
*/
private static void dispatch(GameEvent event, Object... args) {
if (ACTIVE.isEmpty()) {
return;
}
// Copy values so a callback that reruns or a disconnect during the loop
// cannot mutate the map while we iterate.
for (ScriptRuntime runtime : Map.copyOf(ACTIVE).values()) {
if (runtime.hasListeners(event)) {
runtime.dispatch(event, args);
}
}
}
// ── Teardown ──────────────────────────────────────────────────────────
private static void stop(ServerPlayer player) {
ScriptRuntime runtime = ACTIVE.remove(player.getUUID());
if (runtime != null) {
runtime.stop();
}
}
private static void stopAll() {
for (ScriptRuntime runtime : ACTIVE.values()) {
runtime.stop();
}
ACTIVE.clear();
}
}

View File

@@ -0,0 +1,41 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import com.aranroig.editor.Edit;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Someone else's edit of {@code file}, already rebased by the server. The file
* is now at {@code version}. The player who wrote the edit does not get this:
* their copy already has it, they get an {@link ClientboundEditAckPayload}
* instead.
*/
public record ClientboundDocumentEditPayload(String file, int version, Edit edit) implements CustomPacketPayload {
public static final Identifier DOCUMENT_EDIT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "document_edit");
public static final CustomPacketPayload.Type<ClientboundDocumentEditPayload> TYPE = new CustomPacketPayload.Type<>(DOCUMENT_EDIT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundDocumentEditPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundDocumentEditPayload::file,
ByteBufCodecs.VAR_INT,
ClientboundDocumentEditPayload::version,
Edit.STREAM_CODEC,
ClientboundDocumentEditPayload::edit,
ClientboundDocumentEditPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,39 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* The authoritative contents of {@code file} at {@code version}. Sent in reply
* to {@link ServerboundOpenDocumentPayload}, and again whenever the server
* finds that a client's copy is too old to be rebased onto the live one.
*/
public record ClientboundDocumentStatePayload(String file, String text, int version) implements CustomPacketPayload {
public static final Identifier DOCUMENT_STATE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "document_state");
public static final CustomPacketPayload.Type<ClientboundDocumentStatePayload> TYPE = new CustomPacketPayload.Type<>(DOCUMENT_STATE_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundDocumentStatePayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundDocumentStatePayload::file,
ByteBufCodecs.STRING_UTF8,
ClientboundDocumentStatePayload::text,
ByteBufCodecs.VAR_INT,
ClientboundDocumentStatePayload::version,
ClientboundDocumentStatePayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,44 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Confirms that the server applied one of the player's own edits: the document
* is now at {@code version}, whose contents have length {@code textLength} and
* hash {@code textHash}. Once the player has no edits in flight any more, they
* compare those two against their own buffer; a mismatch means the copies
* drifted apart and the file is fetched again.
*/
public record ClientboundEditAckPayload(String file, int version, int textHash, int textLength) implements CustomPacketPayload {
public static final Identifier EDIT_ACK_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "edit_ack");
public static final CustomPacketPayload.Type<ClientboundEditAckPayload> TYPE = new CustomPacketPayload.Type<>(EDIT_ACK_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundEditAckPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundEditAckPayload::file,
ByteBufCodecs.VAR_INT,
ClientboundEditAckPayload::version,
ByteBufCodecs.VAR_INT,
ClientboundEditAckPayload::textHash,
ByteBufCodecs.VAR_INT,
ClientboundEditAckPayload::textLength,
ClientboundEditAckPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,39 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import com.aranroig.editor.EditorPresence;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import java.util.List;
/**
* Who else has {@code file} open in their editor right now, and where their
* carets are. Everyone with the editor open gets this for every file somebody
* joins, leaves or moves in, minus themselves.
*/
public record ClientboundPresencePayload(String file, List<EditorPresence> editors) implements CustomPacketPayload {
public static final Identifier PRESENCE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "presence");
public static final CustomPacketPayload.Type<ClientboundPresencePayload> TYPE = new CustomPacketPayload.Type<>(PRESENCE_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundPresencePayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundPresencePayload::file,
EditorPresence.STREAM_CODEC.apply(ByteBufCodecs.list()),
ClientboundPresencePayload::editors,
ClientboundPresencePayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,30 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import com.aranroig.editor.EditorFile;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
import java.util.List;
public record ClientboundProjectFilesPayload(List<EditorFile> files) implements CustomPacketPayload {
public static final Identifier PROJECT_FILES_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "project_files");
public static final CustomPacketPayload.Type<ClientboundProjectFilesPayload> TYPE = new CustomPacketPayload.Type<>(PROJECT_FILES_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundProjectFilesPayload> CODEC =
StreamCodec.composite(
EditorFile.STREAM_CODEC.apply(ByteBufCodecs.list()),
ClientboundProjectFilesPayload::files,
ClientboundProjectFilesPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,36 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Tells the client that a project file was renamed by somebody else, so its
* name in the file list and all live-editing bookkeeping keyed by the old name
* follow it.
*/
public record ClientboundRenameFilePayload(String oldName, String newName) implements CustomPacketPayload {
public static final Identifier RENAME_FILE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "rename_file");
public static final CustomPacketPayload.Type<ClientboundRenameFilePayload> TYPE = new CustomPacketPayload.Type<>(RENAME_FILE_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundRenameFilePayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundRenameFilePayload::oldName,
ByteBufCodecs.STRING_UTF8,
ClientboundRenameFilePayload::newName,
ClientboundRenameFilePayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,31 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* The shell is gone — it exited on its own or could not be started — and says
* why, which the terminal pane prints as a dim note.
*/
public record ClientboundShellClosedPayload(String reason) implements CustomPacketPayload {
public static final Identifier SHELL_CLOSED_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_closed");
public static final CustomPacketPayload.Type<ClientboundShellClosedPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_CLOSED_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundShellClosedPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundShellClosedPayload::reason,
ClientboundShellClosedPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,32 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Everything the shell printed, in order — stdout and stderr merged, line
* endings already normalised to {@code \n}. A message can hold any number of
* lines and can stop in the middle of one: the pane just appends it.
*/
public record ClientboundShellOutputPayload(String text) implements CustomPacketPayload {
public static final Identifier SHELL_OUTPUT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_output");
public static final CustomPacketPayload.Type<ClientboundShellOutputPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_OUTPUT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ClientboundShellOutputPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ClientboundShellOutputPayload::text,
ClientboundShellOutputPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,27 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* The player closed the editor: drop them from every live editing session, so
* their caret disappears from everyone else's screen and their keystrokes are
* no longer streamed to them.
*/
public record ServerboundCloseEditorPayload() implements CustomPacketPayload {
public static final Identifier CLOSE_EDITOR_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "close_editor");
public static final CustomPacketPayload.Type<ServerboundCloseEditorPayload> TYPE = new CustomPacketPayload.Type<>(CLOSE_EDITOR_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCloseEditorPayload> CODEC =
StreamCodec.unit(new ServerboundCloseEditorPayload());
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,26 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* The player closed the terminal pane: kill the shell it was attached to.
* Nothing about it is saved — closing the pane means closing the shell.
*/
public record ServerboundCloseShellPayload() implements CustomPacketPayload {
public static final Identifier CLOSE_SHELL_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "close_shell");
public static final CustomPacketPayload.Type<ServerboundCloseShellPayload> TYPE = new CustomPacketPayload.Type<>(CLOSE_SHELL_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCloseShellPayload> CODEC =
StreamCodec.unit(new ServerboundCloseShellPayload());
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,38 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Moves the player's caret (and selection) inside {@code file}, to be shown on
* everyone else's screen.
*/
public record ServerboundCursorPayload(String file, int cursor, int anchor) implements CustomPacketPayload {
public static final Identifier CURSOR_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "cursor");
public static final CustomPacketPayload.Type<ServerboundCursorPayload> TYPE = new CustomPacketPayload.Type<>(CURSOR_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundCursorPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ServerboundCursorPayload::file,
ByteBufCodecs.VAR_INT,
ServerboundCursorPayload::cursor,
ByteBufCodecs.VAR_INT,
ServerboundCursorPayload::anchor,
ServerboundCursorPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,40 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import com.aranroig.editor.Edit;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* One keystroke's worth of changes to {@code file}, made against version
* {@code baseVersion} of it. The server rebases the edit onto the current
* version, applies it, and hands it to everyone else editing the file.
*/
public record ServerboundEditPayload(String file, int baseVersion, Edit edit) implements CustomPacketPayload {
public static final Identifier EDIT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "edit");
public static final CustomPacketPayload.Type<ServerboundEditPayload> TYPE = new CustomPacketPayload.Type<>(EDIT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundEditPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ServerboundEditPayload::file,
ByteBufCodecs.VAR_INT,
ServerboundEditPayload::baseVersion,
Edit.STREAM_CODEC,
ServerboundEditPayload::edit,
ServerboundEditPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,35 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Asks the server to put the player into the live editing session of
* {@code file} and to reply with its authoritative contents
* ({@link ClientboundDocumentStatePayload}). Sent when the editor opens and
* every time the player switches file; the server then streams that file's
* edits and carets to the player.
*/
public record ServerboundOpenDocumentPayload(String file) implements CustomPacketPayload {
public static final Identifier OPEN_DOCUMENT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "open_document");
public static final CustomPacketPayload.Type<ServerboundOpenDocumentPayload> TYPE = new CustomPacketPayload.Type<>(OPEN_DOCUMENT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundOpenDocumentPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ServerboundOpenDocumentPayload::file,
ServerboundOpenDocumentPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,37 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Asks the server to rename a project file: its copy in the saved project and
* its live document move to the new name, the sessions of everyone editing it
* follow, and the other editors are told
* ({@link ClientboundRenameFilePayload}).
*/
public record ServerboundRenameFilePayload(String oldName, String newName) implements CustomPacketPayload {
public static final Identifier RENAME_FILE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "rename_file");
public static final CustomPacketPayload.Type<ServerboundRenameFilePayload> TYPE = new CustomPacketPayload.Type<>(RENAME_FILE_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundRenameFilePayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ServerboundRenameFilePayload::oldName,
ByteBufCodecs.STRING_UTF8,
ServerboundRenameFilePayload::newName,
ServerboundRenameFilePayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,22 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
public record ServerboundRequestProjectPayload() implements CustomPacketPayload {
public static final Identifier REQUEST_PROJECT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "request_project");
public static final CustomPacketPayload.Type<ServerboundRequestProjectPayload> TYPE = new CustomPacketPayload.Type<>(REQUEST_PROJECT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundRequestProjectPayload> CODEC =
StreamCodec.unit(new ServerboundRequestProjectPayload());
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,34 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* What the terminal pane's keyboard produces, written to the pseudo-terminal
* exactly as it is: a keystroke, a Tab, the {@code \u0003} Ctrl-C becomes, an
* arrow key's escape sequence, a status report the emulator owes the shell.
* On the pty those bytes are not text but signals and edits — SIGINT, an
* echoed backspace, vim moving its cursor — so nothing here interprets them.
*/
public record ServerboundShellInputPayload(String bytes) implements CustomPacketPayload {
public static final Identifier SHELL_INPUT_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_input");
public static final CustomPacketPayload.Type<ServerboundShellInputPayload> TYPE = new CustomPacketPayload.Type<>(SHELL_INPUT_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundShellInputPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.STRING_UTF8,
ServerboundShellInputPayload::bytes,
ServerboundShellInputPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,37 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* The terminal pane's grid changed size. Not keystrokes — the shell's input
* is left alone: the server resizes the pseudo-terminal itself, and the
* kernel signals whatever runs in it the way it signals a real window's
* resize. That is what lets a full-screen program reflow while it holds the
* screen, which a typed {@code stty} at a prompt that is not there could
* never do.
*/
public record ServerboundShellResizePayload(int rows, int cols) implements CustomPacketPayload {
public static final Identifier SHELL_RESIZE_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "shell_resize");
public static final CustomPacketPayload.Type<ServerboundShellResizePayload> TYPE = new CustomPacketPayload.Type<>(SHELL_RESIZE_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundShellResizePayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.VAR_INT,
ServerboundShellResizePayload::rows,
ByteBufCodecs.VAR_INT,
ServerboundShellResizePayload::cols,
ServerboundShellResizePayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,34 @@
package com.aranroig.payloads;
import com.aranroig.Codecraft;
import net.minecraft.network.RegistryFriendlyByteBuf;
import net.minecraft.network.codec.ByteBufCodecs;
import net.minecraft.network.codec.StreamCodec;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.resources.Identifier;
/**
* Ask for a shell. The size of the terminal pane that asked comes along: a
* terminal opens at the size of its window, and 0 means the client could not
* tell it yet, which leaves the shell on its own defaults.
*/
public record ServerboundSpawnShellPayload(int rows, int cols) implements CustomPacketPayload {
public static final Identifier SPAWN_SHELL_PAYLOAD_ID = Identifier.fromNamespaceAndPath(Codecraft.MOD_ID, "spawn_shell");
public static final CustomPacketPayload.Type<ServerboundSpawnShellPayload> TYPE = new CustomPacketPayload.Type<>(SPAWN_SHELL_PAYLOAD_ID);
public static final StreamCodec<RegistryFriendlyByteBuf, ServerboundSpawnShellPayload> CODEC =
StreamCodec.composite(
ByteBufCodecs.VAR_INT,
ServerboundSpawnShellPayload::rows,
ByteBufCodecs.VAR_INT,
ServerboundSpawnShellPayload::cols,
ServerboundSpawnShellPayload::new
);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}

View File

@@ -0,0 +1,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,115 @@
package com.aranroig.shell;
import com.aranroig.Codecraft;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.level.ServerPlayer;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* The server half of the editor's terminal: at most one {@link ShellSession}
* per player, spawned when they press the terminal button and killed when they
* close the pane, leave, or the server stops.
*
* <p><b>This hands out a real shell on the machine the server runs on, to
* anyone who can open the editor.</b> Commands run as the server's user, in
* the server's files, with everything that implies. That is fine on a
* single-player game or a server among friends who all get the keys to the
* box; it is emphatically not something to leave open to strangers.</p>
*
* <p>Payload handlers run on the server thread, so spawning, submitting and
* closing need no locking; only the output threads report back from outside,
* through {@link #sessionEnded}, hence the concurrent map.</p>
*/
public final class ShellManager {
private static final Map<UUID, ShellSession> SESSIONS = new ConcurrentHashMap<>();
private ShellManager() {
}
/** Kills every shell when its player leaves or the server goes down. */
public static void install() {
ServerPlayConnectionEvents.DISCONNECT.register((handler, server) -> close(handler.player));
ServerLifecycleEvents.SERVER_STOPPING.register(ShellManager::closeAll);
}
/**
* Gives {@code player} a shell, opening it at the size of the terminal
* pane that asked ({@code rows}/{@code cols} of 0: the shell's own
* defaults). Pressing the button with one already running does not
* disturb it: the pane keeps its scrollback, so the same session is
* simply attached again and told so.
*/
public static void spawn(ServerPlayer player, int rows, int cols) {
ShellSession existing = SESSIONS.get(player.getUUID());
if (existing != null && existing.isAlive()) {
send(player, new ClientboundShellOutputPayload("shell already running — this pane is attached to it\r\n"));
return;
}
if (existing != null) existing.close();
ShellSession session = new ShellSession(player);
try {
session.start(rows, cols);
SESSIONS.put(player.getUUID(), session);
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not spawn a shell for {}", player.getName().getString(), e);
send(player, new ClientboundShellOutputPayload("could not start a shell: " + e.getMessage() + "\r\n"));
send(player, new ClientboundShellClosedPayload("could not start a shell"));
}
}
/** Forwards what the pane's keyboard produced, as it is, to that player's shell. */
public static void submit(ServerPlayer player, String bytes) {
ShellSession session = SESSIONS.get(player.getUUID());
if (session == null || !session.isAlive()) {
send(player, new ClientboundShellOutputPayload("no shell running — open one with the Shell button\r\n"));
return;
}
session.submitInput(bytes);
}
/**
* Resizes the pty behind that player's shell to the size their terminal
* pane now has. Nothing is said when there is no live shell to size: the
* next spawn opens at whatever size asks anyway.
*/
public static void resize(ServerPlayer player, int rows, int cols) {
ShellSession session = SESSIONS.get(player.getUUID());
if (session != null && session.isAlive()) session.resize(rows, cols);
}
/** Kills the shell a player was attached to, if they had one. */
public static void close(ServerPlayer player) {
ShellSession session = SESSIONS.remove(player.getUUID());
if (session != null) session.close();
}
/** Called by a session's output thread once the process is done with. */
static void sessionEnded(ShellSession session) {
SESSIONS.values().removeIf(alive -> alive == session);
}
private static void closeAll(MinecraftServer server) {
for (ShellSession session : SESSIONS.values()) session.close();
SESSIONS.clear();
}
private static void send(ServerPlayer player, CustomPacketPayload payload) {
try {
ServerPlayNetworking.send(player, payload);
} catch (RuntimeException e) {
// The player is leaving; nobody is there to read this.
}
}
}

View File

@@ -0,0 +1,535 @@
package com.aranroig.shell;
import com.aranroig.Codecraft;
import com.aranroig.payloads.ClientboundShellClosedPayload;
import com.aranroig.payloads.ClientboundShellOutputPayload;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.minecraft.network.protocol.common.custom.CustomPacketPayload;
import net.minecraft.server.level.ServerPlayer;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.lang.ProcessBuilder.Redirect;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* One interactive bash session on the server, wired to one player's terminal
* pane: what it prints is forwarded to the pane as
* {@link ClientboundShellOutputPayload}s, and every byte the player types is
* written to its input.
*
* <h2>A real terminal, not a pipe</h2>
*
* <p>Bash is fully interactive ({@code -i}, readline and all) and runs on a
* pseudo-terminal allocated through {@code script} (util-linux), so everything
* a real terminal does happens here: the tty echoes what arrives, readline
* redraws the line while it is edited, programs see a tty — {@code tty} says
* {@code /dev/pts/…}, {@code ls --color=auto} colours, {@code sudo} prompts,
* {@code vim} takes over the screen — and {@code TERM} is
* {@code xterm-256color} to match. Drawing all of that, cursor and all, is the
* pane's job: it is the emulator, this is only the machine behind it. Where
* {@code script} is not available, it falls back to plain non-interactive
* bash over pipes, which still runs commands and keeps state, but without any
* of the tty behaviours.</p>
*
* <p>The pane tells the shell how big the "window" is the way a real terminal
* emulator sizes one: the pty's window is moved from out here — {@code stty}
* run against the session's {@code /dev/pts} device, which makes the kernel
* resize the terminal and signal the programs in the foreground that it did,
* so a full-screen program reflows mid-resize — and nothing is ever typed
* into the shell to say so.</p>
*
* <h2>Threading</h2>
*
* <p>The process' output is read on its own thread — a command that prints
* for a minute must not stop the server from ticking — and handed straight to
* the player's connection, which netty accepts from any thread. Input goes
* the other way from the server thread, written through as it arrives.</p>
*/
public final class ShellSession {
/**
* The shell the pseudo-terminal runs: the server user's plain interactive
* bash, so — exactly like a terminal opened on the machine itself — it
* sources their startup files, {@code /etc/bash.bashrc} and
* {@code ~/.bashrc}, before the first prompt.
*/
private static final String SHELL_COMMAND = "bash -i";
/** Allocates the pty that lets bash be interactive. Tried in order. */
private static final String[] PTY_LAUNCHERS = { "/usr/bin/script", "/bin/script", "script" };
/** Tried in order when no pty launcher could be started; first one that starts wins. */
private static final String[] PLAIN_SHELLS = { "/bin/bash", "/usr/bin/bash", "bash" };
/**
* Sizes the pty's window through its {@code /dev/pts} device; tried in
* order like everything else. {@code stty} does nothing but the one ioctl
* on its standard input, which the kernel turns into a new window size
* and — when it changed — a SIGWINCH for the terminal's foreground group.
*/
private static final String[] STTY_COMMANDS = { "/bin/stty", "/usr/bin/stty", "stty" };
/** How long the shell may take to appear under {@code script} before the pty device search gives up. */
private static final long PTS_SEARCH_BUDGET_MS = 5_000;
private static final long PTS_SEARCH_RETRY_MS = 200;
/** How long one {@code stty} may take to size a window before it is not believed. */
private static final long STTY_TIMEOUT_MS = 2_000;
/** How much of the shell's output is read — and sent — at once. */
private static final int CHUNK_SIZE = 4096;
private final ServerPlayer player;
private Process process;
private OutputStream stdin;
private volatile boolean alive;
/** Whether the shell sits on a real pty (programs see a terminal) or on pipes. */
private boolean interactive;
/** Set when we killed it ourselves, so its exit is not announced as news. */
private volatile boolean closing;
/**
* Guards the wanted and applied window sizes, and the wait between the
* pane wanting one and the resize worker getting it: the pane's sizes
* arrive on the server thread with its payloads, and the {@code stty}
* runs that turn them into kernel calls must not keep the server ticking.
*/
private final Object resizeLock = new Object();
/** The size the pane last wanted, and the last one actually applied; guarded by {@link #resizeLock}. */
private int wantRows, wantCols, appliedRows, appliedCols;
/** Whether the worker that applies sizes has been started; guarded by {@link #resizeLock}. */
private boolean resizeLoopStarted;
/**
* This session's {@code /dev/pts} device, found once by following the
* process tree down from {@code script}: whoever runs under it has the
* pty on its standard input, and the link there is the device. Written
* only by the resize worker.
*/
private String ptsDevice;
/** Whether the device above was given up on; guarded by {@link #resizeLock}, read by the worker. */
private boolean ptsSearchFailed;
ShellSession(ServerPlayer player) {
this.player = player;
}
/**
* Spawns the shell and starts forwarding its output to the player. A
* pseudo-terminal through {@code script} if one can be had, plain bash
* over pipes otherwise. {@code rows}/{@code cols} (when positive) are the
* size of the pane that asked: on the pty the window is set to them as
* soon as its device can be found (see {@link #resize}), the same call a
* real window resize makes; only the pipe fallback, which has no terminal
* at all to size, is given them as {@code LINES}/{@code COLUMNS} instead.
*
* @throws IOException no shell could be started on this machine
*/
public void start(int rows, int cols) throws IOException {
IOException lastFailure = null;
for (String launcher : PTY_LAUNCHERS) {
try {
process = ptyBuilderFor(launcher).start();
// `script` starting is not running it: an older one that does
// not know these options exits at once, and that is found out
// by giving it the moment it needs, no more.
if (startedAndStayedUp()) {
interactive = true;
break;
}
process = null;
} catch (IOException e) {
lastFailure = e;
process = null;
}
}
if (process == null) {
for (String shell : PLAIN_SHELLS) {
try {
process = plainBuilderFor(shell, rows, cols).start();
break;
} catch (IOException e) {
lastFailure = e;
}
}
}
if (process == null) {
throw lastFailure != null ? lastFailure
: new IOException("no bash found on this server");
}
stdin = process.getOutputStream();
alive = true;
Codecraft.LOGGER.info("Spawned a {} shell for {} in {}",
interactive ? "pty-backed" : "plain",
player.getName().getString(), System.getProperty("user.dir"));
// A terminal opens at the size of the window that asked: `script`
// cannot be told, so its pty starts at the kernel's default and the
// worker corrects it to the pane's grid a moment later, as soon as
// the device behind it is findable — well before bash prints much.
synchronized (resizeLock) {
wantRows = rows;
wantCols = cols;
if (interactive) startResizeLoop();
}
Thread.ofVirtual()
.name("codecraft-shell-" + player.getName().getString())
.start(this::pumpOutput);
}
/**
* Whether the process made it past the moment an unusable launcher takes
* to argue with its own command line and give up.
*/
private boolean startedAndStayedUp() {
try {
return !process.waitFor(250, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return true;
}
}
private static ProcessBuilder ptyBuilderFor(String script) {
ProcessBuilder builder = new ProcessBuilder(
// -q quiet, -f flush every write (output must not wait for the
// shell to exit), -e exit with the child's code. The tty's
// echo stays on: the pane shows what was typed exactly the
// way it arrives back, as any terminal does, so readline can
// redraw the line and nothing is ever shown twice.
script, "-q", "-f", "-e",
"-c", SHELL_COMMAND,
// No typescript file: the scrollback in the pane is the record.
"/dev/null");
// A real terminal on a real tty, not the dumb one a pipe implies. The
// prompt stays bash's own — it is part of what the pane draws. And no
// LINES/COLUMNS in the environment: those make programs trust the
// numbers over the terminal they are on, and the numbers here must be
// the pty's own window, kept true by the resize machinery below.
builder.environment().put("TERM", "xterm-256color");
return builder;
}
private static ProcessBuilder plainBuilderFor(String shell, int rows, int cols) {
ProcessBuilder builder = new ProcessBuilder(shell, "--noediting");
// A non-interactive bash reads no rc files at all, so BASH_ENV is the
// way to have this path source the same ~/.bashrc (expanded by bash
// itself, against the server process' HOME) that the pty path gets.
builder.environment().put("BASH_ENV", "~/.bashrc");
// Without the pty, stdout and stderr are merged here instead.
builder.redirectErrorStream(true);
return configurePipeEnv(builder, rows, cols);
}
/** The environment of the pipe fallback: a terminal it does not really have, sized only by env. */
private static ProcessBuilder configurePipeEnv(ProcessBuilder builder, int rows, int cols) {
Map<String, String> env = builder.environment();
env.put("TERM", "xterm-256color");
// There is no terminal to size on this path, so LINES/COLUMNS are the
// only way a program here can be told anything at all.
if (rows > 0 && cols > 0) {
env.put("LINES", String.valueOf(rows));
env.put("COLUMNS", String.valueOf(cols));
}
return builder;
}
/**
* Writes what the pane typed straight to the pseudo-terminal: keystrokes,
* tabs, Ctrl-C's {@code \u0003}, an arrow key's escape sequence, an
* emulator's answer to a status query. Nothing is interpreted on the way —
* on the pty those bytes are edits and signals, not text, and the shell
* and its programs read them exactly as they would from a real terminal.
*/
public void submitInput(String bytes) {
if (!alive || stdin == null) return;
try {
stdin.write(bytes.getBytes(StandardCharsets.UTF_8));
stdin.flush();
} catch (IOException e) {
Codecraft.LOGGER.warn("Could not write to the shell of {}", player.getName().getString(), e);
}
}
/**
* Resizes the pty's window to a new size of the pane, from the outside:
* nothing is written to the shell's input, so a full-screen program in
* the foreground is signalled mid-run — SIGWINCH, and it redraws —
* instead of waiting for a typed {@code stty} it would only read as
* keystrokes. The newest size wins while an older one is still being
* applied, so dragging a sash across the screen converges on where it
* was let go rather than queueing a resize per frame.
*/
public void resize(int rows, int cols) {
if (rows <= 0 || cols <= 0) return;
synchronized (resizeLock) {
if (!alive) return;
wantRows = rows;
wantCols = cols;
resizeLock.notifyAll();
if (interactive) startResizeLoop();
}
}
/** Hands the pending sizes to a worker; the caller holds {@link #resizeLock}. */
private void startResizeLoop() {
if (resizeLoopStarted) return;
resizeLoopStarted = true;
Thread.ofVirtual()
.name("codecraft-shell-resize-" + player.getName().getString())
.start(this::applySizes);
}
/**
* Waits for the pane to want a window of a different size and applies it,
* one wanted size at a time: whatever arrived meanwhile is simply the
* next thing asked for.
*/
private void applySizes() {
while (true) {
int rows, cols;
synchronized (resizeLock) {
while (alive && !sizeWantedLocked()) {
try {
resizeLock.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
}
if (!alive) return;
rows = wantRows;
cols = wantCols;
}
applyWindowSize(rows, cols);
synchronized (resizeLock) {
appliedRows = rows;
appliedCols = cols;
}
}
}
/** Whether a real size is wanted and not applied yet; the caller holds {@link #resizeLock}. */
private boolean sizeWantedLocked() {
return wantRows > 0 && wantCols > 0 && (wantRows != appliedRows || wantCols != appliedCols);
}
/**
* Moves the pty's window to {@code rows} x {@code cols} by sizing its
* device — the same ioctl a real terminal emulator makes, and the kernel
* signals the terminal's foreground the way it signals any resize.
*/
private void applyWindowSize(int rows, int cols) {
String device = findPtsDevice();
if (device != null && runSttyAt(device, rows, cols)) return;
// No device to size from — no /proc to find it, no stty to size it,
// or it went away mid-session. Typed at the prompt is the only way
// left to tell a size at all: echoed, blind to whatever holds the
// screen, and the old behaviour, but better here than a window stuck
// at whatever it was.
Codecraft.LOGGER.warn("Could not size the pty of {}'s shell from its device; "
+ "resizing falls back to typing at the prompt", player.getName().getString());
ptsDevice = null;
submitInput("export LINES=" + rows + " COLUMNS=" + cols
+ "; stty rows " + rows + " cols " + cols + "\r");
}
/** Sizes the terminal at {@code device} by handing it, as standard input, to {@code stty}. */
private boolean runSttyAt(String device, int rows, int cols) {
for (String stty : STTY_COMMANDS) {
Process resized = null;
try {
resized = new ProcessBuilder(stty, "rows", String.valueOf(rows), "cols", String.valueOf(cols))
.redirectInput(new File(device))
.redirectOutput(Redirect.DISCARD)
.redirectError(Redirect.DISCARD)
.start();
if (resized.waitFor(STTY_TIMEOUT_MS, TimeUnit.MILLISECONDS) && resized.exitValue() == 0) return true;
} catch (IOException e) {
// This stty is not here; the next one may be.
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return false;
} finally {
if (resized != null && resized.isAlive()) resized.destroyForcibly();
}
}
return false;
}
/**
* This session's pty device, searched for on first need and kept after.
* The shell appears under {@code script} a moment after the spawn, so the
* search retries quietly for a little while before giving up — from then
* on this session is known to have no findable device.
*/
private String findPtsDevice() {
synchronized (resizeLock) {
if (ptsDevice != null) return ptsDevice;
if (ptsSearchFailed) return null;
}
long deadline = System.currentTimeMillis() + PTS_SEARCH_BUDGET_MS;
do {
try {
String device = searchPtsDevice();
ptsDevice = device;
return device;
} catch (IOException e) {
try {
Thread.sleep(PTS_SEARCH_RETRY_MS);
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
return null;
}
}
} while (alive && System.currentTimeMillis() < deadline);
synchronized (resizeLock) {
ptsSearchFailed = true;
}
Codecraft.LOGGER.warn("No /dev/pts under {}'s shell process tree; the pty window cannot be sized from here",
player.getName().getString());
return null;
}
/**
* Follows the process tree down from {@code script}: whoever runs under
* it has the pty on its standard input, and the {@code /proc} link there
* names the device. Throws when the tree holds nobody yet, which is how
* the search knows to look again in a moment.
*/
private String searchPtsDevice() throws IOException {
ArrayDeque<Long> queue = new ArrayDeque<>();
queue.add(process.pid());
for (int visited = 0; !queue.isEmpty() && visited < 64; visited++) {
for (long child : childrenOf(queue.poll())) {
String standardInput = fdTarget(child, 0);
if (standardInput != null && standardInput.startsWith("/dev/pts/")) return standardInput;
queue.add(child);
}
}
throw new IOException("no /dev/pts within pid " + process.pid() + "'s tree");
}
/** The pids {@code pid} spawned, as {@code /proc} reports them. */
private static List<Long> childrenOf(long pid) {
List<Long> children = new ArrayList<>();
try {
String line = Files.readString(
Path.of("/proc", Long.toString(pid), "task", Long.toString(pid), "children"));
for (String token : line.split(" ")) {
if (!token.isBlank()) children.add(Long.parseLong(token));
}
} catch (IOException | NumberFormatException e) {
// No /proc to ask, or the process is gone already: nobody is under there.
}
return children;
}
/** What fd {@code fd} of {@code pid} points at, or null when {@code /proc} will not say. */
private static String fdTarget(long pid, int fd) {
try {
return Files.readSymbolicLink(
Path.of("/proc", Long.toString(pid), "fd", Integer.toString(fd))).toString();
} catch (IOException | SecurityException e) {
return null;
}
}
public boolean isAlive() {
return alive;
}
/** Kills the shell; its output thread then ends by itself, quietly. */
public void close() {
closing = true;
alive = false;
synchronized (resizeLock) {
resizeLock.notifyAll();
}
if (process == null) return;
process.destroy();
try {
if (!process.waitFor(500, TimeUnit.MILLISECONDS)) process.destroyForcibly();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
process.destroyForcibly();
}
}
/**
* Reads the shell's merged output until it closes, forwarding every chunk.
*
* <p>Reading characters through a decoder rather than raw bytes is what
* keeps a multibyte character that arrives split over two reads intact.
* Nothing else is done to the stream: the pane interprets it character by
* character — escape sequences and chunk boundaries rarely agree with each
* other, and the emulator is built knowing that.</p>
*/
private void pumpOutput() {
char[] buffer = new char[CHUNK_SIZE];
try (Reader output = new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)) {
int read;
while ((read = output.read(buffer)) > 0) {
send(new ClientboundShellOutputPayload(new String(buffer, 0, read)));
}
} catch (IOException e) {
if (!closing) {
Codecraft.LOGGER.warn("Shell output for {} broke: {}", player.getName().getString(), e.toString());
}
} finally {
alive = false;
synchronized (resizeLock) {
resizeLock.notifyAll();
}
ShellManager.sessionEnded(this);
if (!closing) {
int code = exitCode();
send(new ClientboundShellClosedPayload(
code >= 0 ? "shell exited (code " + code + ")" : "shell stopped"));
}
}
}
private int exitCode() {
try {
return process.exitValue();
} catch (IllegalStateException e) {
return -1;
}
}
/** Sends one message to the player, surviving the moment they are leaving. */
private void send(CustomPacketPayload payload) {
try {
ServerPlayNetworking.send(player, payload);
} catch (RuntimeException e) {
// The connection is gone; there is nobody left to print this to.
}
}
}

View File

@@ -0,0 +1,22 @@
package com.aranroig.wrapper;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerPlayer;
import party.iroiro.luajava.value.LuaFunction;
public class ChatLogger {
public static LuaFunction print(ServerPlayer player) {
return (lua, args) -> {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < args.length; i++) {
if (i > 0) sb.append('\t');
sb.append(args[i]);
}
player.sendSystemMessage(Component.literal(sb.toString()));
return null;
};
}
}

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

@@ -0,0 +1,305 @@
package com.aranroig.wrapper;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.arguments.blocks.BlockStateParser;
import net.minecraft.core.BlockPos;
import net.minecraft.core.registries.BuiltInRegistries;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.Blocks;
import net.minecraft.world.level.block.state.BlockState;
import party.iroiro.luajava.Lua;
import party.iroiro.luajava.value.LuaValue;
import java.util.ArrayList;
/**
* 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
* stands in. They are not limited by the player's reach, so a script can edit any block
* of a loaded chunk.</p>
*
* <p>Failures are reported the Lua way: a function returns {@code false} (or {@code nil}
* for {@code world.get_block}) followed by a short reason, so callers can write
* {@code if not world.set_block(...) then ... end}.</p>
*
* <p>Registered from {@link com.aranroig.Codecraft} on the server thread, which is the
* only thread allowed to touch the world.</p>
*/
public class WorldApi {
/** Update flags for {@link net.minecraft.world.level.Level#setBlock}: neighbours and clients. */
private static final int UPDATE_FLAGS = Block.UPDATE_ALL;
/**
* Registers the global {@code world} table.
*
* @param lua state to register the table on
* @param player the player the edits belong to, which also selects the dimension
*/
public static void register(Lua lua, ServerPlayer player) {
lua.newTable();
int world = lua.getTop();
lua.push((L, args) -> setBlock(L, player, args));
lua.setField(world, "set_block");
lua.push((L, args) -> removeBlock(L, player, args));
lua.setField(world, "remove_block");
lua.push((L, args) -> getBlock(L, player, args));
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");
}
/**
* {@code world.set_block(x, y, z, block)}
*
* <p>{@code block} is a block id such as {@code "minecraft:stone"}, optionally with
* block states: {@code "minecraft:oak_stairs[facing=north]"}. Tags are not allowed.</p>
*/
private static LuaValue[] setBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 4) {
return fail(lua, "usage: world.set_block(x, y, z, \"minecraft:stone\")");
}
BlockPos pos = position(args);
if (pos == null) {
return fail(lua, "x, y and z must be numbers");
}
if (args[3].type() != Lua.LuaType.STRING) {
return fail(lua, "block must be a string, e.g. \"minecraft:stone\"");
}
String description = args[3].toString();
BlockState state;
try {
state = BlockStateParser.parseForBlock(BuiltInRegistries.BLOCK, description, false).blockState();
} catch (CommandSyntaxException e) {
return fail(lua, "'" + description + "' is not a block");
}
ServerLevel level = player.level();
String problem = blockProblem(level, pos);
if (problem != null) {
return fail(lua, problem);
}
level.setBlock(pos, state, UPDATE_FLAGS);
// Read the block back instead of trusting the result of setBlock: a block that
// cannot stay where it was put (a torch in mid-air) removes itself again.
if (level.getBlockState(pos).getBlock() != state.getBlock()) {
return fail(lua, "'" + description + "' does not fit at " + describe(pos));
}
return success(lua);
}
/**
* {@code world.remove_block(x, y, z [, drops])}
*
* <p>The block vanishes without drops unless {@code drops} is given as {@code true},
* in which case it breaks as if a player had broken it.</p>
*/
private static LuaValue[] removeBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 3) {
return fail(lua, "usage: world.remove_block(x, y, z [, drops])");
}
BlockPos pos = position(args);
if (pos == null) {
return fail(lua, "x, y and z must be numbers");
}
ServerLevel level = player.level();
String problem = blockProblem(level, pos);
if (problem != null) {
return fail(lua, problem);
}
if (level.getBlockState(pos).isAir()) {
return fail(lua, "there is nothing to remove at " + describe(pos));
}
if (args.length > 3 && args[3].toBoolean()) {
return level.destroyBlock(pos, true, player, UPDATE_FLAGS)
? success(lua)
: fail(lua, "could not remove the block at " + describe(pos));
}
level.setBlock(pos, Blocks.AIR.defaultBlockState(), UPDATE_FLAGS);
if (!level.getBlockState(pos).isAir()) {
return fail(lua, "could not remove the block at " + describe(pos));
}
return success(lua);
}
/**
* {@code world.get_block(x, y, z)}
*
* <p>Returns the block id with its block states, e.g. {@code "minecraft:air"} or
* {@code "minecraft:oak_stairs[facing=north]"}, ready to be given to set_block.</p>
*/
private static LuaValue[] getBlock(Lua lua, ServerPlayer player, LuaValue[] args) {
if (args.length < 3) {
return missing(lua, "usage: world.get_block(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);
}
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.
*
* @return the position, or {@code null} when one of them is not a number
*/
private static BlockPos position(LuaValue[] args) {
Integer x = number(args[0]);
Integer y = number(args[1]);
Integer z = number(args[2]);
if (x == null || y == null || z == null) {
return null;
}
return new BlockPos(x, y, z);
}
/** Reads a Lua number as an int, or {@code null} for anything else. */
private static Integer number(LuaValue value) {
if (value == null || value.type() != Lua.LuaType.NUMBER) {
return null;
}
try {
return (int) value.toInteger();
} catch (RuntimeException e) {
return null;
}
}
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.
*
* @return why the block cannot be touched, or {@code null} when it can
*/
private static String blockProblem(ServerLevel level, BlockPos pos) {
if (level.isOutsideBuildHeight(pos)) {
return "y must be between " + level.getMinY() + " and " + level.getMaxY()
+ ", not " + pos.getY();
}
if (!level.isLoaded(pos)) {
return "the chunk at " + pos.getX() + ", " + pos.getZ() + " is not loaded";
}
return null;
}
private static String describe(BlockPos pos) {
return pos.getX() + ", " + pos.getY() + ", " + pos.getZ();
}
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) };
}
/** Failure for {@code world.get_block}, which gives {@code nil} rather than {@code false}. */
private static LuaValue[] missing(Lua lua, String reason) {
return new LuaValue[]{ lua.fromNull(), lua.from(reason) };
}
}

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

@@ -0,0 +1,654 @@
{
"topics": [
{
"title": "world",
"blurb": "Read and write blocks, inspect world state, and change time or weather in the executing player’s dimension.",
"functions": [
{
"name": "world.set_block",
"signature": "world.set_block(x, y, z, block)",
"summary": "Places a block and updates neighbours and clients, like /setblock does.",
"params": [
{
"name": "x",
"type": "number",
"optional": false,
"description": "Absolute world x coordinate (F3 to read your own)."
},
{
"name": "y",
"type": "number",
"optional": false,
"description": "Absolute world y coordinate."
},
{
"name": "z",
"type": "number",
"optional": false,
"description": "Absolute world z coordinate."
},
{
"name": "block",
"type": "string",
"optional": false,
"description": "Block id, with or without the minecraft: namespace, optionally with block states."
}
],
"returns": "true on success, or false followed by a reason string.",
"notes": [
"Coordinates are absolute, never relative to the player.",
"A block that cannot survive where it is put (a torch without a wall, a flower without ground) drops itself again and the call reports failure.",
"Replacing a block that holds items, such as a chest, drops its contents."
],
"examples": [
{
"title": "Namespace is optional; states are allowed",
"code": "world.set_block(10, 64, -3, \"minecraft:stone\")\nworld.set_block(10, 65, -3, \"gold_block\")\nworld.set_block(10, 66, -3, \"minecraft:oak_stairs[facing=north]\")"
},
{
"title": "Check whether it worked",
"code": "local ok, reason = world.set_block(10, 64, -3, \"minecraft:stone\")\nif not ok then\n print(\"could not place the block: \" .. reason)\nend"
}
]
},
{
"name": "world.remove_block",
"signature": "world.remove_block(x, y, z [, drops])",
"summary": "Removes the block at the given position.",
"params": [
{
"name": "x",
"type": "number",
"optional": false,
"description": "Absolute world x coordinate."
},
{
"name": "y",
"type": "number",
"optional": false,
"description": "Absolute world y coordinate."
},
{
"name": "z",
"type": "number",
"optional": false,
"description": "Absolute world z coordinate."
},
{
"name": "drops",
"type": "boolean",
"optional": true,
"description": "Pass true to break the block the way a player would (items, sound, particles)."
}
],
"returns": "true on success, or false followed by a reason string.",
"notes": [
"Without drops the block just vanishes, silently and without items.",
"Fails with \"there is nothing to remove\" if the target is already air."
],
"examples": [
{
"title": "Vanish versus break",
"code": "world.remove_block(10, 64, -3) -- vanish\nworld.remove_block(10, 65, -3, true) -- break it, dropping items"
}
]
},
{
"name": "world.get_block",
"signature": "world.get_block(x, y, z)",
"summary": "Returns the block id at that position, including its block states.",
"params": [
{
"name": "x",
"type": "number",
"optional": false,
"description": "Absolute world x coordinate."
},
{
"name": "y",
"type": "number",
"optional": false,
"description": "Absolute world y coordinate."
},
{
"name": "z",
"type": "number",
"optional": false,
"description": "Absolute world z coordinate."
}
],
"returns": "The block id string (ready to hand to set_block), or nil followed by a reason string.",
"notes": [
"Air is the string \"minecraft:air\", and every string is truthy in Lua — compare against the id rather than testing the value.",
"The result carries block states, e.g. minecraft:grass_block[snowy=false]."
],
"examples": [
{
"title": "Compare against the id, not the value",
"code": "local block = world.get_block(10, 64, -3)\nif block ~= \"minecraft:air\" then\n print(\"something is there: \" .. block)\nend"
},
{
"title": "Copy one place to another",
"code": "local block = world.get_block(10, 64, -3)\nif block then\n world.set_block(20, 70, 5, block)\nend"
}
]
},
{
"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."
}
]
},
{
"title": "events",
"blurb": "Run a function when something happens in the game. Listeners keep firing after the script has finished running, and reset when the script runs again.",
"functions": [
{
"name": "events.on_use_item",
"signature": "events.on_use_item(callback)",
"summary": "Calls callback whenever a player right-clicks to use the item in their hand.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the player name, the item id, the stack size and the hand: \"main\" or \"off\".",
"It fires alongside the game, never instead of it: the click still does whatever it would have done.",
"An empty hand does not fire the event.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Notice stick waves",
"code": "events.on_use_item(function(player, item, count, hand)\n if item == \"minecraft:stick\" then\n print(player .. \" waved a stick (\" .. hand .. \" hand)\")\n end\nend)"
}
]
},
{
"name": "events.on_break_block",
"signature": "events.on_break_block(callback)",
"summary": "Calls callback after a player has broken a block.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the player name, the x, y and z coordinates of the broken block and its block id.",
"It fires after the block is already gone — the coordinates now hold air.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Count broken ore",
"code": "broken = 0\nevents.on_break_block(function(player, x, y, z, block)\n if block == \"minecraft:diamond_ore\" then\n broken = broken + 1\n print(player .. \" broke a diamond ore (\" .. broken .. \" total)\")\n end\nend)"
}
]
},
{
"name": "events.on_chat",
"signature": "events.on_chat(callback)",
"summary": "Calls callback when a player sends a chat message.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the player name and the plain text of the message.",
"The message is still sent to chat as usual — the callback only observes it.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Reply to a keyword",
"code": "events.on_chat(function(player, message)\n if message == \"help\" then\n print(player .. \" asked for help\")\n end\nend)"
}
]
},
{
"name": "events.on_player_join",
"signature": "events.on_player_join(callback)",
"summary": "Calls callback when a player finishes joining the game.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the name of the player who just joined, including the running player themselves.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Welcome everyone",
"code": "events.on_player_join(function(player)\n print(\"welcome, \" .. player .. \"!\")\nend)"
}
]
},
{
"name": "events.on_player_leave",
"signature": "events.on_player_leave(callback)",
"summary": "Calls callback when a player leaves the game.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the name of the player who left.",
"When the running player themselves disconnects, their script stops with them, so a script cannot outlive its owner.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Track who is online",
"code": "events.on_player_leave(function(player)\n print(player .. \" left the game\")\nend)"
}
]
},
{
"name": "events.on_tick",
"signature": "events.on_tick(callback)",
"summary": "Calls callback once per server tick, at the end of each tick.",
"params": [
{
"name": "callback",
"type": "function",
"optional": false,
"description": "Lua function to call every time the event happens."
}
],
"returns": "true once the listener is registered, or false followed by a reason string.",
"notes": [
"The callback is given the tick counter, a whole number that increases by one every tick (20 ticks per second).",
"Keep tick callbacks cheap: they run twenty times a second, and a slow one lags the whole server.",
"The listener stays active after the script has finished running, until the script is run again, which resets all listeners."
],
"examples": [
{
"title": "Do something every five seconds",
"code": "events.on_tick(function(tick)\n if tick % 100 == 0 then\n print(\"still running at tick \" .. tick)\n end\nend)"
}
]
}
]
},
{
"title": "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",
"blurb": "Send text to the chat of the player running the script.",
"functions": [
{
"name": "print",
"signature": "print(...)",
"summary": "Writes to the chat of the player who ran the script, tab-separated.",
"params": [],
"returns": "nothing",
"notes": [
"Whole numbers go through the Lua wrapper and are printed as 12.0; concatenate them into a string to drop the decimal.",
"Runs on the server, so output appears in the running player's chat."
],
"examples": [
{
"title": "Print to chat",
"code": "print(\"blocks placed:\", 12)"
},
{
"title": "Drop the trailing .0",
"code": "print(\"blocks placed: \" .. 12) -- -> blocks placed: 12"
}
]
}
]
}
]
}

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",