More things editor is now more stable
Some checks failed
build / build (push) Failing after 50s

This commit is contained in:
2026-10-08 14:00:22 +02:00
parent b7e416d335
commit fe084e1843
21 changed files with 2323 additions and 180 deletions

View File

@@ -9,6 +9,22 @@ Codecraft is a Fabric mod (mod id `codecraft`, group `com.aranroig`) that lets p
- `./gradlew runDatagen` — regenerate data (lang files) into `src/main/generated/`. - `./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). - 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 ## 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. 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.
@@ -17,7 +33,7 @@ All versions live in `gradle.properties` (check https://fabricmc.net/develop): M
Loom uses `splitEnvironmentSourceSets()`: Loom uses `splitEnvironmentSourceSets()`:
- `src/main/java` — common/server code. Entrypoint `com.aranroig.Codecraft` (registers payloads, handles them server-side). Lua execution belongs here eventually. - `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/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/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`. - `src/main/generated` — datagen output (e.g. `assets/codecraft/lang/en_us.json`). Do not hand-edit; add translations in `CodecraftEnglishLangProvider` and run `runDatagen`.
@@ -28,8 +44,8 @@ Flow: client editor → custom payloads → server → persisted project.
- **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`. - **Networking** (`com.aranroig.payloads`): one record per message implementing `CustomPacketPayload` with a static `TYPE` and `StreamCodec`. Serverbound payloads must be registered in `Codecraft.onInitialize()` via `PayloadTypeRegistry.serverboundPlay().register(...)`, and received with `ServerPlayNetworking.registerGlobalReceiver(...)`.
- **Persistence** (`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. - **Persistence** (`com.aranroig.project.ProjectStore`): the project lives on the server's disk under `config/codecraft/` as plain `.lua` files mirroring the project paths (`lib/gui/theme` → `config/codecraft/lib/gui/theme.lua`), so it can also be edited with external editors — the project is re-read from disk every time the editor opens. Explicit saves write synchronously; keystrokes go to a pending map a daemon thread flushes ~1s after typing settles, and everything pending is flushed on server stop. Names are sanitized (`..` etc. refused) before touching the filesystem. `SavedProjectData` (world `SavedData`) is legacy: kept only to migrate a world's scripts into the config folder once, on `SERVER_STARTED`, when the config folder holds no scripts yet. The project is now per server-install, not per world.
- **Editor UI** (`com.aranroig.client.editor`): a custom immediate-mode-ish GUI system, not vanilla widgets. `EditorScreen` routes key/mouse input to `Widget`s by hit-testing (`inside()`) and z-index; scrolling goes to the widget under the mouse. `EditorManager` owns the widgets and editor actions (save/run/etc.); `EditorFileTree`, `EditorTopBar`, `EditorPaneContainer` are the three panels. `EditorPaneContainer` tiles the editing area into one or more `EditorFileView` panes (split right/below from the pane headers, the View menu, or Ctrl+\ / Ctrl+Shift+\), each header naming its file; the sashes between panes drag to resize them, and the "active pane" (last pane clicked) is where files from the tree open and where saving applies. `EditorFileView` is the actual text editor; `LuaHighlighter` tokenizes lines into colored `Span`s and `CompletionProvider` handles autocomplete. - **Editor UI** (`com.aranroig.client.editor`): 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` with the entrypoint name; the server handler in `Codecraft.java` is a TODO (currently just prints). Example of embedding: `Lua l = new LuaJ(); l.register("print", Logger.print()); l.run(code);` — `com.aranroig.client.wrapper.Logger` adapts a `LuaFunction` to print into the player chat. Decide carefully whether Lua runs client- or server-side; server-side is the apparent direction. - **Lua runtime**: `EditorManager.run()` sends a `ServerboundRunCodePayload`; `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 ## Conventions
@@ -42,6 +58,7 @@ Flow: client editor → custom payloads → server → persisted project.
## Status / gotchas ## Status / gotchas
- Work in progress: `EditorManager.newFile/undo/redo/stop` are empty stubs, server-side code execution is unimplemented, `com.aranroig.editor.Project` is a stub that is meant to replace the raw `List<EditorFile>` usage, and `EditorManager.files` is never populated (loading files from the server is an open TODO; `toggleVisible()` will NPE on `files.getFirst()`). - `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. - 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. - 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.

View File

@@ -6,6 +6,8 @@ Scripts are written in the in-game editor (`J` by default, rebindable under
This same documentation is browsable in-game from the editor: This same documentation is browsable in-game from the editor:
**Help → Lua API Documentation**, or press **F1** on a function while editing. **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 Because a script runs on the server thread from start to finish, everything it does
happens at once and the game waits for it to finish. Loops that place millions of happens at once and the game waits for it to finish. Loops that place millions of

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

@@ -12,7 +12,9 @@ import java.util.regex.Pattern;
* {@link LuaSnippets snippets}.</li> * {@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, backed by the * <li>Library member completion after a "." or ":" trigger, backed by the
* {@link LuaLibrary} instances loaded in {@link #registerLibraries()}.</li> * {@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
@@ -30,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",
@@ -42,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", "run", "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 + "("));
@@ -50,7 +57,7 @@ public class CompletionProvider {
// ── Built-in global tables (as types) ──────────────────────────── // ── Built-in global tables (as types) ────────────────────────────
for (String lib : new String[]{ for (String lib : new String[]{
"string", "table", "math", "io", "os", "coroutine", "string", "table", "math", "io", "os", "coroutine",
"package", "utf8", "debug", "_G", "_VERSION", "world", "events" "package", "utf8", "debug", "_G", "_VERSION"
}) items.add(CompletionItem.type(lib)); }) items.add(CompletionItem.type(lib));
// ── Common snippets ─────────────────────────────────────────────── // ── Common snippets ───────────────────────────────────────────────
@@ -63,15 +70,15 @@ public class CompletionProvider {
/** /**
* Loads the libraries whose members are offered after a dot or colon. * Loads the libraries whose members are offered after a dot or colon.
* To expose a new codecraft-provided table in the autocomplete popup, * Codecraft-provided tables come from the {@link com.aranroig.docs.LuaApiDocs}
* implement {@link LuaLibrary} and add an instance here. * catalog, so documenting a function in {@code lua-api.json} is all it takes
* to make it complete in the editor. To expose a plain Lua table, implement
* {@link LuaLibrary} and add an instance here.
*/ */
private static Map<String, List<CompletionItem>> registerLibraries() { private static Map<String, List<CompletionItem>> registerLibraries() {
List<LuaLibrary> libraries = new ArrayList<>(); List<LuaLibrary> libraries = new ArrayList<>();
libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library libraries.addAll(LuaStandardLibraries.all()); // Lua's own standard library
libraries.add(new WorldLibrary()); // block access provided by codecraft libraries.addAll(DocLibraries.libraries()); // codecraft globals, from the docs
libraries.add(new EventsLibrary()); // game event listeners provided by codecraft
libraries.addAll(MinecraftLibraries.all()); // server-side Minecraft APIs
Map<String, List<CompletionItem>> members = new LinkedHashMap<>(); Map<String, List<CompletionItem>> members = new LinkedHashMap<>();
for (LuaLibrary library : libraries) { for (LuaLibrary library : libraries) {

View File

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

View File

@@ -14,14 +14,23 @@ import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NonNull;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Set;
/** /**
* Modal documentation browser for the Lua functions this mod adds. * Modal documentation browser for the Lua functions this mod adds.
* *
* <p>Covers the whole editor screen (z-index 2, set in {@link EditorManager}) * <p>Covers the whole editor screen (z-index 2, set in {@link EditorManager})
* while visible: a dimmed backdrop, a scrollable list of topics/functions on * while visible: a dimmed backdrop, a scrollable list of topics/functions on
* the left and the rendered documentation of the selection on the right.</p> * the left and the rendered documentation of the selection on the right. The
* list is collapsible — the button at the left of the title bar, or Ctrl+B —
* which gives the documentation page the panel's full width, and each topic
* header folds away the functions under it like the file tree's folders.</p>
*
* <p>A search box above the list filters the functions by name and
* description while typing: Ctrl+F focuses it, the arrow keys walk the
* matches, Escape empties it and — once empty — lets go of it again.</p>
* *
* <p>Opened through {@link #open()} / {@link #open(String)} — the top bar's * <p>Opened through {@link #open()} / {@link #open(String)} — the top bar's
* <em>Help → Lua API Documentation</em> menu and <em>F1</em> in the file view. * <em>Help → Lua API Documentation</em> menu and <em>F1</em> in the file view.
@@ -48,6 +57,22 @@ public class EditorDocsPanel extends Widget {
/** Index into {@link #rows} of the current selection. */ /** Index into {@link #rows} of the current selection. */
private int selectedRow = 0; private int selectedRow = 0;
/** Whether the topic list on the left is hidden, leaving the page the full width. */
private boolean sidebarCollapsed = false;
/**
* Topics whose functions are folded away, keyed by their index into
* {@link #topics}. View state only — the list of topics is fixed.
*/
private final Set<Integer> foldedTopics = new HashSet<>();
/** Text of the search box above the list; blank means no filtering. */
private String searchQuery = "";
/** Caret offset into {@link #searchQuery}. */
private int searchCursor = 0;
/** Whether typing goes to the search box rather than being swallowed. */
private boolean searchFocused = false;
private int listScroll = 0; private int listScroll = 0;
private int detailScroll = 0; private int detailScroll = 0;
/** Height of the rendered detail page, measured while drawing, for clamping. */ /** Height of the rendered detail page, measured while drawing, for clamping. */
@@ -73,6 +98,65 @@ public class EditorDocsPanel extends Widget {
private static final int FUNC_INDENT = 10; private static final int FUNC_INDENT = 10;
private static final int SCROLL_SPEED = 3; private static final int SCROLL_SPEED = 3;
/** From the panel's left inset to a topic title (after its fold arrow) / to its functions. */
private static final int TOPIC_TEXT_X = PAD + 10;
private static final int FUNC_TEXT_X = PAD + 16;
// Pixel-pattern icons, '#' a pixel of the icon's colour and '.' nothing —
// the same style as the file tree's chevrons, so they stay sharp at any
// GUI scale.
/** Pointing left: clicking folds the topic list away. */
private static final String[] ICON_COLLAPSE = {
"...#",
"..#.",
".#..",
"#...",
".#..",
"..#.",
"...#",
};
/** Pointing right: clicking brings the topic list back. */
private static final String[] ICON_EXPAND = {
"#...",
".#..",
"..#.",
"...#",
"..#.",
".#..",
"#...",
};
/** Pointing right: the topic's functions are folded away. */
private static final String[] ICON_TOPIC_FOLDED = {
"#...",
".#..",
"..#.",
"...#",
"..#.",
".#..",
"#...",
};
/** Pointing down: the topic is unfolded and its functions are listed. */
private static final String[] ICON_TOPIC_OPEN = {
"#.....#",
".#...#.",
"..#.#..",
"...#...",
};
/** A magnifier: drawn at the left of the search box. */
private static final String[] ICON_SEARCH = {
".###..",
"#...#.",
"#...#.",
"#...#.",
".####.",
".....#",
};
public EditorDocsPanel(EditorManager editorManager) { public EditorDocsPanel(EditorManager editorManager) {
super(editorManager); super(editorManager);
} }
@@ -116,6 +200,9 @@ public class EditorDocsPanel extends Widget {
public void close() { public void close() {
visible = false; visible = false;
selectingCode = false; selectingCode = false;
searchFocused = false;
searchQuery = "";
searchCursor = 0;
if (editorScreen != null && editorScreen.selectedWidget == this) { if (editorScreen != null && editorScreen.selectedWidget == this) {
editorScreen.selectedWidget = null; editorScreen.selectedWidget = null;
} }
@@ -126,11 +213,14 @@ public class EditorDocsPanel extends Widget {
} }
private void selectByName(String word) { private void selectByName(String word) {
// A jump shows the whole list again: a leftover filter could hide the row.
searchQuery = "";
searchCursor = 0;
// Exact match first, then the unqualified last segment. // Exact match first, then the unqualified last segment.
for (int i = 0; i < rows.size(); i++) { for (int i = 0; i < rows.size(); i++) {
Row row = rows.get(i); Row row = rows.get(i);
if (row.isFunction() && row.label().equalsIgnoreCase(word)) { if (row.isFunction() && row.label().equalsIgnoreCase(word)) {
selectRow(i); revealRow(i);
return; return;
} }
} }
@@ -138,12 +228,97 @@ public class EditorDocsPanel extends Widget {
Row row = rows.get(i); Row row = rows.get(i);
if (row.isFunction() if (row.isFunction()
&& row.label().toLowerCase().endsWith("." + word.toLowerCase())) { && row.label().toLowerCase().endsWith("." + word.toLowerCase())) {
selectRow(i); revealRow(i);
return; return;
} }
} }
} }
/** Folds or unfolds a topic: its functions come and go with it. */
private void toggleTopicFolded(int topic) {
if (!foldedTopics.remove(topic)) foldedTopics.add(topic);
clampListScroll();
}
/** Selects a row, unfolding its topic first so the list shows what was picked. */
private void revealRow(int index) {
foldedTopics.remove(rows.get(index).topic());
selectRow(index);
}
/**
* Indices into {@link #rows} of the rows on display: while the search box
* is blank, every topic plus the functions of those unfolded; while it
* holds a query, the functions whose name or description match, and the
* headers of the topics that match or hold a match — folding is ignored
* while searching, so every match is reachable. Positions and scrolling
* work on these.
*/
private List<Integer> visibleRows() {
String query = searchQuery.trim().toLowerCase();
List<Integer> visible = new ArrayList<>(rows.size());
for (int i = 0; i < rows.size(); i++) {
Row row = rows.get(i);
if (query.isEmpty()) {
if (!row.isFunction() || !foldedTopics.contains(row.topic())) visible.add(i);
} else if (row.isFunction()) {
if (functionMatches(topics.get(row.topic()).functions().get(row.function()), query)) {
visible.add(i);
}
} else if (topicMatches(row.topic(), query)) {
visible.add(i);
}
}
return visible;
}
private static boolean functionMatches(FunctionDoc function, String query) {
return matches(function.name(), query) || matches(function.summary(), query);
}
/** The topic itself or one of its functions matches; keeps its header on display. */
private boolean topicMatches(int topic, String query) {
Topic t = topics.get(topic);
if (matches(t.title(), query) || matches(t.blurb(), query)) return true;
for (FunctionDoc function : t.functions()) {
if (functionMatches(function, query)) return true;
}
return false;
}
private static boolean matches(String text, String query) {
return text != null && text.toLowerCase().contains(query);
}
/**
* The search query changed: keep the selection while it is still on
* display, else follow the first matching function (or first row left).
*/
private void onSearchEdited() {
List<Integer> visible = visibleRows();
if (!visible.contains(selectedRow)) {
int next = -1;
for (int i : visible) {
if (rows.get(i).isFunction()) { next = i; break; }
if (next < 0) next = i; // a header, when there are no function matches at all
}
if (next >= 0) selectRow(next);
}
listScroll = 0;
scrollSelectionIntoView();
}
/** Moves the selection by one visible row and scrolls it into view (arrow keys). */
private void selectRelative(int step) {
List<Integer> visible = visibleRows();
if (visible.isEmpty()) return;
int pos = visible.indexOf(selectedRow);
if (pos < 0) pos = step > 0 ? -1 : 0; // hidden by a folded topic: restart from the top
pos = Math.max(0, Math.min(pos + step, visible.size() - 1));
selectRow(visible.get(pos));
scrollSelectionIntoView();
}
private void selectRow(int index) { private void selectRow(int index) {
selectedRow = index; selectedRow = index;
detailScroll = 0; detailScroll = 0;
@@ -153,13 +328,15 @@ public class EditorDocsPanel extends Widget {
} }
private void scrollSelectionIntoView() { private void scrollSelectionIntoView() {
int pos = visibleRows().indexOf(selectedRow);
if (pos < 0) return; // hidden by a folded topic, nothing to scroll to
int rowH = rowHeight(); int rowH = rowHeight();
int top = rowHeight() * selectedRow - listScroll; int top = rowH * pos - listScroll;
int viewH = listAreaBottom() - listTop(); int viewH = listAreaBottom() - listTop();
if (top < 0) { if (top < 0) {
listScroll = rowHeight() * selectedRow; listScroll = rowH * pos;
} else if (top + rowH > viewH) { } else if (top + rowH > viewH) {
listScroll = rowHeight() * selectedRow + rowH - viewH; listScroll = rowH * pos + rowH - viewH;
} }
clampListScroll(); clampListScroll();
} }
@@ -175,14 +352,23 @@ public class EditorDocsPanel extends Widget {
private int panelX2() { return getEndX() - MARGIN; } private int panelX2() { return getEndX() - MARGIN; }
private int panelY2() { return getEndY() - MARGIN; } private int panelY2() { return getEndY() - MARGIN; }
private int listX2() { return panelX1() + LIST_WIDTH; } /** The list's right edge; at the panel's left edge while collapsed. */
private int listTop() { return panelY1() + titleHeight(); } private int listX2() { return panelX1() + (sidebarCollapsed ? 0 : LIST_WIDTH); }
/** Below the title bar, where both content columns start. */
private int detailAreaTop() { return panelY1() + titleHeight(); }
private int listTop() { return detailAreaTop() + (sidebarCollapsed ? 0 : searchHeight()); }
private int listAreaBottom() { return panelY2(); } private int listAreaBottom() { return panelY2(); }
private int detailX() { return listX2() + PAD + 1; } private int detailX() { return listX2() + PAD + 1; }
private int detailTop() { return listTop() + PAD; } private int detailTop() { return detailAreaTop() + PAD; }
private int searchTop() { return detailAreaTop(); }
private int searchBottom() { return detailAreaTop() + searchHeight(); }
private int searchHeight() { return lineHeight() + PAD; }
/** Where the query text begins, after the magnifier icon. */
private int searchTextX() { return panelX1() + PAD + ICON_SEARCH[0].length() + 6; }
private int maxListScroll() { private int maxListScroll() {
return Math.max(0, rows.size() * rowHeight() - (listAreaBottom() - listTop())); return Math.max(0, visibleRows().size() * rowHeight() - (listAreaBottom() - listTop()));
} }
private void clampListScroll() { private void clampListScroll() {
@@ -195,6 +381,17 @@ public class EditorDocsPanel extends Widget {
&& my >= panelY1() && my < panelY1() + buttonSize; && my >= panelY1() && my < panelY1() + buttonSize;
} }
private boolean insideSidebarToggle(int mx, int my) {
int buttonSize = titleHeight();
return mx >= panelX1() + 1 && mx < panelX1() + 1 + buttonSize
&& my >= panelY1() && my < panelY1() + buttonSize;
}
private boolean insideSearchBox(int mx, int my) {
return !sidebarCollapsed && mx >= panelX1() + 1 && mx < listX2() - 1
&& my >= searchTop() && my < searchBottom();
}
private FunctionDoc selectedFunction() { private FunctionDoc selectedFunction() {
Row row = rows.get(selectedRow); Row row = rows.get(selectedRow);
return row.isFunction() ? topics.get(row.topic()).functions().get(row.function()) : null; return row.isFunction() ? topics.get(row.topic()).functions().get(row.function()) : null;
@@ -216,7 +413,7 @@ public class EditorDocsPanel extends Widget {
clampListScroll(); clampListScroll();
detailScroll = Math.max(0, Math.min(detailScroll, detailScroll = Math.max(0, Math.min(detailScroll,
Math.max(0, detailContentHeight - (panelY2() - listTop() - PAD * 2)))); Math.max(0, detailContentHeight - (panelY2() - detailTop() - PAD))));
// Backdrop + panel // Backdrop + panel
graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().overlay()); graphics.fill(getStartX(), getStartY(), getEndX(), getEndY(), editorManager.theme().overlay());
@@ -227,8 +424,11 @@ public class EditorDocsPanel extends Widget {
graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), editorManager.theme().border()); // right graphics.fill(panelX2() - 1, panelY1(), panelX2(), panelY2(), editorManager.theme().border()); // right
drawTitleBar(graphics); drawTitleBar(graphics);
drawSearchBox(graphics);
drawList(graphics, mouseX, mouseY); drawList(graphics, mouseX, mouseY);
graphics.fill(listX2() - 1, listTop(), listX2(), panelY2() - 1, editorManager.theme().border()); if (!sidebarCollapsed) {
graphics.fill(listX2() - 1, detailAreaTop(), listX2(), panelY2() - 1, editorManager.theme().border());
}
drawDetail(graphics); drawDetail(graphics);
} }
@@ -236,11 +436,22 @@ public class EditorDocsPanel extends Widget {
int titleH = titleHeight(); int titleH = titleHeight();
graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, editorManager.theme().raisedBackground()); graphics.fill(panelX1() + 1, panelY1(), panelX2() - 1, panelY1() + titleH, editorManager.theme().raisedBackground());
// Sidebar toggle, sitting at the top of the list it shows and hides.
int buttonSize = titleH;
int toggleX = panelX1() + 1;
boolean toggleHovered = mouseX >= toggleX && mouseX < toggleX + buttonSize
&& mouseY >= panelY1() && mouseY < panelY1() + titleH;
if (toggleHovered) {
graphics.fill(toggleX, panelY1(), toggleX + buttonSize, panelY1() + titleH, editorManager.theme().hoverBackground());
}
drawIcon(graphics, sidebarCollapsed ? ICON_EXPAND : ICON_COLLAPSE,
toggleX, panelY1(), buttonSize, editorManager.theme().mutedText());
int titleX = toggleX + buttonSize;
graphics.text(font, "Lua API documentation", graphics.text(font, "Lua API documentation",
panelX1() + PAD, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false); titleX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Close button // Close button
int buttonSize = titleH;
int bx = panelX2() - buttonSize; int bx = panelX2() - buttonSize;
boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH; boolean hovered = mouseX >= bx && mouseX < panelX2() && mouseY >= panelY1() && mouseY < panelY1() + titleH;
if (hovered) { if (hovered) {
@@ -251,24 +462,106 @@ public class EditorDocsPanel extends Widget {
panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false); panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().text(), false);
// Hint, right-aligned before the button // Hint, right-aligned before the button
String hint = "F1 in the editor opens docs on the word under the cursor"; String hint = "Ctrl+F searches · F1 in the editor opens docs on the word under the cursor";
int hintX = bx - 8 - font.width(hint); int hintX = bx - 8 - font.width(hint);
if (hintX > panelX1() + font.width("Lua API documentation") + 12) { if (hintX > titleX + font.width("Lua API documentation") + 12) {
graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().hint(), false); graphics.text(font, hint, hintX, panelY1() + (titleH - lineHeight()) / 2, editorManager.theme().hint(), false);
} }
} }
/**
* The search box between title bar and topic list: magnifier, placeholder
* or query, and a blinking caret while focused. Long queries shift left so
* the caret stays visible.
*/
private void drawSearchBox(@NonNull GuiGraphicsExtractor graphics) {
if (sidebarCollapsed) return;
int top = searchTop();
int bottom = searchBottom();
int textY = top + (searchHeight() - lineHeight()) / 2;
int textX = searchTextX();
graphics.fill(panelX1() + 1, top, listX2() - 1, bottom, editorManager.theme().raisedBackground());
graphics.fill(panelX1() + 1, bottom - 1, listX2() - 1, bottom, editorManager.theme().border());
drawRowIcon(graphics, ICON_SEARCH, panelX1() + PAD - 1, top, searchHeight(),
searchFocused ? editorManager.theme().text() : editorManager.theme().mutedText());
if (searchQuery.isEmpty()) {
graphics.text(font, "Search…", textX, textY, editorManager.theme().hint(), false);
} else {
int shift = searchShift();
graphics.enableScissor(textX, top, listX2() - 2, bottom - 1);
graphics.text(font, searchQuery, textX - shift, textY, editorManager.theme().text(), false);
graphics.disableScissor();
}
if (searchFocused && (System.currentTimeMillis() / 500) % 2 == 0) {
int caretX = textX - searchShift()
+ font.width(searchQuery.substring(0, searchCursor));
if (caretX >= textX && caretX < listX2() - 1) {
graphics.fill(caretX, textY, caretX + 1, textY + lineHeight(),
editorManager.theme().cursor());
}
}
}
/** How far the query shifts left so the caret does not leave the box. */
private int searchShift() {
int caretWidth = font.width(searchQuery.substring(0, searchCursor));
return Math.max(0, caretWidth - (listX2() - 2 - searchTextX()) + 4);
}
/** Caret offset of a click inside the search box. */
private int searchCaretAt(int mx) {
int x = mx + searchShift();
int best = 0;
for (int i = 1; i <= searchQuery.length(); i++) {
if (x >= searchTextX() + font.width(searchQuery.substring(0, i))) best = i;
}
return best;
}
/** Centres a pixel glyph in a square button and paints it pixel by pixel. */
private static void drawIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int buttonSize, int colour) {
x += (buttonSize - glyph[0].length()) / 2;
y += (buttonSize - glyph.length) / 2;
paintGlyph(graphics, glyph, x, y, colour);
}
/** Centres a pixel glyph vertically in a list row, flush at {@code x}. */
private static void drawRowIcon(GuiGraphicsExtractor graphics, String[] glyph, int x, int y, int rowH, int colour) {
paintGlyph(graphics, glyph, x, y + (rowH - glyph.length) / 2, colour);
}
/** Paints a glyph pixel by pixel, top-left at {@code (x, y)}. */
private static void paintGlyph(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);
}
}
}
private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) { private void drawList(@NonNull GuiGraphicsExtractor graphics, int mouseX, int mouseY) {
if (sidebarCollapsed) return;
graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1); graphics.enableScissor(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1);
graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, editorManager.theme().sidebarBackground()); graphics.fill(panelX1() + 1, listTop(), listX2() - 1, panelY2() - 1, editorManager.theme().sidebarBackground());
int rowH = rowHeight(); int rowH = rowHeight();
for (int i = 0; i < rows.size(); i++) { List<Integer> visible = visibleRows();
Row row = rows.get(i); if (visible.isEmpty() && !searchQuery.isBlank()) {
graphics.text(font, "No matches", panelX1() + FUNC_TEXT_X,
listTop() + PAD, editorManager.theme().mutedText(), false);
}
for (int i = 0; i < visible.size(); i++) {
int rowIndex = visible.get(i);
Row row = rows.get(rowIndex);
int y = listTop() + i * rowH - listScroll; int y = listTop() + i * rowH - listScroll;
if (y + rowH < listTop() || y > panelY2()) continue; if (y + rowH < listTop() || y > panelY2()) continue;
boolean selected = i == selectedRow; boolean selected = rowIndex == selectedRow;
boolean hovered = mouseX >= panelX1() && mouseX < listX2() boolean hovered = mouseX >= panelX1() && mouseX < listX2()
&& mouseY >= y && mouseY < y + rowH; && mouseY >= y && mouseY < y + rowH;
if (selected) { if (selected) {
@@ -278,10 +571,13 @@ public class EditorDocsPanel extends Widget {
} }
if (row.isFunction()) { if (row.isFunction()) {
graphics.text(font, row.label(), panelX1() + PAD + FUNC_INDENT, graphics.text(font, row.label(), panelX1() + FUNC_TEXT_X,
y + ROW_PAD / 2, editorManager.theme().text(), false); y + ROW_PAD / 2, editorManager.theme().text(), false);
} else { } else {
graphics.text(font, row.label(), panelX1() + PAD, boolean folded = foldedTopics.contains(row.topic());
drawRowIcon(graphics, folded ? ICON_TOPIC_FOLDED : ICON_TOPIC_OPEN,
panelX1() + PAD, y, rowH, editorManager.theme().mutedText());
graphics.text(font, row.label(), panelX1() + TOPIC_TEXT_X,
y + ROW_PAD / 2, editorManager.theme().syntaxBuiltin(), true); y + ROW_PAD / 2, editorManager.theme().syntaxBuiltin(), true);
} }
} }
@@ -296,7 +592,7 @@ public class EditorDocsPanel extends Widget {
int maxWidth = panelX2() - PAD - x; int maxWidth = panelX2() - PAD - x;
int y = detailTop() - detailScroll; int y = detailTop() - detailScroll;
graphics.enableScissor(listX2(), listTop(), panelX2() - 1, panelY2() - 1); graphics.enableScissor(listX2(), detailAreaTop(), panelX2() - 1, panelY2() - 1);
FunctionDoc function = selectedFunction(); FunctionDoc function = selectedFunction();
if (function == null) { if (function == null) {
@@ -467,7 +763,7 @@ public class EditorDocsPanel extends Widget {
} }
private CodeBlockLayout codeBlockAt(double x, double y) { private CodeBlockLayout codeBlockAt(double x, double y) {
if (x < listX2() || x >= panelX2() - 1 || y < listTop() || y >= panelY2() - 1) return null; if (x < listX2() || x >= panelX2() - 1 || y < detailAreaTop() || y >= panelY2() - 1) return null;
for (CodeBlockLayout block : codeBlocks) { for (CodeBlockLayout block : codeBlocks) {
if (x >= block.x() && x <= block.x() + block.width() if (x >= block.x() && x <= block.x() + block.width()
&& y >= block.y() && y < block.y() + block.height()) return block; && y >= block.y() && y < block.y() + block.height()) return block;
@@ -519,16 +815,35 @@ public class EditorDocsPanel extends Widget {
close(); close();
return true; return true;
} }
if (insideSidebarToggle(mx, my)) {
sidebarCollapsed = !sidebarCollapsed;
if (sidebarCollapsed) searchFocused = false; // the box hides with the list
else scrollSelectionIntoView();
return true;
}
// Left list: select the clicked row. // Search box: focus it and place the caret where the click landed.
if (insideSearchBox(mx, my)) {
searchFocused = true;
searchCursor = searchCaretAt(mx);
selectingCode = false;
activeExample = -1;
return true;
}
// Left list: select the clicked row, folding or unfolding on a topic.
if (mx < listX2() && my >= listTop()) { if (mx < listX2() && my >= listTop()) {
selectingCode = false; selectingCode = false;
activeExample = -1; activeExample = -1;
selectionAnchor = -1; selectionAnchor = -1;
selectionCursor = -1; selectionCursor = -1;
int index = (my - listTop() + listScroll) / rowHeight(); int pos = (my - listTop() + listScroll) / rowHeight();
if (index >= 0 && index < rows.size()) { List<Integer> visible = visibleRows();
selectRow(index); if (pos >= 0 && pos < visible.size()) {
int rowIndex = visible.get(pos);
Row row = rows.get(rowIndex);
if (!row.isFunction()) toggleTopicFolded(row.topic());
selectRow(rowIndex);
} }
return true; return true;
} }
@@ -546,6 +861,7 @@ public class EditorDocsPanel extends Widget {
selectionAnchor = -1; selectionAnchor = -1;
selectionCursor = -1; selectionCursor = -1;
selectingCode = false; selectingCode = false;
searchFocused = false; // clicking the page takes the keyboard off the search box
// Anything else inside the panel is consumed (scrolling happens per-column). // Anything else inside the panel is consumed (scrolling happens per-column).
return true; return true;
@@ -554,6 +870,55 @@ public class EditorDocsPanel extends Widget {
@Override @Override
public boolean handleKeyPressed(KeyEvent event) { public boolean handleKeyPressed(KeyEvent event) {
if (!visible) return false; if (!visible) return false;
if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B — fold/unfold the topic list, like in the editor
sidebarCollapsed = !sidebarCollapsed;
if (sidebarCollapsed) searchFocused = false;
else scrollSelectionIntoView();
return true;
}
if (event.key() == 70 && event.hasControlDown()) { // Ctrl+F — focus the search box
sidebarCollapsed = false; // the box lives with the list
searchFocused = true;
scrollSelectionIntoView();
return true;
}
if (searchFocused) {
switch (event.key()) {
case 259 -> { // Backspace
if (searchCursor > 0) {
searchQuery = searchQuery.substring(0, searchCursor - 1)
+ searchQuery.substring(searchCursor);
searchCursor--;
onSearchEdited();
}
return true;
}
case 261 -> { // Delete
if (searchCursor < searchQuery.length()) {
searchQuery = searchQuery.substring(0, searchCursor)
+ searchQuery.substring(searchCursor + 1);
onSearchEdited();
}
return true;
}
case 263 -> { searchCursor = Math.max(0, searchCursor - 1); return true; } // Left
case 262 -> { searchCursor = Math.min(searchQuery.length(), searchCursor + 1); return true; } // Right
case 268 -> { searchCursor = 0; return true; } // Home
case 269 -> { searchCursor = searchQuery.length(); return true; } // End
case 257 -> { searchFocused = false; return true; } // Enter — settle on the highlighted match
case 256 -> { // Escape — first empties the box, then lets go of it
if (!searchQuery.isEmpty()) {
searchQuery = "";
searchCursor = 0;
onSearchEdited();
} else {
searchFocused = false;
}
return true;
}
}
// Up and Down still walk the filtered list, handled below.
}
if (activeExample >= 0 && event.hasControlDown()) { if (activeExample >= 0 && event.hasControlDown()) {
CodeBlockLayout block = activeCodeBlock(); CodeBlockLayout block = activeCodeBlock();
if (block != null) { if (block != null) {
@@ -578,13 +943,11 @@ public class EditorDocsPanel extends Widget {
return true; return true;
} }
case 264 -> { // Down case 264 -> { // Down
selectRow(Math.min(selectedRow + 1, rows.size() - 1)); selectRelative(1);
scrollSelectionIntoView();
return true; return true;
} }
case 265 -> { // Up case 265 -> { // Up
selectRow(Math.max(selectedRow - 1, 0)); selectRelative(-1);
scrollSelectionIntoView();
return true; return true;
} }
} }
@@ -593,7 +956,19 @@ public class EditorDocsPanel extends Widget {
@Override @Override
public boolean handleCharTyped(CharacterEvent event) { public boolean handleCharTyped(CharacterEvent event) {
return visible; // swallow typing while the modal is open if (!visible) return false;
if (searchFocused) {
int codePoint = event.codepoint();
if (codePoint >= 32 && codePoint != 127) { // printable characters filter the list
String typed = Character.toString(codePoint);
searchQuery = searchQuery.substring(0, searchCursor) + typed
+ searchQuery.substring(searchCursor);
searchCursor += typed.length();
onSearchEdited();
}
return true;
}
return true; // swallow typing while the modal is open
} }
@Override @Override

View File

@@ -1,5 +1,7 @@
package com.aranroig.client.editor; package com.aranroig.client.editor;
import com.aranroig.docs.FunctionDoc;
import com.aranroig.docs.ParamDoc;
import com.aranroig.editor.Edit; import com.aranroig.editor.Edit;
import com.aranroig.editor.EditorFile; import com.aranroig.editor.EditorFile;
import com.aranroig.editor.EditorPresence; import com.aranroig.editor.EditorPresence;
@@ -11,6 +13,7 @@ import net.minecraft.client.input.KeyEvent;
import net.minecraft.client.input.MouseButtonEvent; import net.minecraft.client.input.MouseButtonEvent;
import org.jspecify.annotations.NonNull; import org.jspecify.annotations.NonNull;
import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -59,6 +62,9 @@ public class EditorFileView extends EditorPane {
private final CompletionProvider completionProvider = new CompletionProvider(); private final CompletionProvider completionProvider = new CompletionProvider();
private final LuaHighlighter luaHighlighter = new LuaHighlighter(); private final LuaHighlighter luaHighlighter = new LuaHighlighter();
/** What Ctrl+Z and Ctrl+Shift+Z take back and give forward again. */
private final EditHistory history = new EditHistory();
/** /**
* Per-line multiline-string continuation state, rebuilt whenever the text * Per-line multiline-string continuation state, rebuilt whenever the text
* changes. Index {@code i} is {@code true} when line {@code i} is inside a * changes. Index {@code i} is {@code true} when line {@code i} is inside a
@@ -82,6 +88,12 @@ public class EditorFileView extends EditorPane {
private static final int POPUP_WIDTH = 240; private static final int POPUP_WIDTH = 240;
private static final int KIND_BADGE_WIDTH = 4; // coloured left strip private static final int KIND_BADGE_WIDTH = 4; // coloured left strip
// Documentation box shown next to the completion popup
private static final int DOC_MAX_WIDTH = 340; // clamped to the pane width
private static final int DOC_GAP = 3; // popup ↔ documentation box
private static final int DOC_PADDING = 4;
private static final int DOC_INDENT = 8; // wrapped parameter descriptions
// ───────────────────────────────────────────────────────────────────── // ─────────────────────────────────────────────────────────────────────
private String[] getLines() { private String[] getLines() {
@@ -198,16 +210,20 @@ public class EditorFileView extends EditorPane {
/** /**
* The only place the buffer changes because the local player asked for it: * The only place the buffer changes because the local player asked for it:
* applies the change here and reports it to {@link EditorManager}, which * remembers the change for undo, applies it here and reports it to
* forwards it to the server so everyone else editing this file sees it. * {@link EditorManager}, which forwards it to the server so everyone else
* Every keystroke goes through this, so the shared copy of the file stays * editing this file sees it. Every keystroke goes through this, so the
* complete without waiting for a save. * shared copy of the file stays complete without waiting for a save.
*/ */
private void applyLocalEdit(int position, int deleteLength, String insert) { private void applyLocalEdit(int position, int deleteLength, String insert) {
int start = Math.max(0, Math.min(position, text.length())); int start = Math.max(0, Math.min(position, text.length()));
int end = Math.max(start, Math.min(start + deleteLength, text.length())); int end = Math.max(start, Math.min(start + deleteLength, text.length()));
String deleted = text.substring(start, end);
text.replace(start, end, insert); text.replace(start, end, insert);
history.recordLocalEdit(start, deleted, insert, cursorPos, selectionAnchor);
if (currentEditorFile != null) { if (currentEditorFile != null) {
editorManager.submitEdit(currentEditorFile, text.toString(), start, end - start, insert); editorManager.submitEdit(currentEditorFile, text.toString(), start, end - start, insert);
} }
@@ -228,6 +244,11 @@ public class EditorFileView extends EditorPane {
editorManager.requestDocumentSync(currentEditorFile); editorManager.requestDocumentSync(currentEditorFile);
} }
// Everything remembered for undo was written against the text as it
// stands before this lands; rewrite the walks — and the carets they
// would restore — to speak about the text as it will stand after.
history.rebaseAgainst(edit);
int newCursor = edit.shiftPosition(cursorPos); int newCursor = edit.shiftPosition(cursorPos);
if (selectionAnchor >= 0) selectionAnchor = edit.shiftPosition(selectionAnchor); if (selectionAnchor >= 0) selectionAnchor = edit.shiftPosition(selectionAnchor);
@@ -261,9 +282,50 @@ public class EditorFileView extends EditorPane {
cursorPos = Math.min(cursorPos, text.length()); cursorPos = Math.min(cursorPos, text.length());
if (selectionAnchor > text.length()) selectionAnchor = text.length(); if (selectionAnchor > text.length()) selectionAnchor = text.length();
if (currentEditorFile != null) currentEditorFile.setText(serverText); if (currentEditorFile != null) currentEditorFile.setText(serverText);
history.clear(); // the buffer is the server's text now: nothing remembered fits it
dismissCompletions(); dismissCompletions();
} }
// ── Undo and redo ─────────────────────────────────────────────────────
/**
* Ctrl+Z: takes the last change remembered here back. Applying it is an
* edit like any other — the buffer changes at once and the server and the
* other editors are told, so undoing is itself a change everyone sees —
* and what it gives back goes onto the redo stack for {@link #redo()}.
*/
public void undo() {
applyRemembered(history.takeUndo(), true);
}
/** Ctrl+Shift+Z: takes away again what {@link #undo()} gave back. */
public void redo() {
applyRemembered(history.takeRedo(), false);
}
private void applyRemembered(EditHistory.Entry step, boolean undoing) {
if (step == null || currentEditorFile == null) return;
// What this step writes back, going the other way again has to take
// out; worked out while the buffer still holds what is being erased.
Edit inverse = step.operation().invert(text.toString());
int caretBefore = cursorPos;
int anchorBefore = selectionAnchor;
text = new StringBuilder(step.operation().apply(text.toString()));
editorManager.submitEdit(currentEditorFile, text.toString(), step.operation());
cursorPos = Math.min(step.caret(), text.length());
selectionAnchor = step.selectionAnchor() < 0 ? -1 : Math.min(step.selectionAnchor(), text.length());
EditHistory.Entry otherWay = new EditHistory.Entry(inverse, caretBefore, anchorBefore);
if (undoing) history.putRedo(otherWay);
else history.putUndo(otherWay);
dismissCompletions();
scrollToCursor();
}
/** Who else has this file open, and where their carets are. */ /** Who else has this file open, and where their carets are. */
private List<EditorPresence> remoteEditors = Collections.emptyList(); private List<EditorPresence> remoteEditors = Collections.emptyList();
@@ -449,6 +511,12 @@ public class EditorFileView extends EditorPane {
transparent(editor.color(), 0x4D)); transparent(editor.color(), 0x4D));
} }
List<Integer> findMatches = editorManager.findMatchOffsets(this);
int findMatchLength = editorManager.findQueryLength(this);
int activeFindOffset = editorManager.activeFindMatchOffset(this);
int lineStartOffset = 0;
for (int i = 0; i < firstLine; i++) lineStartOffset += lines[i].length() + 1;
// Line numbers + text // Line numbers + text
for (int i = firstLine; i <= lastLine; i++) { for (int i = firstLine; i <= lastLine; i++) {
int screenY = start_y + i * lineH - scrollY; int screenY = start_y + i * lineH - scrollY;
@@ -459,8 +527,11 @@ public class EditorFileView extends EditorPane {
gutterDivX() - 4 - numW, gutterDivX() - 4 - numW,
screenY, editorManager.theme().mutedText(), false); screenY, editorManager.theme().mutedText(), false);
drawFindHighlights(graphics, lines[i], lineStartOffset, screenY,
findMatches, findMatchLength, activeFindOffset);
boolean lineInMultiline = (i < multilineState.length) && multilineState[i]; boolean lineInMultiline = (i < multilineState.length) && multilineState[i];
drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline); drawHighlightedLine(graphics, lines[i], textAreaX() - scrollX, screenY, lineInMultiline);
lineStartOffset += lines[i].length() + 1;
} }
// Other players' carets in this file, each in the colour the server gave them // Other players' carets in this file, each in the colour the server gave them
@@ -521,6 +592,28 @@ public class EditorFileView extends EditorPane {
} }
} }
/** Draws every in-file find hit behind its source text, with the current hit brighter. */
private void drawFindHighlights(GuiGraphicsExtractor graphics, String line, int lineStart, int screenY,
List<Integer> matches, int matchLength, int activeOffset) {
if (matchLength <= 0 || matches.isEmpty()) return;
int lineEnd = lineStart + line.length();
for (int offset : matches) {
int matchEnd = offset + matchLength;
int from = Math.max(offset, lineStart);
int to = Math.min(matchEnd, lineEnd);
if (from >= to) continue;
int fromColumn = from - lineStart;
int toColumn = to - lineStart;
int x = textAreaX() + widthUpTo(line, fromColumn) - scrollX;
int right = textAreaX() + widthUpTo(line, toColumn) - scrollX;
int color = offset == activeOffset
? transparent(editorManager.theme().accent(), 0xA0)
: transparent(editorManager.theme().folder(), 0x66);
graphics.fill(x, screenY, Math.max(x + 1, right), screenY + font.lineHeight, color);
}
}
/** /**
* Draws one remote player's caret, in the colour the server assigned them, * Draws one remote player's caret, in the colour the server assigned them,
* with their name next to it so several people in the same file are * with their name next to it so several people in the same file are
@@ -634,12 +727,343 @@ public class EditorFileView extends EditorPane {
} }
} }
// Hint line below the popup when more than one item is present // Documentation for the highlighted item, rendered as a multi-line box
if (completions.size() > 1) { // below (or above) the popup, followed by the navigation hint.
int hintY = py + popupH + 2; drawCompletionDocs(graphics, px, py, popupH);
String hint = "↑↓ navigate Tab/Enter accept Esc dismiss";
graphics.text(font, hint, px, hintY, editorManager.theme().hint(), false);
} }
// ── Completion documentation box ──────────────────────────────────────
/** One styled run inside a documentation line. */
private record DocRun(String text, int color, boolean bold) {}
/** One documentation line built of coloured runs; empty runs = blank line. */
private record DocLine(List<DocRun> runs) {
static final DocLine BLANK = new DocLine(List.of());
}
/**
* Renders the API documentation of the highlighted completion in a
* multi-line box — the same sections as the documentation panel
* (signature, description, parameters, returns, notes), minus examples.
* Prefers the space below the popup, falls back above it, and truncates
* with an ellipsis when neither side can hold it.
*/
private void drawCompletionDocs(GuiGraphicsExtractor graphics, int px, int py, int popupH) {
CompletionItem.Docs docs = completions.get(completionIndex).docs();
int width = Math.min(DOC_MAX_WIDTH, getEndX() - getStartX() - 4);
int boxX = Math.max(getStartX() + 2, Math.min(px, getEndX() - width - 2));
List<DocLine> lines = docs == null
? List.of()
: layoutCompletionDocs(docs, width - DOC_PADDING * 2);
int boxY = -1;
if (!lines.isEmpty()) {
int docsH = lines.size() * font.lineHeight + DOC_PADDING * 2;
if (py + popupH + DOC_GAP + docsH <= getEndY()) {
boxY = py + popupH + DOC_GAP; // fits below the popup
} else if (py - DOC_GAP - docsH >= getStartY()) {
boxY = py - DOC_GAP - docsH; // fits above the popup
} else {
// Neither side holds it whole: clip below the popup, marked with …
int visible = (getEndY() - (py + popupH + DOC_GAP) - DOC_PADDING * 2) / font.lineHeight - 1;
if (visible >= 1) {
lines = new ArrayList<>(lines.subList(0, Math.min(visible, lines.size())));
lines.add(new DocLine(List.of(
new DocRun("…", editorManager.theme().mutedText(), false))));
boxY = py + popupH + DOC_GAP;
}
}
}
if (boxY < 0) {
drawCompletionHint(graphics, px, py + popupH + 2);
return;
}
// Shadow + background + border, in the popup's style.
int docsH = lines.size() * font.lineHeight + DOC_PADDING * 2;
graphics.fill(boxX + 2, boxY + 2, boxX + width + 2, boxY + docsH + 2,
transparent(editorManager.theme().background(), 0x55));
graphics.fill(boxX, boxY, boxX + width, boxY + docsH, editorManager.theme().raisedBackground());
graphics.fill(boxX, boxY, boxX + width, boxY + 1, editorManager.theme().border());
graphics.fill(boxX, boxY + docsH - 1, boxX + width, boxY + docsH, editorManager.theme().border());
graphics.fill(boxX, boxY, boxX + 1, boxY + docsH, editorManager.theme().border());
graphics.fill(boxX + width - 1, boxY, boxX + width, boxY + docsH, editorManager.theme().border());
int textY = boxY + DOC_PADDING;
for (DocLine line : lines) {
int textX = boxX + DOC_PADDING;
for (DocRun run : line.runs()) {
graphics.text(font, run.text(), textX, textY, run.color(), run.bold());
textX += font.width(run.text());
}
textY += font.lineHeight;
}
// Hint under whichever element ends last (box above the popup would
// otherwise overlap the popup with it).
int hintY = (boxY + docsH <= py) ? py + popupH + 2 : boxY + docsH + 2;
drawCompletionHint(graphics, boxX, hintY);
}
private void drawCompletionHint(GuiGraphicsExtractor graphics, int x, int y) {
if (completions.size() <= 1 || y + font.lineHeight > getEndY()) return;
graphics.text(font, "↑↓ navigate Tab/Enter accept Esc dismiss", x, y,
editorManager.theme().hint(), false);
}
/** Builds the wrapped, coloured documentation lines for one completion. */
private List<DocLine> layoutCompletionDocs(CompletionItem.Docs docs, int maxWidth) {
EditorTheme.Palette theme = editorManager.theme();
List<DocLine> lines = new ArrayList<>();
FunctionDoc function = docs.function();
if (function == null) {
// Plain documented table: its name and the topic blurb.
lines.add(docHeader(docs.name(), theme.syntaxBuiltin()));
addWrapped(lines, docs.blurb(), maxWidth, theme.syntaxDefault(), 0);
return lines;
}
addWrapped(lines, function.signature(), maxWidth, theme.syntaxMethod(), 0);
if (!function.summary().isEmpty()) {
lines.add(DocLine.BLANK);
lines.add(docHeader("Description", theme.syntaxKeyword()));
addWrapped(lines, function.summary(), maxWidth, theme.syntaxDefault(), 0);
}
if (!function.params().isEmpty()) {
lines.add(DocLine.BLANK);
lines.add(docHeader("Parameters", theme.syntaxKeyword()));
for (ParamDoc param : function.params()) {
String suffix = param.optional() ? " (optional)" : "";
lines.add(new DocLine(List.of(
new DocRun(param.name(), theme.syntaxParam(), false),
new DocRun(" · " + param.type() + suffix, theme.mutedText(), false))));
addWrapped(lines, param.description(), maxWidth, theme.syntaxDefault(), DOC_INDENT);
}
}
if (!function.returns().isEmpty()) {
lines.add(DocLine.BLANK);
lines.add(docHeader("Returns", theme.syntaxKeyword()));
addWrapped(lines, function.returns(), maxWidth, theme.syntaxDefault(), 0);
}
if (!function.notes().isEmpty()) {
lines.add(DocLine.BLANK);
lines.add(docHeader("Notes", theme.syntaxKeyword()));
String bullet = "• ";
String pad = spacesToWidth(font.width(bullet));
for (String note : function.notes()) {
boolean first = true;
for (String line : wrap(note, maxWidth - font.width(bullet))) {
lines.add(new DocLine(List.of(
new DocRun(first ? bullet : pad, theme.mutedText(), false),
new DocRun(line, theme.syntaxDefault(), false))));
first = false;
}
}
}
return lines;
}
/** A bold section header line. */
private DocLine docHeader(String title, int color) {
return new DocLine(List.of(new DocRun(title, color, true)));
}
/** Appends text as word-wrapped paragraph lines with an optional indent. */
private void addWrapped(List<DocLine> lines, String text, int maxWidth, int color, int indent) {
if (text == null || text.isEmpty()) return;
for (String paragraph : text.split("\n")) {
for (String line : wrap(paragraph, maxWidth - indent)) {
List<DocRun> runs = new ArrayList<>(2);
if (indent > 0) runs.add(new DocRun(spacesToWidth(indent), color, false));
runs.add(new DocRun(line, color, false));
lines.add(new DocLine(runs));
}
}
}
/** Spaces roughly as wide as {@code width} pixels. */
private String spacesToWidth(int width) {
int spaceW = Math.max(1, font.width(" "));
return " ".repeat(Math.max(0, (width + spaceW - 1) / spaceW));
}
/** Greedy word wrap on spaces; the same algorithm as the docs panel. */
private List<String> wrap(String text, int maxWidth) {
List<String> lines = new ArrayList<>();
if (text == null || text.isEmpty()) {
lines.add("");
return lines;
}
StringBuilder current = new StringBuilder();
for (String word : text.split(" ")) {
String candidate = current.isEmpty() ? word : current + " " + word;
if (!current.isEmpty() && font.width(candidate) > maxWidth) {
lines.add(current.toString());
current.setLength(0);
current.append(word);
} else {
if (!current.isEmpty()) current.append(' ');
current.append(word);
}
}
lines.add(current.toString());
return lines;
}
// ── Auto-indent ───────────────────────────────────────────────────────
/** One level of indentation: stored as a tab, drawn expanded. */
private static final String INDENT_UNIT = "\t";
/** Spaces per level when taking indentation off. */
private static final int SPACE_STOP = 4;
/** Leading whitespace of {@code line}. */
private static String indentOf(String line) {
int i = 0;
while (i < line.length() && (line.charAt(i) == ' ' || line.charAt(i) == '\t')) i++;
return line.substring(0, i);
}
/**
* Whether a fresh line under this code belongs one level deeper: Lua's
* block keywords and opening brackets. A {@code --} starts a comment and
* is cut off, so {@code if x then -- guard} still indents.
*/
private static boolean opensBlock(String code) {
int comment = code.indexOf("--");
if (comment >= 0) code = code.substring(0, comment);
code = code.stripTrailing();
if (code.endsWith("{") || code.endsWith("(")) return true;
for (String keyword : new String[]{"then", "do", "repeat", "else"}) {
int start = code.length() - keyword.length();
if (start >= 0 && code.endsWith(keyword)
&& (start == 0 || !Character.isJavaIdentifierPart(code.charAt(start - 1)))) {
return true;
}
}
return false;
}
/** A closing token by itself: {@code end}, {@code }} … */
private static boolean isCloser(String trimmed) {
return switch (trimmed) {
case "end", "until", "}", ")", "]" -> true;
default -> false;
};
}
/**
* Enter: breaks the line keeping its indentation, one level deeper after
* a block opener. When the rest of the line is just a closer
* ({@code end}, {@code }} …) that closer keeps the outer level on a line
* of its own and the caret lands on the fresh line between the two.
* Spaces around the caret are cleaned away rather than left behind as
* trailing whitespace.
*/
private void insertNewlineIndented() {
String[] lines = getLines();
int[] lc = offsetToLineCol(cursorPos);
String line = lines[lc[0]];
int lineStart = lineColToOffset(lc[0], 0);
String indent = indentOf(line);
String before = line.substring(0, lc[1]);
String after = line.substring(lc[1]);
boolean splitCloser = isCloser(after.strip());
String newIndent = opensBlock(before) ? indent + INDENT_UNIT : indent;
String insert = splitCloser ? "\n" + newIndent + "\n" + indent : "\n" + newIndent;
// Trim the spaces left of the caret, and the gap up to the closer
// when there is one: both would only become trailing whitespace.
int contentEnd = before.stripTrailing().length();
int gapEnd = splitCloser
? lc[1] + after.length() - after.stripLeading().length()
: lc[1];
applyLocalEdit(lineStart + contentEnd, gapEnd - contentEnd, insert);
cursorPos = lineStart + contentEnd + insert.length()
- (splitCloser ? 1 + indent.length() : 0);
selectionAnchor = -1;
scrollToCursor();
dismissCompletions();
}
/**
* Backspace along a line's indentation: removes one tab, or the spaces
* down to the previous {@value #SPACE_STOP}-space stop, instead of a
* single character. False when the cursor is not over indentation and
* the key should delete normally.
*/
private boolean deleteOneIndentLevel() {
int lineStart = lineColToOffset(offsetToLineCol(cursorPos)[0], 0);
if (lineStart >= cursorPos) return false;
String prefix = text.substring(lineStart, cursorPos);
if (!prefix.chars().allMatch(c -> c == ' ' || c == '\t')) return false;
int spaces = 0;
while (spaces < prefix.length() && prefix.charAt(prefix.length() - 1 - spaces) == ' ') spaces++;
int remove = spaces == 0 ? 1 : Math.min(spaces, (spaces - 1) % SPACE_STOP + 1);
applyLocalEdit(cursorPos - remove, remove, "");
cursorPos -= remove;
return true;
}
/**
* Re-indents every line the selection touches: one level off with Shift
* (a tab, or up to four leading spaces), one on otherwise. The selection
* goes with the text.
*/
private void reindentSelection(boolean outdent) {
int lo = Math.min(selectionAnchor, cursorPos);
int hi = Math.max(selectionAnchor, cursorPos);
// Line/column positions are only valid before the buffer changes.
int[] anchorLC = offsetToLineCol(selectionAnchor);
int[] cursorLC = offsetToLineCol(cursorPos);
int firstLine = Math.min(anchorLC[0], cursorLC[0]);
int blockStart = lineColToOffset(firstLine, 0);
String[] blockLines = text.substring(blockStart, hi).split("\n", -1);
int[] cut = new int[blockLines.length];
if (outdent) {
for (int i = 0; i < blockLines.length; i++) {
String src = blockLines[i];
if (src.startsWith("\t")) cut[i] = 1;
else while (cut[i] < SPACE_STOP && cut[i] < src.length() && src.charAt(cut[i]) == ' ') cut[i]++;
}
}
StringBuilder updated = new StringBuilder();
int[] lineStarts = new int[blockLines.length]; // where each line begins in `updated`
for (int i = 0; i < blockLines.length; i++) {
lineStarts[i] = updated.length();
if (!outdent) updated.append(INDENT_UNIT);
updated.append(blockLines[i], cut[i], blockLines[i].length());
if (i + 1 < blockLines.length) updated.append('\n');
}
applyLocalEdit(blockStart, hi - blockStart, updated.toString());
selectionAnchor = blockStart + lineStarts[anchorLC[0] - firstLine]
+ reindentedColumn(anchorLC[1], cut[anchorLC[0] - firstLine], outdent);
cursorPos = blockStart + lineStarts[cursorLC[0] - firstLine]
+ reindentedColumn(cursorLC[1], cut[cursorLC[0] - firstLine], outdent);
scrollToCursor();
dismissCompletions();
}
/** Where the caret lands in a re-indented line: one unit right, or back over the level taken off. */
private static int reindentedColumn(int column, int cut, boolean outdent) {
return outdent ? Math.max(0, column - cut) : column + INDENT_UNIT.length();
} }
// ── Input handlers ──────────────────────────────────────────────────── // ── Input handlers ────────────────────────────────────────────────────
@@ -771,27 +1195,29 @@ public class EditorFileView extends EditorPane {
// ── Normal key handling ────────────────────────────────────────── // ── Normal key handling ──────────────────────────────────────────
switch (key) { switch (key) {
case 257 -> { // Enter case 257 -> { // Enter — newline with auto-indent
if (hasSelection()) deleteSelection(); if (hasSelection()) deleteSelection();
applyLocalEdit(cursorPos, 0, "\n"); insertNewlineIndented();
cursorPos++;
selectionAnchor = -1;
scrollToCursor();
dismissCompletions();
return true; return true;
} }
case 258 -> { // Tab (no popup) case 258 -> { // Tab (no popup): indents every selected line,
if (hasSelection()) deleteSelection(); // Shift+Tab takes one level off; alone it types a tab
if (hasSelection()) {
reindentSelection(shift);
} else {
applyLocalEdit(cursorPos, 0, "\t"); applyLocalEdit(cursorPos, 0, "\t");
cursorPos++; cursorPos++;
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
dismissCompletions(); dismissCompletions();
}
return true; return true;
} }
case 259 -> { // Backspace case 259 -> { // Backspace
if (hasSelection()) { deleteSelection(); } if (hasSelection()) { deleteSelection(); }
else if (cursorPos > 0) { applyLocalEdit(cursorPos - 1, 1, ""); cursorPos--; } else if (cursorPos > 0 && !deleteOneIndentLevel()) {
applyLocalEdit(cursorPos - 1, 1, ""); cursorPos--;
}
selectionAnchor = -1; selectionAnchor = -1;
scrollToCursor(); scrollToCursor();
updateCompletions(); // re-compute after deletion updateCompletions(); // re-compute after deletion
@@ -910,6 +1336,13 @@ public class EditorFileView extends EditorPane {
return true; return true;
} }
} }
case 90 -> { // Ctrl+Z takes the last change back, Ctrl+Shift+Z the one before that
if (ctrl) {
if (shift) redo();
else undo();
return true;
}
}
case 83 -> { // Ctrl+S case 83 -> { // Ctrl+S
saveEditorFile(); saveEditorFile();
} }
@@ -966,11 +1399,12 @@ public class EditorFileView extends EditorPane {
dismissCompletions(); dismissCompletions();
if (!sameFile) { if (!sameFile) {
// Caret and scroll belonged to the file we just left. // Caret, scroll and remembered changes belonged to the file we left.
cursorPos = 0; cursorPos = 0;
selectionAnchor = -1; selectionAnchor = -1;
scrollX = 0; scrollX = 0;
scrollY = 0; scrollY = 0;
history.clear();
} }
// Join this file's live session (and re-show who is in it). // Join this file's live session (and re-show who is in it).
@@ -990,6 +1424,7 @@ public class EditorFileView extends EditorPane {
scrollX = 0; scrollX = 0;
scrollY = 0; scrollY = 0;
remoteEditors = Collections.emptyList(); remoteEditors = Collections.emptyList();
history.clear();
dismissCompletions(); dismissCompletions();
} }
@@ -1033,4 +1468,39 @@ public class EditorFileView extends EditorPane {
public EditorFile getCurrentEditorFile() { public EditorFile getCurrentEditorFile() {
return currentEditorFile; return currentEditorFile;
} }
String textForSearch() {
return text.toString();
}
int caretOffset() {
return cursorPos;
}
int searchAnchorOffset() {
return hasSelection() ? Math.min(selectionAnchor, cursorPos) : cursorPos;
}
String searchSeed() {
if (hasSelection()) {
return text.substring(Math.min(selectionAnchor, cursorPos), Math.max(selectionAnchor, cursorPos));
}
return wordUnderCursor();
}
/** Selects a search hit and moves the editor caret to it. */
void selectSearchMatch(int offset, int length) {
if (currentEditorFile == null) return;
int start = Math.max(0, Math.min(offset, text.length()));
cursorPos = Math.min(text.length(), start + Math.max(0, length));
selectionAnchor = start;
dismissCompletions();
scrollToCursor();
sendCursorIfMoved();
}
/** Removes the selection left by a previous find hit when the query stops matching. */
void clearSearchSelection() {
if (hasSelection()) selectionAnchor = -1;
}
} }

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

@@ -46,6 +46,9 @@ public class EditorManager {
EditorPaneContainer paneContainer; EditorPaneContainer paneContainer;
EditorDocsPanel editorDocsPanel; EditorDocsPanel editorDocsPanel;
EditorTerminalPane editorTerminal; EditorTerminalPane editorTerminal;
private final EditorFindBar findBar;
private EditorSearchPopup searchPopup;
private EditorThemePopup themePopup;
List<EditorFile> files = new ArrayList<>(); List<EditorFile> files = new ArrayList<>();
@@ -85,6 +88,7 @@ public class EditorManager {
paneContainer = new EditorPaneContainer(this); paneContainer = new EditorPaneContainer(this);
editorDocsPanel = new EditorDocsPanel(this); editorDocsPanel = new EditorDocsPanel(this);
editorTerminal = new EditorTerminalPane(this); editorTerminal = new EditorTerminalPane(this);
findBar = new EditorFindBar(this);
} }
public EditorTheme.Palette theme() { public EditorTheme.Palette theme() {
@@ -95,8 +99,11 @@ public class EditorManager {
return theme; return theme;
} }
void previewTheme(EditorTheme theme) {
this.theme = theme;
}
public void setTheme(EditorTheme theme) { public void setTheme(EditorTheme theme) {
if (this.theme == theme) return;
this.theme = theme; this.theme = theme;
Path path = themeConfigPath(); Path path = themeConfigPath();
@@ -201,6 +208,76 @@ public class EditorManager {
editorDocsPanel.open(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)}. */ /** Asks the server for the current project files; the reply lands in {@link #setFiles(List)}. */
public void requestProjectFiles() { public void requestProjectFiles() {
if (!connected()) return; if (!connected()) return;
@@ -401,6 +478,23 @@ public class EditorManager {
ClientPlayNetworking.send(new ServerboundEditPayload(file.getName(), doc.base(), edit)); 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 * 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 * file gets it; if no pane shows it, it is merged into our stored copy of
@@ -707,7 +801,10 @@ public class EditorManager {
editorTerminal.markClosed(reason); 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() {
@@ -728,7 +825,10 @@ 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,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

@@ -37,7 +37,52 @@ public enum EditorTheme {
0xFFF8F8F2, 0x66F8F8F2, 0xFFF8F8F2, 0x66F8F8F2,
0xFFF8F8F2, 0xFFF92672, 0xFFA6E22E, 0xFFE6DB74, 0xFFAE81FF, 0xFFF8F8F2, 0xFFF92672, 0xFFA6E22E, 0xFFE6DB74, 0xFFAE81FF,
0xFF75715E, 0xFFFD971F, 0xFFA6E22E, 0xFF75715E, 0xFF75715E, 0xFFFD971F, 0xFFA6E22E, 0xFF75715E,
0xFF1E1F1A, 0xFF909185, 0xFF1E1F1A, 0xB0000000)); 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 String displayName;
private final Palette palette; private final Palette palette;

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

@@ -66,10 +66,7 @@ public class EditorTopBar extends Widget {
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Close Pane"), MenuItem.item("Close Pane"),
MenuItem.separator(), MenuItem.separator(),
MenuItem.item("Midnight"), MenuItem.item("Change theme...")
MenuItem.item("Light"),
MenuItem.item("Nord"),
MenuItem.item("Monokai")
), ),
// Help // Help
List.of( List.of(
@@ -297,7 +294,7 @@ public class EditorTopBar extends Widget {
graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, editorManager.theme().accentHover()); graphics.fill(tabX + 1, curY, dropX2 - 1, curY + itemH, editorManager.theme().accentHover());
} }
graphics.text(font, displayLabel(tabIndex, i), graphics.text(font, displayLabel(item),
tabX + TAB_PADDING_X, tabX + TAB_PADDING_X,
curY + TAB_PADDING_Y, curY + TAB_PADDING_Y,
editorManager.theme().text(), false); editorManager.theme().text(), false);
@@ -320,6 +317,7 @@ public class EditorTopBar extends Widget {
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 "Toggle Sidebar" -> editorManager.toggleSidebar();
@@ -327,10 +325,7 @@ public class EditorTopBar extends Widget {
case "Split Below" -> editorManager.splitBelow(); case "Split Below" -> editorManager.splitBelow();
case "Close Pane" -> editorManager.closeActivePane(); case "Close Pane" -> editorManager.closeActivePane();
case "Lua API Documentation" -> editorManager.openDocs(); case "Lua API Documentation" -> editorManager.openDocs();
case "Midnight" -> editorManager.setTheme(EditorTheme.MIDNIGHT); case "Change theme..." -> editorManager.openThemePicker();
case "Light" -> editorManager.setTheme(EditorTheme.LIGHT);
case "Nord" -> editorManager.setTheme(EditorTheme.NORD);
case "Monokai" -> editorManager.setTheme(EditorTheme.MONOKAI);
// Add remaining cases as needed // Add remaining cases as needed
default -> System.out.println("[TopBar] Clicked: " + item.label()); default -> System.out.println("[TopBar] Clicked: " + item.label());
} }
@@ -344,17 +339,13 @@ public class EditorTopBar extends Widget {
for (int i = 0; i < items.size(); i++) { for (int i = 0; i < items.size(); i++) {
MenuItem item = items.get(i); MenuItem item = items.get(i);
if (!item.isSeparator()) { if (!item.isSeparator()) {
maxW = Math.max(maxW, font.width(displayLabel(tabIndex, i)) + 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(int tabIndex, int itemIndex) { private String displayLabel(MenuItem item) {
MenuItem item = TAB_ITEMS.get(tabIndex).get(itemIndex);
if (tabIndex == 3 && item.label().equals(editorManager.currentTheme().displayName())) {
return "✓ " + item.label();
}
return item.label(); return item.label();
} }

View File

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

View File

@@ -55,6 +55,21 @@ public final class LiveDocument {
return 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. */ /** The version of the server's copy this buffer was written against. */
public int base() { public int base() {
return base; return base;

View File

@@ -7,9 +7,10 @@ import java.util.List;
* trigger — Lua's own standard libraries ({@code string}, {@code math}, …) and * trigger — Lua's own standard libraries ({@code string}, {@code math}, …) and
* the tables codecraft itself injects ({@code world}, {@code events}). * the tables codecraft itself injects ({@code world}, {@code events}).
* *
* <p>To make a new library's members appear in the autocomplete popup, * <p>Codecraft's own tables do not implement this by hand: they are generated
* implement this interface and add an instance to * from the Lua API docs catalog by {@link DocLibraries}. To make a new plain
* {@link CompletionProvider}.</p> * Lua table's members appear in the autocomplete popup, implement this
* interface and add an instance to {@link CompletionProvider}.</p>
*/ */
public interface LuaLibrary { public interface LuaLibrary {

View File

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

View File

@@ -32,6 +32,20 @@ public class TextEditorScreen extends EditorScreen {
@Override @Override
public boolean keyPressed(KeyEvent event) { 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 if (event.key() == 66 && event.hasControlDown()) { // Ctrl+B
editorManager.toggleSidebar(); editorManager.toggleSidebar();
return true; return true;

View File

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

View File

@@ -194,6 +194,38 @@ public record Edit(UUID author, long seq, List<Edit.Component> components) {
return written; 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 ────────────────────────────────────────────────────── // ── Transforming ──────────────────────────────────────────────────────
/** /**