feat(pbs): add sprite animation and shared Studio authoring

Implement DEC-0084 with factory-only Sprite/Animator structs, complete result
lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP
authoring through shared services.

Qualify native dev/release with ordinary and optimized producers, zero-allocation
playback, private-cycle reclamation, canonical Composer pixels, installed JARs
and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
This commit is contained in:
2026-11-05 15:16:07 +00:00
parent 1d8b8c2101
commit bf31184d4d
151 changed files with 4823 additions and 98 deletions
+38
View File
@@ -505,3 +505,41 @@ GC fixtures require actual advancing collection counters. Snapshots release sour
backings and observe 1,200 → 1 → 1 → 0 nodes/payloads. Collection fixtures observe
64 → 61 → 0 → 1 → 0 payloads and only one retained backing until its final owner
is dropped. Temporary Cargo projects/targets stay outside the runtime checkout.
## PBS Result, Sprite and Animation qualification
Generate the source corpora with `:prometeu-architecture-tests:test` and
`:prometeu-app:installedKnowledgeTest`. Focused native gates are `--result-only`
and `--animation-only`; add `--release` for the runtime release profile. Before
animation qualification, generate the Composer pixel corpus with
`:prometeu-app:headlessProcessTest --tests '*AnimationInstalledRuntimeTest'`
and `-PstudioRuntimeInstall=<extracted-runtime-installation>`. The desktop gate
is `:prometeu-app:animationDesktopTest`. Each native gate
requires both ordinary and optimized producer variants and fails on missing fixtures.
Result executes status plus complete payload groups, once-only propagation and
handling, error remapping, reference/Fn/trait/builtin payloads and uncaught traps.
Animation executes the public core, reusable independent backing, state/reset/time
boundaries, every domain error, exact long limits and a test-only near-limit state.
The isolated count/phase setup is never shipped as a public mutation hook.
`animation.rs` single-steps actual instructions between post-construction markers.
Sprite and successful, negative and overflow advance paths must execute zero
StructNew/ArrayNew/MakeClosure instructions. Large jumps must remain below the
bounded instruction gate. Zero guest/handle quotas trap during construction and
are distinct from recoverable domain errors. A test-only safepoint marker observes
live private rings followed by complete reclamation after their last owner clears.
The installed-JAR producer saves a real Packer-bound canonical sidecar, compiles
virtual factories with read-only JSON origins and supplies both producer variants
for production firmware execution. `AnimationInstalledRuntimeTest` separately boots
the configured extracted runtime and compares every pixel of direct/generated
Composer sprites with the shared preview across tick boundaries and alternating
palettes. That saved-project corpus is replayed by production firmware in native
dev/release with both producers, comparing the exact same canonical pixels. The public Composer
facade retains int status and nine arguments; its private host carrier is narrowed
from the existing native Int64 status. No runtime source write is required.
Keep Cargo targets in `/tmp` and retain source hashes, provider revision, profiles,
allocation counts and GC observations with the completed discussion's evidence.
+118
View File
@@ -0,0 +1,118 @@
//! Real core playback and executed allocation evidence, including error paths.
use super::*;
use prometeu_vm::LogicalFrameEndingReason as End;
use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op};
pub fn verify(root: &std::path::Path) {
let manifest = std::fs::read_to_string(root.join("pbs-animation-manifest.txt")).expect("mandatory animation manifest");
let names: Vec<_> = manifest.lines().collect();
assert_eq!(names, ["basic", "loop", "once", "negative", "overflow", "draft", "limits", "matrix", "errors"]);
for name in names { for suffix in ["", "-optimized"] {
let bytes = std::fs::read(root.join(format!("pbs-animation-{name}{suffix}.pbx"))).expect("mandatory animation fixture");
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
.unwrap_or_else(|e| panic!("animation/{name}{suffix}: load {e:?}"));
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
vm.prepare_boot_call().unwrap();
let mut watching = false; let mut started = 0; let mut ended = 0; let mut allocations = 0; let mut measured_steps=0;
for step in 0..2_000_000 {
let instruction = decode_next(vm.pc(), image.code()).unwrap();
if instruction.opcode == Op::PushI32 {
if instruction.imm_i32().unwrap() == 162000001 { watching = true; started += 1; }
if instruction.imm_i32().unwrap() == 162000002 { watching = false; ended += 1; }
}
if watching { measured_steps+=1; }
if watching && matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; }
let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None))
.unwrap_or_else(|e| panic!("animation/{name}{suffix}: run {e:?}"));
if matches!(report.reason, End::Halted | End::EndOfRom) { break; }
assert!(matches!(report.reason, End::BudgetExhausted), "animation/{name}{suffix}: {report:?}");
assert!(step < 1_999_999, "animation failed to terminate");
}
assert_eq!(vm.operand_stack_top(2), vec![Value::Int32(42), Value::Int32(0)], "animation/{name}{suffix}");
if !matches!(name, "basic" | "draft" | "limits" | "matrix") { assert_eq!((started, ended), (1, 1)); }
assert!(measured_steps<50000,"bounded frame traversal: {measured_steps}");
assert_eq!(allocations, 0, "animation/{name}{suffix}: executed advance/sprite heap allocations");
if name=="basic" {
use prometeu_vm::resource_budget::{RuntimeLimits,RuntimeResource};
for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots] {
let mut refused=VirtualMachine::from_image(image.clone(),RuntimeLimits::default().lowered(resource,0).unwrap());
refused.prepare_boot_call().unwrap();let report=refused.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason,End::Trap(ref fault) if fault.code==prometeu_bytecode::TRAP_RESOURCE_LIMIT));
assert_eq!(refused.heap().len(),0);println!("ANIMATION QUOTA TRAP PASS {suffix} {resource:?}");
}
}
println!("ANIMATION PASS {name}{suffix} watched={started} executed_allocations={allocations}");
} }
verify_gc(root);
verify_installed(root);
verify_composer(root);
}
fn verify_gc(root: &std::path::Path) {
for suffix in ["", "-optimized"] {
let bytes=std::fs::read(root.join(format!("pbs-animation-gc{suffix}.pbx"))).unwrap();
let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap();
let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap();
for round in 0..2 {
let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap();
assert!(matches!(report.reason,End::FrameSync),"animation GC: {report:?}");
let objects=vm.heap().diagnostic_typed_storage();
for name in ["Animator","_AnimationClip","_AnimationFrame"] {
let count=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count();
if round==0 {assert!(count>0,"live animation root {name}");} else {assert_eq!(count,0,"unowned cycle {name}");}
}
assert!(vm.resource_snapshot().gc.reclaimed>1000);
println!("ANIMATION GC PASS {suffix} round={round} collections={} reclaimed={}",vm.resource_snapshot().gc.collections,vm.resource_snapshot().gc.reclaimed);
}
}
}
fn verify_installed(root: &std::path::Path) {
use prometeu_drivers::TestPlatform;
use prometeu_firmware::firmware::Firmware;
use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource}};
for suffix in ["", "-optimized"] {
let name=format!("pbs-animation-installed{suffix}");
let mut fw=Firmware::new(None);let mut platform=TestPlatform::new();
fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,capabilities:caps::NONE,memcard_slots:None,program:std::fs::read(root.join(format!("{name}.pbx"))).unwrap(),assets:AssetsPayloadSource::empty(),asset_table:vec![],preload:vec![]});
for _ in 0..5 {fw.tick(&InputSignals::default(),&mut platform);assert!(fw.os.vm().last_crash_report().is_none());}
let task=fw.os.lifecycle().resident_game_task().unwrap();let mut sessions=fw.os.sessions();let session=sessions.vm_session_for_task_mut(task).unwrap();
let id=std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();session.vm.prepare_call(id.trim()).unwrap();
let report=session.vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(session.vm.operand_stack_top(1),vec![Value::Int32(42)]);
println!("ANIMATION INSTALLED GENERATED/FIRMWARE PASS {suffix}");
}
}
fn verify_composer(root: &std::path::Path) {
use prometeu_drivers::TestPlatform;
use prometeu_firmware::firmware::Firmware;
use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource,AssetsPackPrelude}};
for suffix in ["", "-optimized"] {
let prefix=format!("pbs-animation-composer{suffix}");
let manifest:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.manifest.json"))).unwrap()).unwrap();
let oracle:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.oracle.json"))).unwrap()).unwrap();
let packed=std::fs::read(root.join(format!("{prefix}.assets.pa"))).unwrap();let prelude=AssetsPackPrelude::from_bytes(&packed).unwrap();
let mut fw=Firmware::new(None);let mut platform=TestPlatform::new();
fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation Composer".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,
capabilities:caps::COMPOSER,memcard_slots:None,
program:std::fs::read(root.join(format!("{prefix}.pbx"))).unwrap(),assets:AssetsPayloadSource::from_bytes(packed[prelude.payload_offset as usize..].to_vec()),
asset_table:serde_json::from_value(manifest["asset_table"].clone()).unwrap(),preload:serde_json::from_value(manifest["preload"].clone()).unwrap()});
let mut observed=0;
for _ in 0..50000 {
fw.tick(&InputSignals::default(),&mut platform);
assert!(fw.os.vm().last_crash_report().is_none(),"Composer {suffix}: {:?}",fw.os.vm().last_crash_report());
if let Some(task)=fw.os.lifecycle().resident_game_task() {
let completed={let sessions=fw.os.sessions();sessions.vm_session_for_task(task).map(|s|s.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(0)};
if completed>observed {
assert_eq!(completed,observed+1,"one native frame per observation");
let sample=&oracle[observed as usize];let pixels=sample["rgba"].as_array().unwrap();let front=platform.local_hardware().gfx.front_buffer();let width=platform.local_hardware().gfx.size().0;
for x in [32,64] {for y in 0..16 {for dx in 0..16 {assert_eq!(front[(32+y)*width+x+dx],pixels[y*16+dx].as_u64().unwrap() as u32,"{prefix} tick={observed} x={x} pixel={dx},{y}");}}}
println!("ANIMATION COMPOSER PIXELS PASS {suffix} tick={observed} glyph={} palette={}",sample["glyph"],sample["palette"]);
observed=completed;if observed==8 {break;}
}
}
std::thread::yield_now();
}
assert_eq!(observed,8,"native Composer did not produce all frames");
}
}
+6
View File
@@ -2,6 +2,8 @@ use prometeu_bytecode::Value;
mod stack_queue;
mod lifecycle;
mod memcard;
mod result;
mod animation;
use prometeu_bytecode::load_limits::{LoadBudget, LoadLimits};
use prometeu_hal::syscalls::caps;
use prometeu_vm::{
@@ -44,6 +46,8 @@ fn main() {
for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations,Q::IndividualStringBytes,Q::CallDepth] {
println!("DEFAULT VM LIMIT {resource:?}={}",limits.get(resource));
}
if std::env::args().any(|arg| arg == "--animation-only") { animation::verify(&root); return; }
if std::env::args().any(|arg| arg == "--result-only") { result::verify(&root); return; }
if std::env::args().any(|arg| arg == "--memcard-only") { memcard::verify(&root); return; }
if std::env::args().any(|arg| arg == "--lifecycle-only") { lifecycle::verify(&root); return; }
if std::env::args().any(|arg| arg == "--stack-queue-only") { stack_queue::verify(&root); return; }
@@ -57,6 +61,8 @@ fn main() {
if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; }
verify_pbs_math_fixtures(&root);
if std::env::args().any(|arg| arg == "--math-only") { return; }
result::verify(&root);
animation::verify(&root);
verify_pbs_random_fixtures(&root);
verify_identity_hashing_fixtures(&root);
verify_catalog_fixtures(&root);
+56
View File
@@ -0,0 +1,56 @@
//! PBS result groups execute on the unchanged production loader and VM.
use super::*;
use prometeu_vm::LogicalFrameEndingReason as End;
use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op};
pub fn verify(root: &std::path::Path) {
let cases = [
("unit-ok", vec![Value::Int32(0)]),
("unit-err", vec![Value::Int32(2)]),
("scalar", vec![Value::Int32(0), Value::Int32(42)]),
("error", vec![Value::Int32(1), Value::Int64(0)]),
("tuple", vec![Value::Int32(0), Value::Int64(9_007_199_254_740_993), Value::Int32(42)]),
("reference", vec![Value::Int32(2), Value::Null]),
("propagate", vec![Value::Int32(2), Value::Int64(0), Value::Null]),
("nested", vec![Value::Int32(2), Value::Int32(0)]),
("recover", vec![Value::Int32(0), Value::Int32(42)]),
("remap", vec![Value::Int32(2), Value::Int32(0)]),
("success", vec![Value::Int32(0), Value::Int32(42)]),
("trait", vec![Value::Int32(1), Value::Null, Value::Null]),
("fn", vec![Value::Int32(1), Value::Null]),
("once", vec![Value::Int32(0), Value::Int32(42)]),
("block-remap", vec![Value::Int32(2), Value::Int32(0)]),
("reference-ok", vec![Value::Int32(0), Value::Int32(42)]),
("fn-ok", vec![Value::Int32(0), Value::Int32(42)]),
("trait-ok", vec![Value::Int32(0), Value::Int32(42)]),
("color-ok", vec![Value::Int32(0), Value::Int64(42)]),
("color-err", vec![Value::Int32(1), Value::Int64(0)]),
("trap", vec![]),
];
let manifest = std::fs::read_to_string(root.join("pbs-result-manifest.txt")).expect("mandatory result manifest");
assert_eq!(manifest.lines().count(), cases.len() * 2);
for (name, expected) in cases { for suffix in ["", "-optimized"] {
let bytes = std::fs::read(root.join(format!("pbs-result-{name}{suffix}.pbx"))).expect("mandatory result fixture");
let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE)
.unwrap_or_else(|e| panic!("result/{name}{suffix}: load {e:?}"));
let mut vm = VirtualMachine::from_image(image.clone(), Default::default());
vm.prepare_boot_call().unwrap();
let mut allocations = 0;
let mut trapped=false;
for step in 0..100_000 {
let instruction = decode_next(vm.pc(), image.code()).unwrap();
if matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; }
let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None))
.unwrap_or_else(|e| panic!("result/{name}{suffix}: run {e:?}"));
if matches!(report.reason, End::Trap(_)) && name=="trap" { trapped=true;break; }
if matches!(report.reason, End::Halted | End::EndOfRom) { break; }
assert!(matches!(report.reason, End::BudgetExhausted), "result/{name}{suffix}: {report:?}");
assert!(step < 99_999, "result failed to terminate");
}
if name=="trap" { assert!(trapped,"handle must not recover a VM trap");println!("RESULT TRAP PASS {suffix}");continue; }
assert_eq!(vm.operand_stack_top(expected.len()).iter().rev().cloned().collect::<Vec<_>>(), expected, "result/{name}{suffix}");
if matches!(name,"reference-ok"|"fn-ok"|"trait-ok") { assert!(allocations>0,"successful payload is constructed"); }
else { assert_eq!(allocations, 0, "result/{name}{suffix}: no holder or inactive payload allocations"); }
println!("RESULT PASS {name}{suffix} group={expected:?} executed_allocations={allocations}");
} }
}
+5 -1
View File
@@ -11,6 +11,8 @@ parser = argparse.ArgumentParser()
parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime"))
parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance"))
parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies")
parser.add_argument("--animation-only", action="store_true", help="Run mandatory PBS core animation corpus")
parser.add_argument("--result-only", action="store_true", help="Run mandatory PBS result return-group corpus")
parser.add_argument("--memcard-only", action="store_true", help="Run PBS memcard through production Firmware/SystemOS (native, not installed process)")
parser.add_argument("--lifecycle-only", action="store_true", help="Run PBS guest lifecycle VM and production firmware corpus")
parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness")
@@ -71,6 +73,8 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory:
(root / "src").mkdir()
(root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text())
(root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text())
(root / "src/animation.rs").write_text(pathlib.Path(__file__).with_name("animation.rs").read_text())
(root / "src/result.rs").write_text(pathlib.Path(__file__).with_name("result.rs").read_text())
(root / "src/memcard.rs").write_text(pathlib.Path(__file__).with_name("memcard.rs").read_text())
(root / "src/lifecycle.rs").write_text(pathlib.Path(__file__).with_name("lifecycle.rs").read_text())
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--animation-only"] if args.animation_only else []), *(["--result-only"] if args.result_only else []), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True)
+10 -1
View File
@@ -52,7 +52,16 @@ function activate(context) {
reconnectContext = context;
output = vscode.window.createOutputChannel("Prometeu LSP");
output.appendLine("Prometeu VS Code extension activated.");
context.subscriptions.push(externalSources, vscode.workspace.registerTextDocumentContentProvider(externalSources_1.externalScheme, externalSources), vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()), vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)), vscode.workspace.onDidCloseTextDocument(document => void externalSources.closeDocument(document)));
context.subscriptions.push(externalSources, vscode.languages.registerCodeLensProvider({ scheme: externalSources_1.externalScheme, language: "pbs" }, {
provideCodeLenses: document => externalSources.originLenses(document)
}), vscode.commands.registerCommand("prometeu.openAnimationOrigin", async (uri, byteOffset) => {
try {
await externalSources.openAnimationOrigin(uri, byteOffset);
}
catch (error) {
void vscode.window.showErrorMessage(String(error));
}
}), vscode.workspace.registerTextDocumentContentProvider(externalSources_1.externalScheme, externalSources), vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()), vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)), vscode.workspace.onDidCloseTextDocument(document => void externalSources.closeDocument(document)));
const connectCommand = vscode.commands.registerCommand("prometeu.connectStudioLsp", async () => {
await startClient(context);
});
@@ -108,6 +108,25 @@ class ExternalSources {
this.refreshStatus();
return content.text;
}
originLenses(document) {
if (!this.canQuery(document))
return [];
const content = this.documents.get(document.uri.toString());
return (content?.descriptor.origins ?? []).map(origin => {
const offset = Buffer.from(document.getText(), "utf8").subarray(0, origin.startOffset).toString("utf8").length;
const position = document.positionAt(offset);
return new vscode.CodeLens(new vscode.Range(position, position), {
title: "Open animation definition in Studio", command: "prometeu.openAnimationOrigin",
arguments: [document.uri, origin.startOffset]
});
});
}
async openAnimationOrigin(uri, byteOffset) {
const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
if (!document || !this.canQuery(document) || !this.client || !this.consumerId)
throw new Error("Animation source unavailable: navigate again to obtain the current revision.");
await this.client.sendRequest("prometeu/openAnimationOrigin", { consumerId: this.consumerId, uri: uri.toString(), offset: byteOffset });
}
async opened(document) {
if (document.uri.scheme !== exports.externalScheme)
return;
+4
View File
@@ -36,6 +36,10 @@
{
"command": "prometeu.restartStudioLsp",
"title": "Prometeu: Restart Studio LSP"
},
{
"command": "prometeu.openAnimationOrigin",
"title": "Prometeu: Open Animation Definition in Studio"
}
],
"configuration": {
+7
View File
@@ -79,6 +79,13 @@ export function activate(context: vscode.ExtensionContext): void {
output = vscode.window.createOutputChannel("Prometeu LSP");
output.appendLine("Prometeu VS Code extension activated.");
context.subscriptions.push(externalSources,
vscode.languages.registerCodeLensProvider({ scheme: externalScheme, language: "pbs" }, {
provideCodeLenses: document => externalSources.originLenses(document)
}),
vscode.commands.registerCommand("prometeu.openAnimationOrigin", async (uri: vscode.Uri, byteOffset: number) => {
try { await externalSources.openAnimationOrigin(uri, byteOffset); }
catch (error) { void vscode.window.showErrorMessage(String(error)); }
}),
vscode.workspace.registerTextDocumentContentProvider(externalScheme, externalSources),
vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()),
vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)),
+22 -1
View File
@@ -3,7 +3,7 @@ import { LanguageClient } from "vscode-languageclient/node";
export const externalScheme = "prometeu-source";
export type ExternalContent = {
descriptor: { uri: string; revision: string; origin: string; name: string; languageId: string; readOnly: true };
descriptor: { uri: string; revision: string; origin: string; name: string; languageId: string; readOnly: true; origins?: { startOffset: number; endOffset: number; definitionPath: string; jsonPointer: string; assetUuid: string }[] };
text: string;
};
@@ -74,6 +74,27 @@ export class ExternalSources implements vscode.TextDocumentContentProvider, vsco
return content.text;
}
originLenses(document: vscode.TextDocument): vscode.CodeLens[] {
if (!this.canQuery(document)) return [];
const content = this.documents.get(document.uri.toString());
return (content?.descriptor.origins ?? []).map(origin => {
const offset = Buffer.from(document.getText(), "utf8").subarray(0, origin.startOffset).toString("utf8").length;
const position = document.positionAt(offset);
return new vscode.CodeLens(new vscode.Range(position, position), {
title: "Open animation definition in Studio", command: "prometeu.openAnimationOrigin",
arguments: [document.uri, origin.startOffset]
});
});
}
async openAnimationOrigin(uri: vscode.Uri, byteOffset: number): Promise<void> {
const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString());
if (!document || !this.canQuery(document) || !this.client || !this.consumerId)
throw new Error("Animation source unavailable: navigate again to obtain the current revision.");
await this.client.sendRequest<void>("prometeu/openAnimationOrigin",
{ consumerId: this.consumerId, uri: uri.toString(), offset: byteOffset });
}
async opened(document: vscode.TextDocument): Promise<void> {
if (document.uri.scheme !== externalScheme) return;
const content = this.documents.get(document.uri.toString());