Establish buildable modules and shared host-service boundaries

This commit is contained in:
2026-11-12 07:49:06 +01:00
parent 1326b18746
commit 306266ae40
41 changed files with 1980 additions and 23 deletions
@@ -0,0 +1,213 @@
package de.neitzel.fxdesigner.intellij;
import com.intellij.openapi.application.*;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.event.*;
import com.intellij.openapi.fileEditor.*;
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.vfs.*;
import de.neitzel.fxdesigner.contracts.*;
import de.neitzel.fxdesigner.host.*;
import java.net.URI;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* Adapts actual IntelliJ Documents and native commands/history; never creates a competing undo
* store.
*/
public final class IntellijDocuments implements HostServices.Documents, AutoCloseable {
private final Project project;
private final com.intellij.openapi.Disposable lifetime;
private final Map<Path, State> states = new HashMap<>();
private final Set<Handle> handles = new HashSet<>();
private boolean closed;
private static final class State {
VirtualFile file;
Document document;
String disk;
AtomicLong revision = new AtomicLong();
}
public IntellijDocuments(Project project) {
this.project = Objects.requireNonNull(project);
lifetime = this::disposeResources;
Disposer.register(project, lifetime);
}
private <T> CompletionStage<T> edt(Callable<T> action) {
var future = new CompletableFuture<T>();
Runnable task =
() ->
WriteIntentReadAction.run(
() -> {
try {
if (closed || project.isDisposed() || Disposer.isDisposed(lifetime))
throw new IllegalStateException("Designer host disposed");
future.complete(action.call());
} catch (Throwable e) {
future.completeExceptionally(e);
}
});
if (ApplicationManager.getApplication().isDispatchThread()) task.run();
else ApplicationManager.getApplication().invokeLater(task, ModalityState.any());
return future;
}
public CompletionStage<DocumentSession> open(URI uri) {
return edt(
() -> {
Path path = Path.of(uri).toRealPath();
State state = states.get(path);
if (state == null) {
state = new State();
state.file = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path);
if (state.file == null) throw new IllegalArgumentException("Missing file: " + path);
state.document = FileDocumentManager.getInstance().getDocument(state.file);
if (state.document == null) throw new IllegalArgumentException("Not a text document");
state.disk = Files.readString(path);
var observed = state;
state.document.addDocumentListener(
new DocumentListener() {
@Override
public void documentChanged(DocumentEvent e) {
observed.revision.incrementAndGet();
}
},
lifetime);
states.put(path, state);
}
var handle = new Handle(state);
handles.add(handle);
return handle;
});
}
private DocumentSnapshot snapshot(State s) {
return new DocumentSnapshot(
Path.of(s.file.getPath()).toUri(),
s.revision.get(),
s.document.getText(),
s.document.isWritable() && s.file.isWritable(),
FileDocumentManager.getInstance().isDocumentUnsaved(s.document));
}
private final class Handle implements DocumentSession {
private final State s;
private boolean released;
private Editor editor;
Handle(State s) {
this.s = s;
}
private <T> CompletionStage<T> run(Callable<T> action) {
return edt(
() -> {
if (released) throw new IllegalStateException("Document handle closed");
return action.call();
});
}
public CompletionStage<DocumentSnapshot> snapshot() {
return run(() -> IntellijDocuments.this.snapshot(s));
}
public CompletionStage<DocumentSnapshot> apply(EditBatch edits) {
return run(
() -> {
edits.applyTo(IntellijDocuments.this.snapshot(s));
var ranges = new ArrayList<>(edits.replacements());
ranges.sort(Comparator.comparingInt(EditBatch.Replacement::start));
Collections.reverse(ranges);
WriteCommandAction.runWriteCommandAction(
project,
edits.name(),
java.util.UUID.randomUUID().toString(),
() -> {
for (var range : ranges)
s.document.replaceString(range.start(), range.end(), range.text());
});
return IntellijDocuments.this.snapshot(s);
});
}
public CompletionStage<DocumentSnapshot> undo() {
return history(false);
}
public CompletionStage<DocumentSnapshot> redo() {
return history(true);
}
private CompletionStage<DocumentSnapshot> history(boolean redo) {
return run(
() -> {
if (!s.document.isWritable() || !s.file.isWritable())
throw new IllegalStateException("Read-only document");
if (editor == null)
editor = EditorFactory.getInstance().createEditor(s.document, project);
var textEditor = TextEditorProvider.getInstance().getTextEditor(editor);
var undo = UndoManager.getInstance(project);
if (redo) {
if (undo.isRedoAvailable(textEditor)) undo.redo(textEditor);
} else if (undo.isUndoAvailable(textEditor)) undo.undo(textEditor);
return IntellijDocuments.this.snapshot(s);
});
}
public CompletionStage<DocumentSnapshot> save(long revision) {
return run(
() -> {
if (s.revision.get() != revision)
throw new ConcurrentModificationException("Stale save");
if (!s.document.isWritable() || !s.file.isWritable())
throw new IllegalStateException("Read-only document");
Path file = Path.of(s.file.getPath());
if (!Files.readString(file).equals(s.disk))
throw new ConcurrentModificationException("External change; draft retained");
FileDocumentManager.getInstance().saveDocument(s.document);
if (FileDocumentManager.getInstance().isDocumentUnsaved(s.document))
throw new IllegalStateException("IDE did not save document");
s.disk = Files.readString(file);
return IntellijDocuments.this.snapshot(s);
});
}
private void release() {
if (released) return;
released = true;
if (editor != null) EditorFactory.getInstance().releaseEditor(editor);
handles.remove(this);
}
public void close() {
edt(
() -> {
release();
return null;
});
}
}
private void disposeResources() {
for (var h : List.copyOf(handles)) h.release();
closed = true;
states.clear();
}
public void close() {
edt(
() -> {
Disposer.dispose(lifetime);
return null;
});
}
}