[215] Cycles: Bau (CI Linux/macOS) und Auslieferung (Tauri, Electron)
cycles.yml baut Cycles je Plattform (Linux x86_64, macOS arm64) und legt das Paket als Artefakt und am Gitea-Release cycles-<version> ab; release.yml lädt es vor dem App-Bau (get.sh). Mitgeliefert: Electron extraResources (resources/cycles), Tauri externalBin + resources (tauri.cycles.conf.json). Fassade src/native/cyclesRuntime.ts (cyclesAvailable, runCycles mit Fortschritt und Abbruch), Hauptprozess und Rust (cycles.rs) prüfen die Argumente und starten nur das Paketprogramm. build-macos.sh fertig, Lizenztexte im Paket, NOTICE, doc/CYCLES.md. Geprüft: vitest, rustc --test, AppImage mit Linux-Paket (test:linux-app, Fall Cycles). Nicht geprüft: Workflows, Mac, Tauri-Befehle.
This commit is contained in:
35 files changed
+1785
-58
No files matched your search
@@ -0,0 +1,103 @@
|
||||
// [215] Cycles-Paket: Namensschema (Bau, Gitea-Release, App-Bau), Einbindung ins AppImage (extraResources) und in die Workflows.
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const req = createRequire(import.meta.url);
|
||||
const root = join(__dirname, "..", "..");
|
||||
const read = (rel: string) => readFileSync(join(root, rel), "utf8");
|
||||
|
||||
const lib = req("../../scripts/cycles/cycles-lib.cjs") as {
|
||||
cyclesVersion: () => string;
|
||||
releaseTag: (v: string) => string;
|
||||
assetName: (os: string, arch: string, v: string) => string;
|
||||
artifactName: (os: string, arch: string, v: string) => string;
|
||||
downloadUrl: (os: string, arch: string, v: string) => string;
|
||||
hostPlatform: (p?: string, a?: string) => { os: string; arch: string };
|
||||
parseSha256: (t: string) => string | null;
|
||||
};
|
||||
const pack = req("../../scripts/electron-pack.cjs") as {
|
||||
packConfig: (b: string, v?: string, c?: string) => { extraResources?: unknown };
|
||||
resolveCyclesDir: (root: string, argv: string[], env: Record<string, string>) => string | null;
|
||||
};
|
||||
|
||||
describe("Cycles-Paketnamen", () => {
|
||||
it("Version aus scripts/cycles/VERSION, Tag, Asset, Artefakt, Adresse", () => {
|
||||
const v = lib.cyclesVersion();
|
||||
expect(v).toMatch(/^\d+\.\d+\.\d+$/);
|
||||
expect(lib.releaseTag("5.3.0")).toBe("cycles-5.3.0");
|
||||
expect(lib.assetName("linux", "x86_64", "5.3.0")).toBe("cycles-linux-x86_64-5.3.0.tar.xz");
|
||||
expect(lib.artifactName("macos", "arm64", "5.3.0")).toBe("cycles-macos-arm64-5.3.0");
|
||||
expect(lib.downloadUrl("macos", "arm64", "5.3.0")).toBe("https://git.openbureau.ch/karim/dossier/releases/download/cycles-5.3.0/cycles-macos-arm64-5.3.0.tar.xz");
|
||||
expect(() => lib.assetName("windows", "x86_64", "5.3.0")).toThrow();
|
||||
expect(() => lib.releaseTag("v5.3")).toThrow();
|
||||
});
|
||||
it("Rechner → Paketname; Prüfsummendatei", () => {
|
||||
expect(lib.hostPlatform("linux", "x64")).toEqual({ os: "linux", arch: "x86_64" });
|
||||
expect(lib.hostPlatform("darwin", "arm64")).toEqual({ os: "macos", arch: "arm64" });
|
||||
expect(() => lib.hostPlatform("win32", "x64")).toThrow();
|
||||
expect(lib.parseSha256(`${"ab".repeat(32)} cycles-linux-x86_64-5.3.0.tar.xz\n`)).toBe("ab".repeat(32));
|
||||
expect(lib.parseSha256("kaputt")).toBeNull();
|
||||
});
|
||||
it("pack.sh schreibt denselben Namen wie das Skript-Schema", () => {
|
||||
const sh = read("scripts/cycles/pack.sh");
|
||||
expect(sh).toContain('NAME="cycles-$OS-$ARCH-$VERSION.tar.xz"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("AppImage: Cycles als extraResources", () => {
|
||||
it("packConfig trägt den Ordner als `cycles/` ein, ohne Ordner nichts", () => {
|
||||
expect(pack.packConfig("1", undefined, "/x/cyc").extraResources).toEqual([{ from: "/x/cyc", to: "cycles" }]);
|
||||
expect(pack.packConfig("1").extraResources).toBeUndefined();
|
||||
});
|
||||
it("Ordnerwahl: --cycles, Umgebung, build/cycles; fehlendes Programm / Pflicht", () => {
|
||||
const d = mkdtempSync(join(tmpdir(), "dossier-cypack-"));
|
||||
try {
|
||||
expect(pack.resolveCyclesDir(d, [], {})).toBeNull();
|
||||
expect(() => pack.resolveCyclesDir(d, [], { DOSSIER_REQUIRE_CYCLES: "1" })).toThrow(/Cycles fehlt/);
|
||||
expect(() => pack.resolveCyclesDir(d, [`--cycles=${d}/nix`], {})).toThrow(/kein Programm/);
|
||||
mkdirSync(join(d, "build", "cycles"), { recursive: true });
|
||||
writeFileSync(join(d, "build", "cycles", "cycles"), "x");
|
||||
expect(pack.resolveCyclesDir(d, [], {})).toBe(join(d, "build", "cycles"));
|
||||
expect(pack.resolveCyclesDir(d, [`--cycles=${join(d, "build", "cycles")}`], {})).toBe(join(d, "build", "cycles"));
|
||||
expect(pack.resolveCyclesDir(d, [], { DOSSIER_CYCLES_DIR: join(d, "build", "cycles") })).toBe(join(d, "build", "cycles"));
|
||||
} finally {
|
||||
rmSync(d, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
it("Hauptprozess und Preload verweisen auf electron-cycles, das Skript steht in `files`", () => {
|
||||
expect(read("scripts/electron-main.cjs")).toMatch(/electron-cycles\.cjs"\)\.register\(ipcMain, app\)/);
|
||||
expect(read("scripts/electron-preload.cjs")).toContain('exposeInMainWorld("dossierCycles"');
|
||||
expect(read("electron-builder.yml")).toMatch(/^\s+- scripts\/electron-cycles\.cjs$/m);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Workflows", () => {
|
||||
it("cycles.yml: Jobs linux (ubuntu-24.04) und macos (macos-14), Artefakte, Gitea-Ablage", () => {
|
||||
const y = read(".github/workflows/cycles.yml");
|
||||
expect(y).toMatch(/^\s+linux:\n\s+runs-on: ubuntu-24\.04/m);
|
||||
expect(y).toMatch(/^\s+macos:\n\s+runs-on: macos-14/m);
|
||||
expect(y).toContain("scripts/cycles/build-linux.sh");
|
||||
expect(y).toContain("scripts/cycles/build-macos.sh");
|
||||
expect(y).toContain("cycles-linux-x86_64-${{ steps.v.outputs.version }}");
|
||||
expect(y).toContain("cycles-macos-arm64-${{ steps.v.outputs.version }}");
|
||||
expect(y).toContain("scripts/cycles/upload-gitea.mjs");
|
||||
expect(y).toContain("workflow_dispatch");
|
||||
expect(y).toMatch(/paths:\n\s+- "scripts\/cycles\/\*\*"/);
|
||||
});
|
||||
it("release.yml lädt Cycles vor dem App-Bau (beide Jobs) und verlangt es für das AppImage", () => {
|
||||
const y = read(".github/workflows/release.yml");
|
||||
expect(y).toContain("scripts/cycles/get.sh macos arm64");
|
||||
expect(y).toContain("scripts/cycles/get.sh linux x86_64");
|
||||
expect(y.indexOf("get.sh macos arm64")).toBeLessThan(y.indexOf("tauri-apps/tauri-action"));
|
||||
expect(y.indexOf("get.sh linux x86_64")).toBeLessThan(y.indexOf("npm run electron:pack"));
|
||||
expect(y).toContain('DOSSIER_REQUIRE_CYCLES: "1"');
|
||||
});
|
||||
it("Tauri-Overlay: Sidecar + Ressourcen für Bibliotheken, Kernel-Quellen, Lizenzen", () => {
|
||||
const c = JSON.parse(read("src-tauri/tauri.cycles.conf.json")) as { bundle: { externalBin: string[]; resources: Record<string, string> } };
|
||||
expect(c.bundle.externalBin).toEqual(["binaries/cycles"]);
|
||||
expect(Object.values(c.bundle.resources).sort()).toEqual(["cycles/lib/", "cycles/licenses/", "cycles/source/"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// [215] Cycles-Fassade (src/native/cyclesRuntime.ts) mit einer Brücke als Ersatz für den Hauptprozess; Browser: nicht verfügbar.
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { cyclesAvailable, parseCyclesProgress, prepareCyclesScene, runCycles, type DossierCyclesApi } from "./cyclesRuntime";
|
||||
|
||||
type G = { window?: { dossierCycles?: DossierCyclesApi } };
|
||||
const g = globalThis as unknown as G;
|
||||
afterEach(() => {
|
||||
delete g.window;
|
||||
});
|
||||
|
||||
/** Ersatz-Brücke: `start` meldet die Zeilen und das Ende nach `exitAfterMs`, `cancel` beendet sofort mit -1. */
|
||||
function fakeApi(opts: { exe?: string | null; lines?: string[]; code?: number; hang?: boolean } = {}): DossierCyclesApi & { started: unknown[][]; cancelled: string[] } {
|
||||
const lineCbs = new Set<(e: { jobId: string; line: string }) => void>();
|
||||
const exitCbs = new Set<(e: { jobId: string; code: number }) => void>();
|
||||
const started: unknown[][] = [];
|
||||
const cancelled: string[] = [];
|
||||
return {
|
||||
started,
|
||||
cancelled,
|
||||
where: async () => (opts.exe === undefined ? "/res/cycles/cycles" : opts.exe),
|
||||
prepare: async () => "/tmp/dossier-render/1",
|
||||
readFile: async () => new Uint8Array([1, 2, 3]),
|
||||
start: async (jobId, dir, args) => {
|
||||
started.push([jobId, dir, args]);
|
||||
queueMicrotask(() => {
|
||||
for (const line of opts.lines ?? []) for (const cb of lineCbs) cb({ jobId, line });
|
||||
if (!opts.hang) for (const cb of exitCbs) cb({ jobId, code: opts.code ?? 0 });
|
||||
});
|
||||
},
|
||||
cancel: (jobId) => {
|
||||
cancelled.push(jobId);
|
||||
for (const cb of exitCbs) cb({ jobId, code: -1 });
|
||||
},
|
||||
onLine: (cb) => (lineCbs.add(cb), () => lineCbs.delete(cb)),
|
||||
onExit: (cb) => (exitCbs.add(cb), () => exitCbs.delete(cb)),
|
||||
};
|
||||
}
|
||||
|
||||
describe("parseCyclesProgress", () => {
|
||||
it("liest 'Progress 06.25 Sample 1/16'", () => {
|
||||
expect(parseCyclesProgress("Progress 06.25 Sample 1/16 ")).toEqual({ fraction: 0.0625, sample: 1, samples: 16 });
|
||||
expect(parseCyclesProgress("Progress 100.00 Sample 16/16")).toEqual({ fraction: 1, sample: 16, samples: 16 });
|
||||
});
|
||||
it("andere Zeilen sind kein Fortschritt", () => {
|
||||
for (const l of ["Updating Scene BVH", "Writing image out.png", "Progress 100.00 Finished", "Loading render kernels (may take a few minutes the first time)", ""]) {
|
||||
expect(parseCyclesProgress(l)).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("cyclesAvailable / runCycles", () => {
|
||||
it("Browser (kein Fenster, keine Brücke, kein Tauri): nicht verfügbar", async () => {
|
||||
expect(await cyclesAvailable()).toBe(false);
|
||||
g.window = {};
|
||||
expect(await cyclesAvailable()).toBe(false);
|
||||
await expect(prepareCyclesScene([])).rejects.toThrow(/nicht verfügbar/);
|
||||
await expect(runCycles("/x", [], () => {})).rejects.toThrow(/nicht verfügbar/);
|
||||
});
|
||||
|
||||
it("Paket ohne Cycles (where = null): nicht verfügbar", async () => {
|
||||
g.window = { dossierCycles: fakeApi({ exe: null }) };
|
||||
expect(await cyclesAvailable()).toBe(false);
|
||||
});
|
||||
|
||||
it("Electron-Brücke: verfügbar, Fortschritt, Exit-Code, übrige Zeilen", async () => {
|
||||
const api = fakeApi({ lines: ["Updating Scene", "Progress 50.00 Sample 8/16", "Progress 100.00 Sample 16/16", "Writing image out.png"], code: 0 });
|
||||
g.window = { dossierCycles: api };
|
||||
expect(await cyclesAvailable()).toBe(true);
|
||||
expect(await prepareCyclesScene([])).toBe("/tmp/dossier-render/1");
|
||||
const seen: number[] = [];
|
||||
const r = await runCycles("/tmp/dossier-render/1", ["--background", "szene.xml"], (p) => seen.push(p.sample));
|
||||
expect(seen).toEqual([8, 16]);
|
||||
expect(r).toEqual({ code: 0, cancelled: false, lines: ["Updating Scene", "Writing image out.png"] });
|
||||
expect(api.started[0].slice(1)).toEqual(["/tmp/dossier-render/1", ["--background", "szene.xml"]]);
|
||||
});
|
||||
|
||||
it("Abbruch per Signal beendet den Prozess", async () => {
|
||||
const api = fakeApi({ lines: ["Progress 10.00 Sample 1/10"], hang: true });
|
||||
g.window = { dossierCycles: api };
|
||||
const ac = new AbortController();
|
||||
const r = runCycles("/tmp/dossier-render/1", ["szene.xml"], () => ac.abort(), ac.signal);
|
||||
expect(await r).toMatchObject({ cancelled: true, code: -1 });
|
||||
expect(api.cancelled).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("schon abgebrochenes Signal startet nichts", async () => {
|
||||
const api = fakeApi();
|
||||
g.window = { dossierCycles: api };
|
||||
const ac = new AbortController();
|
||||
ac.abort();
|
||||
expect(await runCycles("/tmp/dossier-render/1", ["szene.xml"], () => {}, ac.signal)).toMatchObject({ cancelled: true });
|
||||
expect(api.started).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
// Mitgeliefertes Cycles ([215], Endbilder) aus der App starten — gemeinsame Fassade für Tauri (macOS) und Electron (Linux).
|
||||
// Tauri: Rust-Befehle `cycles_where`, `cycles_job_dir`, `cycles_start`, `cycles_cancel` (src-tauri/src/cycles.rs), Ereignisse
|
||||
// `cycles://line` / `cycles://exit`, Szenendateien über das fs-Plugin im Ordner `$TEMP/dossier-render`. Electron: `window.dossierCycles`
|
||||
// (scripts/electron-preload.cjs → scripts/electron-cycles.cjs). Im reinen Browser gibt es kein Programm: `cyclesAvailable()` ist false.
|
||||
//
|
||||
// Ablauf eines Bildes: Szene (Cycles-XML + Texturen) mit `prepareCyclesScene` in einen Arbeitsordner schreiben, `runCycles` mit
|
||||
// den Schaltern aufrufen (Pfade relativ zum Arbeitsordner), das Ergebnis mit `readCyclesFile` lesen. Der Hauptprozess startet nur das
|
||||
// Programm im Paketordner und prüft die Argumente (Schalterliste, Wertebereiche, Dateien nur im Arbeitsordner).
|
||||
// Die Tauri-Plugins werden nur dynamisch importiert (Muster `blender.ts`): Browser-Build und vitest brauchen sie nicht.
|
||||
// Nicht auf dem Mac geprüft (Tauri-Teil nach Muster geschrieben); Electron/Linux: e2e/linuxApp170.spec.ts.
|
||||
|
||||
import { isTauri } from "./blender";
|
||||
|
||||
/** Von electron-preload.cjs injiziert (nur Electron/Linux). */
|
||||
export interface DossierCyclesApi {
|
||||
where: () => Promise<string | null>;
|
||||
prepare: (files: { path: string; bytes: Uint8Array }[]) => Promise<string>;
|
||||
start: (jobId: string, sceneDir: string, args: string[]) => Promise<void>;
|
||||
cancel: (jobId: string) => void;
|
||||
readFile: (path: string) => Promise<Uint8Array>;
|
||||
onLine: (cb: (e: { jobId: string; line: string }) => void) => () => void;
|
||||
onExit: (cb: (e: { jobId: string; code: number }) => void) => () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
dossierCycles?: DossierCyclesApi;
|
||||
}
|
||||
}
|
||||
|
||||
/** Fortschritt aus einer Zeile `Progress 06.25 Sample 1/16` (Anteil 0…1, Sample, Samples). */
|
||||
export interface CyclesProgress {
|
||||
fraction: number;
|
||||
sample: number;
|
||||
samples: number;
|
||||
}
|
||||
|
||||
const PROGRESS_RE = /Progress\s+(\d+(?:\.\d+)?)\s+Sample\s+(\d+)\s*\/\s*(\d+)/;
|
||||
|
||||
/** Liest eine Ausgabezeile von Cycles; `null`, wenn sie kein Fortschritt ist („Updating …“, „Writing image …“). */
|
||||
export function parseCyclesProgress(line: string): CyclesProgress | null {
|
||||
const m = PROGRESS_RE.exec(line);
|
||||
if (!m) return null;
|
||||
const samples = Number(m[3]);
|
||||
const sample = Number(m[2]);
|
||||
const percent = Number(m[1]);
|
||||
if (!(samples > 0) || !Number.isFinite(percent)) return null;
|
||||
return { fraction: Math.min(1, Math.max(0, percent / 100)), sample, samples };
|
||||
}
|
||||
|
||||
/** Wirt: wo liegt Cycles, Dateien schreiben/lesen, Prozess starten (Tauri und Electron liefern je eine Fassung). */
|
||||
interface CyclesHost {
|
||||
where(): Promise<string | null>;
|
||||
prepare(files: { path: string; bytes: Uint8Array }[]): Promise<string>;
|
||||
readFile(path: string): Promise<Uint8Array>;
|
||||
spawn(sceneDir: string, args: string[], onLine: (line: string) => void): { done: Promise<number>; cancel(): void };
|
||||
}
|
||||
|
||||
let counter = 0;
|
||||
const newJobId = (): string => `cycles-${Date.now().toString(36)}-${counter++}`;
|
||||
const join = (dir: string, rel: string): string => `${dir.replace(/[\\/]+$/, "")}/${rel}`;
|
||||
|
||||
async function tauriHost(): Promise<CyclesHost> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const { listen } = await import("@tauri-apps/api/event");
|
||||
const fs = await import("@tauri-apps/plugin-fs");
|
||||
return {
|
||||
where: () => invoke<string | null>("cycles_where"),
|
||||
async prepare(files) {
|
||||
const dir = await invoke<string>("cycles_job_dir");
|
||||
const made = new Set<string>();
|
||||
for (const f of files) {
|
||||
const slash = f.path.lastIndexOf("/");
|
||||
if (slash > 0) {
|
||||
const sub = join(dir, f.path.slice(0, slash));
|
||||
if (!made.has(sub)) {
|
||||
await fs.mkdir(sub, { recursive: true });
|
||||
made.add(sub);
|
||||
}
|
||||
}
|
||||
await fs.writeFile(join(dir, f.path), f.bytes);
|
||||
}
|
||||
return dir;
|
||||
},
|
||||
readFile: (path) => fs.readFile(path),
|
||||
spawn(sceneDir, args, onLine) {
|
||||
const jobId = newJobId();
|
||||
const done = (async () => {
|
||||
let resolveExit!: (code: number) => void;
|
||||
const exit = new Promise<number>((r) => (resolveExit = r));
|
||||
const offLine = await listen<{ jobId: string; line: string }>("cycles://line", (e) => {
|
||||
if (e.payload.jobId === jobId) onLine(e.payload.line);
|
||||
});
|
||||
const offExit = await listen<{ jobId: string; code: number }>("cycles://exit", (e) => {
|
||||
if (e.payload.jobId === jobId) resolveExit(e.payload.code);
|
||||
});
|
||||
try {
|
||||
await invoke("cycles_start", { jobId, sceneDir, args });
|
||||
return await exit;
|
||||
} finally {
|
||||
offLine();
|
||||
offExit();
|
||||
}
|
||||
})();
|
||||
return { done, cancel: () => void invoke("cycles_cancel", { jobId }).catch(() => undefined) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function electronHost(api: DossierCyclesApi): CyclesHost {
|
||||
return {
|
||||
where: () => api.where(),
|
||||
prepare: (files) => api.prepare(files),
|
||||
readFile: (path) => api.readFile(path),
|
||||
spawn(sceneDir, args, onLine) {
|
||||
const jobId = newJobId();
|
||||
let resolveExit!: (code: number) => void;
|
||||
const exit = new Promise<number>((r) => (resolveExit = r));
|
||||
const offLine = api.onLine((e) => {
|
||||
if (e.jobId === jobId) onLine(e.line);
|
||||
});
|
||||
const offExit = api.onExit((e) => {
|
||||
if (e.jobId === jobId) resolveExit(e.code);
|
||||
});
|
||||
const done = api
|
||||
.start(jobId, sceneDir, args)
|
||||
.then(() => exit)
|
||||
.finally(() => {
|
||||
offLine();
|
||||
offExit();
|
||||
});
|
||||
return { done, cancel: () => api.cancel(jobId) };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function cyclesHost(): Promise<CyclesHost | null> {
|
||||
if (typeof window === "undefined") return null;
|
||||
if (window.dossierCycles) return electronHost(window.dossierCycles);
|
||||
if (isTauri()) return tauriHost();
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Ist ein Cycles-Programm in dieser Installation vorhanden und lauffähig (nicht im Browser, nicht bei Paketen ohne Cycles)? */
|
||||
export async function cyclesAvailable(): Promise<boolean> {
|
||||
try {
|
||||
const host = await cyclesHost();
|
||||
return host ? (await host.where()) !== null : false;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function requireHost(): Promise<CyclesHost> {
|
||||
const host = await cyclesHost();
|
||||
if (!host || (await host.where()) === null) throw new Error("Cycles ist in dieser Installation nicht verfügbar");
|
||||
return host;
|
||||
}
|
||||
|
||||
/** Schreibt Szenendateien (Pfade relativ, mit `/`) in einen neuen Arbeitsordner und gibt dessen Pfad zurück. */
|
||||
export async function prepareCyclesScene(files: { path: string; bytes: Uint8Array }[]): Promise<string> {
|
||||
return (await requireHost()).prepare(files);
|
||||
}
|
||||
|
||||
/** Liest eine Datei aus dem Arbeitsordner (z. B. das gerenderte Bild). */
|
||||
export async function readCyclesFile(path: string): Promise<Uint8Array> {
|
||||
return (await requireHost()).readFile(path);
|
||||
}
|
||||
|
||||
export interface CyclesResult {
|
||||
/** Exit-Code von Cycles; -1 nach Abbruch oder wenn der Prozess nicht startete. */
|
||||
code: number;
|
||||
cancelled: boolean;
|
||||
/** Letzte Ausgabezeilen ohne Fortschritt (für Fehlermeldungen), höchstens 200. */
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Startet Cycles im Arbeitsordner `sceneDir` (von {@link prepareCyclesScene}). `args`: Schalter wie `["--background", "--samples", "64",
|
||||
* "--output", "bild.png", "szene.xml"]` (Dateien relativ zum Arbeitsordner); der Hauptprozess erlaubt nur bekannte Schalter.
|
||||
* `onProgress` bekommt Anteil und `Sample n/N`. Abbruch über `signal`: beendet den Prozess, das Ergebnis hat `cancelled: true`.
|
||||
*/
|
||||
export async function runCycles(
|
||||
sceneDir: string,
|
||||
args: string[],
|
||||
onProgress: (p: CyclesProgress) => void,
|
||||
signal?: AbortSignal,
|
||||
): Promise<CyclesResult> {
|
||||
const host = await requireHost();
|
||||
const lines: string[] = [];
|
||||
if (signal?.aborted) return { code: -1, cancelled: true, lines };
|
||||
const job = host.spawn(sceneDir, args, (line) => {
|
||||
const p = parseCyclesProgress(line);
|
||||
if (p) onProgress(p);
|
||||
else {
|
||||
lines.push(line);
|
||||
if (lines.length > 200) lines.shift();
|
||||
}
|
||||
});
|
||||
let cancelled = false;
|
||||
const abort = (): void => {
|
||||
cancelled = true;
|
||||
job.cancel();
|
||||
};
|
||||
signal?.addEventListener("abort", abort, { once: true });
|
||||
try {
|
||||
const code = await job.done;
|
||||
return { code, cancelled, lines };
|
||||
} finally {
|
||||
signal?.removeEventListener("abort", abort);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
// [215] Cycles im Electron-Hauptprozess (scripts/electron-cycles.cjs): Argumentprüfung, Pfadwahl, Prozessstart mit Ersatzprogramm.
|
||||
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
type Job = { jobId: string; line?: string; code?: number };
|
||||
const cy = createRequire(import.meta.url)("../../scripts/electron-cycles.cjs") as {
|
||||
register: (ipc: unknown, app: { isPackaged: boolean }) => void;
|
||||
cyclesDir: (o: { isPackaged: boolean; resourcesPath: string; env?: Record<string, string>; repoRoot?: string }) => string;
|
||||
cyclesExe: (dir: string, o?: { platform?: string; arch?: string }) => string | null;
|
||||
validateCyclesArgs: (dir: string, args: unknown) => string[];
|
||||
};
|
||||
|
||||
const root = join(tmpdir(), "dossier-render");
|
||||
const dirs: string[] = [];
|
||||
const scene = () => {
|
||||
mkdirSync(root, { recursive: true });
|
||||
const d = mkdtempSync(join(root, "t-"));
|
||||
dirs.push(d);
|
||||
return d;
|
||||
};
|
||||
afterEach(() => {
|
||||
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("validateCyclesArgs", () => {
|
||||
it("erlaubte Schalter, Pfade werden im Arbeitsordner aufgelöst", () => {
|
||||
const d = scene();
|
||||
expect(cy.validateCyclesArgs(d, ["--background", "--samples", "8", "--width", "320", "--height", "180", "--device", "CPU", "--output", "out.png", "haus.xml"])).toEqual([
|
||||
"--background", "--samples", "8", "--width", "320", "--height", "180", "--device", "CPU", "--output", join(d, "out.png"), join(d, "haus.xml"),
|
||||
]);
|
||||
expect(cy.validateCyclesArgs(d, ["--device", "METAL+CPU", "sub/a.xml"])).toContain(join(d, "sub", "a.xml"));
|
||||
});
|
||||
it("lehnt Fremdes ab: Schalter, Werte, Pfade ausserhalb, falscher Arbeitsordner, Shell-Zeichen", () => {
|
||||
const d = scene();
|
||||
const bad = (args: unknown) => expect(() => cy.validateCyclesArgs(d, args)).toThrow();
|
||||
bad(["--help", "a.xml"]);
|
||||
bad(["--samples", "0", "a.xml"]);
|
||||
bad(["--samples", "8; rm -rf /", "a.xml"]);
|
||||
bad(["--samples", "99999999", "a.xml"]);
|
||||
bad(["--device", "CPU;ls", "a.xml"]);
|
||||
bad(["--output", "../out.png", "a.xml"]);
|
||||
bad(["--output", "/etc/passwd", "a.xml"]);
|
||||
bad(["--output", "out.sh", "a.xml"]);
|
||||
bad(["../../etc/x.xml"]);
|
||||
bad(["/etc/hosts.xml"]);
|
||||
bad(["a.xml", "b.xml"]); // zwei Szenen
|
||||
bad(["--samples", "8"]); // keine Szene
|
||||
bad(["--samples"]); // Wert fehlt
|
||||
bad("a.xml");
|
||||
expect(() => cy.validateCyclesArgs(tmpdir(), ["a.xml"])).toThrow(/dossier-render/);
|
||||
expect(() => cy.validateCyclesArgs(join(root, ".."), ["a.xml"])).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("cyclesDir / cyclesExe", () => {
|
||||
it("gepackt: resources/cycles, keine Umlenkung per Umgebung", () => {
|
||||
expect(cy.cyclesDir({ isPackaged: true, resourcesPath: "/opt/dossier/resources", env: { DOSSIER_CYCLES_DIR: "/boese" } })).toBe("/opt/dossier/resources/cycles");
|
||||
});
|
||||
it("ungepackt: DOSSIER_CYCLES_DIR, sonst build/cycles", () => {
|
||||
expect(cy.cyclesDir({ isPackaged: false, resourcesPath: "/x", env: { DOSSIER_CYCLES_DIR: "/lokal/c" } })).toBe("/lokal/c");
|
||||
expect(cy.cyclesDir({ isPackaged: false, resourcesPath: "/x", env: {}, repoRoot: "/repo" })).toBe("/repo/build/cycles");
|
||||
});
|
||||
it("Programm muss ausführbar sein; Intel-Mac: nicht verfügbar", () => {
|
||||
const d = scene();
|
||||
expect(cy.cyclesExe(d)).toBeNull();
|
||||
writeFileSync(join(d, "cycles"), "#!/bin/sh\n");
|
||||
chmodSync(join(d, "cycles"), 0o644);
|
||||
expect(cy.cyclesExe(d)).toBeNull();
|
||||
chmodSync(join(d, "cycles"), 0o755);
|
||||
expect(cy.cyclesExe(d)).toBe(join(d, "cycles"));
|
||||
expect(cy.cyclesExe(d, { platform: "darwin", arch: "x64" })).toBeNull();
|
||||
expect(cy.cyclesExe(d, { platform: "darwin", arch: "arm64" })).toBe(join(d, "cycles"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("Prozessstart (Ersatzprogramm)", () => {
|
||||
it("meldet Zeilen (\\r-getrennt), Ende, nutzt den Arbeitsordner und CYCLES_KERNEL_PATH; Abbruch beendet", async () => {
|
||||
if (process.platform === "win32") return;
|
||||
const pkg = scene();
|
||||
mkdirSync(join(pkg, "source"));
|
||||
writeFileSync(
|
||||
join(pkg, "cycles"),
|
||||
'#!/bin/sh\nprintf "Updating\\rProgress 50.00 Sample 1/2\\rProgress 100.00 Sample 2/2\\n"\necho "cwd=$(pwd) kernel=$CYCLES_KERNEL_PATH args=$*"\n[ "$1" = "--quiet" ] && exec sleep 30\nexit 3\n',
|
||||
);
|
||||
chmodSync(join(pkg, "cycles"), 0o755);
|
||||
process.env.DOSSIER_CYCLES_DIR = pkg;
|
||||
const handlers = new Map<string, (...a: unknown[]) => unknown>();
|
||||
const listeners = new Map<string, (...a: unknown[]) => unknown>();
|
||||
cy.register({ handle: (c: string, f: (...a: unknown[]) => unknown) => handlers.set(c, f), on: (c: string, f: (...a: unknown[]) => unknown) => listeners.set(c, f) }, { isPackaged: false });
|
||||
expect(await handlers.get("cycles:where")!()).toBe(join(pkg, "cycles"));
|
||||
|
||||
const work = scene();
|
||||
const sent: { ch: string; p: Job }[] = [];
|
||||
const ev = { sender: { isDestroyed: () => false, send: (ch: string, p: Job) => sent.push({ ch, p }) } };
|
||||
const done = () => new Promise<void>((res) => { const t = setInterval(() => sent.some((s) => s.ch === "cycles:exit") && (clearInterval(t), res()), 20); });
|
||||
await handlers.get("cycles:start")!(ev, "j1", work, ["--background", "haus.xml"]);
|
||||
await done();
|
||||
const lines = sent.filter((s) => s.ch === "cycles:line").map((s) => s.p.line);
|
||||
expect(lines.slice(0, 3)).toEqual(["Updating", "Progress 50.00 Sample 1/2", "Progress 100.00 Sample 2/2"]);
|
||||
expect(lines[3]).toContain(`kernel=${join(pkg, "source")}`);
|
||||
expect(lines[3]).toContain(`args=--background ${join(work, "haus.xml")}`);
|
||||
expect(sent.find((s) => s.ch === "cycles:exit")!.p.code).toBe(3);
|
||||
|
||||
// Abbruch: das Ersatzprogramm schläft bei --quiet
|
||||
sent.length = 0;
|
||||
await handlers.get("cycles:start")!(ev, "j2", work, ["--quiet", "haus.xml"]);
|
||||
await new Promise((r) => setTimeout(r, 150));
|
||||
listeners.get("cycles:cancel")!({}, "j2");
|
||||
await done();
|
||||
expect(sent.find((s) => s.ch === "cycles:exit")!.p.code).toBe(-1);
|
||||
|
||||
// fremde Argumente: kein Prozess
|
||||
expect(() => handlers.get("cycles:start")!(ev, "j3", work, ["--help", "haus.xml"])).toThrow(/nicht erlaubt/);
|
||||
delete process.env.DOSSIER_CYCLES_DIR;
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user