mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Expose optional GPU composition and export in photocraft-cli (#10912)
* Add headless GPU backend foundation for composition and flat export (issue #8062 PR 1) * Fix headless GPU readback bounds, API compliance, and error preservation (#8062) * Fix GPU readback bounds, context thread spawn error, and test parity (#8062) * Fix BandRenderer Send bound, PNG reborrows, and clippy lints (#8062) * Fix effect shadow test construction and remove dead code wrappers (#8062) * Use short reborrows for Headless renderer without lifetime escaping (#8062) * Fix clippy collapsible_if and ensure multi-band geometry in flat export tests (#8062) * Fix automation Rect import, add renderer diagnostics, and harden flat export retries (#8062) * Expose optional GPU rendering in photocraft-cli (#8062) * Fix GPU feature test APIs and native target gates * Fix CLI locked metadata, bounded benchmark params, and protocol diagnostics (#8062) * Verify unsupported GPU effects before testing band seams * Fix CLI renderer borrows and GPU-enabled test compilation * Use compositor buffer ownership API after upstream memory accounting change * Fix GPU CLI lint failures and validate run environment policy * Update export renderer test helper for owned compositor buffers * Fix needless benchmark layer name borrow * Fix headless GPU backend review findings (#10842) - release a closed document's GPU caches through a BandRenderer hook - bound the monitored readback wait and report a stalled GPU as device loss - reject 32-bit float documents before band readback so exports fall back to CPU - keep previews at 8-bit RGBA and report the palette/Duotone renderer bypass - retain renderer diagnostics when encoding fails - strengthen renderer, save-path and GPU diagnostics tests * Use valid batch arguments and inspect method in GPU CLI tests * Add GPU close-hook and 8-bit preview regression tests (#10842) * Fix GPU CLI review findings (#10912) - guard the benchmark's modulo divisors for one-pixel dimensions - count a cold export as GPU only when the renderer context was used - report every batch file's export warnings, deduplicating only GPU diagnostics - drain renderer diagnostics before propagating convert and run save errors - cover renderer use in the GPU precedence, bridge and serve tests * fix(io): correct renderer binding mutability * test(cli): verify narrow benchmark inputs and GPU diagnostics * Fix remaining headless GPU review findings (#10842) - release a document's GPU caches when file.close, file.closeAll or file.closeOthers removes it through a command - honor cancellation while band readback waits, polling in 100 ms slices - fault the device after a readback timeout so later exports skip it - report single-layer, CMYK ink-mixing, ORA and PDF CPU paths to a requested renderer - keep fallback warnings in their export instead of leaking them into the next one - requeue renderer diagnostics when a renderer-aware save's final write fails - write MCP/serve diagnostics without panicking on a broken stderr - document the actual colour-space contract and drop F32 from the GPU depth list * Fix remaining headless GPU review findings (#10842) - release a document's GPU caches when file.close, file.closeAll or file.closeOthers removes it through a command - honor cancellation while band readback waits, polling in 100 ms slices - fault the device after a readback timeout so later exports skip it - report single-layer, CMYK ink-mixing, ORA and PDF CPU paths to a requested renderer - keep fallback warnings in their export instead of leaking them into the next one - requeue renderer diagnostics when a renderer-aware save's final write fails - write MCP/serve diagnostics without panicking on a broken stderr - document the actual colour-space contract and drop F32 from the GPU depth list * Fix remaining GPU CLI review findings (#10912) - reject non-UTF-8 PHOTOCRAFT_GPU values instead of silently using the CPU - release a batch item's document caches before taking the renderer to the next item, and report fallbacks once - count warm benchmark runs that fell back to CPU in the summary - write serve diagnostics without panicking on a broken stderr - assert that the batch test's --gpu policy reaches the renderer * Use question mark for cancellable readback errors * Use question mark for cancellable readback errors * Keep GPU export diagnostics with their attempt and stop bands on cancel Encode native .pcraft bytes before draining renderer diagnostics, and requeue export warnings when a workspace write fails, so callers still report the adapter or fallback reason with the error. Move a failed GPU attempt's queued diagnostics into its CPU retry result instead of leaving them for a later successful export to report. Stop GPU band readback at the next band after cancellation, and check the interrupt before each CpuRenderer sink delivery. Band readback uploads half-precision textures, so reject U16 alongside F32: their samples cannot survive the upload. Tighten the 8-bit CPU/GPU parity checks to 1/255. * Keep GPU export diagnostics with their attempt and stop bands on cancel Encode native .pcraft bytes before draining renderer diagnostics, and requeue export warnings when a workspace write fails, so callers still report the adapter or fallback reason with the error. Move a failed GPU attempt's queued diagnostics into its CPU retry result instead of leaving them for a later successful export to report. Stop GPU band readback at the next band after cancellation, and check the interrupt before each CpuRenderer sink delivery. Band readback uploads half-precision textures, so reject U16 alongside F32: their samples cannot survive the upload. Tighten the 8-bit CPU/GPU parity checks to 1/255. * Report partial warm fallbacks and CPU fallback on stderr The averaged GPU Warm row now says how many warm runs fell back to the CPU and were excluded from the average, through the existing helper. The single-layer convert diagnostic test checks that the CPU fallback is reported on stderr, in GPU-enabled and CPU-only builds alike. * Keep headless export warnings when a workspace write fails (#10842) A capability-scoped save encodes the export, then writes it; when the write fails, the export warnings (folded together with renderer diagnostics) were pushed back through `BandRenderer::push_diagnostic`, whose default is a no-op. A custom renderer that overrides only `drain_diagnostics` therefore lost the adapter or fallback reason that belonged with the error. Keep them in `Headless` instead and return them from the next `drain_diagnostics`, alongside the renderer's own queue. The regression uses a renderer without a `push_diagnostic` override and checks the warnings survive the failed write and drain exactly once. Also name the actual source of the depth limit in the headless GPU matrix: layer content is uploaded as half-precision textures, not band readback. * Stop CPU bands and CPU retries on cancellation (#10912) The CPU retry after a retryable GPU error composes through `FlatSource::bands`, whose shared `emit` sink did not poll the export interrupt: a cancel was only observed after the whole composite finished. Check it once per band, as `CpuRenderer` does, for both RGB and CMYK ink bands. The flat and streamed-PNG retry branches also check before starting the full CPU composite again, so a cancelled export returns `IoError::Cancelled` instead of re-rendering the document. Tests: band-sink cancellation for RGB and CMYK inks, a renderer call counter proving a second export reaches the renderer, and a pending `wait_slices` poll observing cancellation set mid-wait. * Merge origin/main into GPU foundation (#10842) * Keep GPU-path diagnostics on every failure path, honour cancel in native copy - save: export warnings of a failed local write stay in Headless pending diagnostics - render: preview fallback warnings are returned, drained, and added to the doc.render reply - io: renderer-neutral fallback wording; native single-layer copy checks cancellation per band - gpu: gate wait_slices tests off wasm32 (#10842) * Address CodeRabbit review: keep fallback reasons on failed retries, report native-copy and quick-export CPU use, guard diagnostics drain (#10912) * Accept render diagnostics from the doc.render reply in the serve GPU test (#10912) --------- Co-authored-by: FredApps <[email protected]>
This commit is contained in:
1 parent
f1137013a2
commit
13b481f892
24 files changed
+1095
-41
No files matched your search
Generated
+2
@@ -5220,9 +5220,11 @@ dependencies = [
|
||||
"clap_mangen",
|
||||
"photocraft-automation",
|
||||
"photocraft-codecs",
|
||||
"photocraft-doc",
|
||||
"photocraft-engine",
|
||||
"photocraft-format",
|
||||
"photocraft-io",
|
||||
"photocraft-raster",
|
||||
"photocraft-raw",
|
||||
"serde_json",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -7,9 +7,12 @@ license.workspace = true
|
||||
build = "build.rs"
|
||||
|
||||
[features]
|
||||
default = ["gpu"]
|
||||
# Open HEIC/HEIF photos (the optional photocraft-heif crate). Not default so distributors choose
|
||||
# it; official builds (CI, packaging/, release) build with `--features heif`.
|
||||
heif = ["photocraft-codecs/heif"]
|
||||
# Optional native GPU rendering backend, enabled by default in native CLI builds.
|
||||
gpu = ["photocraft-automation/gpu"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -22,10 +25,16 @@ path = "src/lib.rs"
|
||||
name = "photocraft-cli"
|
||||
path = "src/main.rs"
|
||||
|
||||
[[example]]
|
||||
name = "gpu_bench"
|
||||
required-features = ["gpu"]
|
||||
|
||||
[dependencies]
|
||||
photocraft-automation = { path = "../../crates/automation" }
|
||||
photocraft-doc = { workspace = true }
|
||||
photocraft-engine = { workspace = true }
|
||||
photocraft-io = { workspace = true }
|
||||
photocraft-raster = { workspace = true }
|
||||
photocraft-format = { path = "../../crates/format" }
|
||||
photocraft-codecs = { workspace = true }
|
||||
clap = { workspace = true }
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
//! Benchmark example measuring headless CPU vs GPU rendering and export performance.
|
||||
//!
|
||||
//! Usage:
|
||||
//! ```sh
|
||||
//! cargo run --release -p photocraft-cli --example gpu_bench -- [options]
|
||||
//! ```
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::Instant;
|
||||
|
||||
use clap::Parser;
|
||||
use photocraft_automation::files;
|
||||
use photocraft_automation::gpu::GpuRenderer;
|
||||
use photocraft_doc::{BlendMode, Color, ColorMode, Document, Layer, LayerContent, Rect, SampleType, Size, Surface};
|
||||
use photocraft_io::ExportOptions;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "gpu_bench", about = "Benchmark headless CPU vs GPU rendering and export performance")]
|
||||
struct BenchArgs {
|
||||
/// Input image or PSD file (optional; defaults to synthetic mockup)
|
||||
#[arg(short, long)]
|
||||
input: Option<PathBuf>,
|
||||
|
||||
/// Synthetic document width in pixels (1..=16384)
|
||||
#[arg(short, long, default_value_t = 2048, value_parser = clap::value_parser!(u32).range(1..=16384))]
|
||||
width: u32,
|
||||
|
||||
/// Synthetic document height in pixels (1..=16384)
|
||||
#[arg(short = 'H', long, default_value_t = 2048, value_parser = clap::value_parser!(u32).range(1..=16384))]
|
||||
height: u32,
|
||||
|
||||
/// Synthetic layer count (1..=128)
|
||||
#[arg(short, long, default_value_t = 8, value_parser = clap::value_parser!(u32).range(1..=128))]
|
||||
layers: u32,
|
||||
|
||||
/// Number of warm GPU runs (0..=50)
|
||||
#[arg(short = 'r', long = "warm-runs", default_value_t = 3, value_parser = clap::value_parser!(u32).range(0..=50))]
|
||||
warm_runs: u32,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let args = BenchArgs::parse();
|
||||
let layers = args.layers as usize;
|
||||
let warm_runs = args.warm_runs as usize;
|
||||
|
||||
println!("# PhotoCraft CLI Headless Rendering Benchmark");
|
||||
println!();
|
||||
|
||||
const MAX_SYNTHETIC_PIXELS: u64 = 256 * 1024 * 1024;
|
||||
let doc = if let Some(path) = &args.input {
|
||||
println!("- **Input Source**: file `{}`", path.display());
|
||||
let open_res = files::open(path)?;
|
||||
open_res.document
|
||||
} else {
|
||||
let total_pixels = u64::from(args.width) * u64::from(args.height) * u64::from(args.layers);
|
||||
if total_pixels > MAX_SYNTHETIC_PIXELS {
|
||||
return Err(format!(
|
||||
"requested synthetic benchmark volume ({}x{} x {} layers = {} total pixels) exceeds budget of {} pixels (~{} MB); please lower width, height, or layer count",
|
||||
args.width,
|
||||
args.height,
|
||||
args.layers,
|
||||
total_pixels,
|
||||
MAX_SYNTHETIC_PIXELS,
|
||||
(MAX_SYNTHETIC_PIXELS * 4) / (1024 * 1024)
|
||||
)
|
||||
.into());
|
||||
}
|
||||
println!("- **Input Source**: synthetic mockup ({}x{}, {} layers)", args.width, args.height, args.layers);
|
||||
sample_doc(args.width, args.height, layers)
|
||||
};
|
||||
|
||||
println!("- **Dimensions**: {}x{}", doc.size.width, doc.size.height);
|
||||
println!("- **Layer Count**: {}", doc.layers.len());
|
||||
println!();
|
||||
|
||||
let tmp_dir = std::env::temp_dir().join(format!("pc-bench-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&tmp_dir);
|
||||
let cpu_out = tmp_dir.join("cpu_out.png");
|
||||
let gpu_cold_out = tmp_dir.join("gpu_cold_out.png");
|
||||
let gpu_warm_out = tmp_dir.join("gpu_warm_out.png");
|
||||
|
||||
let opts = ExportOptions::default();
|
||||
|
||||
// 1. CPU Run
|
||||
print!("Benchmarking CPU export... ");
|
||||
let t0 = Instant::now();
|
||||
files::save_with_renderer(&doc, &cpu_out, Some("png"), &opts, None, None)?;
|
||||
let cpu_dur = t0.elapsed();
|
||||
println!("{:.2} ms", cpu_dur.as_secs_f64() * 1000.0);
|
||||
|
||||
// 2. GPU Cold Run
|
||||
print!("Benchmarking GPU cold export... ");
|
||||
let mut gpu_renderer = GpuRenderer::lazy();
|
||||
let t0 = Instant::now();
|
||||
let gpu_cold_res = files::save_with_renderer(&doc, &gpu_cold_out, Some("png"), &opts, None, Some(&mut gpu_renderer));
|
||||
let gpu_cold_dur = t0.elapsed();
|
||||
|
||||
let (gpu_succeeded, is_fallback) = match gpu_cold_res {
|
||||
Ok(warnings) => {
|
||||
let fallback = warnings.iter().any(|w| w.contains("falling back to CPU"));
|
||||
if fallback {
|
||||
println!("{:.2} ms (FALLBACK TO CPU: {:?})", gpu_cold_dur.as_secs_f64() * 1000.0, warnings);
|
||||
(true, true)
|
||||
} else if gpu_renderer.context().is_none() {
|
||||
// The export never reached the renderer (e.g. a single-layer input takes the
|
||||
// native path), so no GPU work ran: report it as CPU work, not a GPU result.
|
||||
println!("{:.2} ms (renderer not used)", gpu_cold_dur.as_secs_f64() * 1000.0);
|
||||
(false, true)
|
||||
} else {
|
||||
println!("{:.2} ms", gpu_cold_dur.as_secs_f64() * 1000.0);
|
||||
let adapter = gpu_renderer.adapter_name().unwrap_or("unknown");
|
||||
let is_soft = if gpu_renderer.is_software() { " (software rasterizer)" } else { " (hardware)" };
|
||||
println!("- **GPU Adapter**: `{adapter}`{is_soft}");
|
||||
(true, false)
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!("FAILED ({e})");
|
||||
let _ = std::fs::remove_dir_all(&tmp_dir);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
// 3. GPU Warm Runs
|
||||
let mut warm_durations = Vec::with_capacity(warm_runs);
|
||||
let mut warm_fallbacks = 0usize;
|
||||
if gpu_succeeded && !is_fallback && warm_runs > 0 {
|
||||
for run in 1..=warm_runs {
|
||||
print!("Benchmarking GPU warm export (run {run}/{warm_runs})... ");
|
||||
let t0 = Instant::now();
|
||||
let warm_res = files::save_with_renderer(&doc, &gpu_warm_out, Some("png"), &opts, None, Some(&mut gpu_renderer))?;
|
||||
let d = t0.elapsed();
|
||||
if warm_res.iter().any(|w| w.contains("falling back to CPU")) {
|
||||
warm_fallbacks += 1;
|
||||
println!("{:.2} ms (FALLBACK TO CPU)", d.as_secs_f64() * 1000.0);
|
||||
} else {
|
||||
println!("{:.2} ms", d.as_secs_f64() * 1000.0);
|
||||
warm_durations.push(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
println!();
|
||||
println!("### Summary Results");
|
||||
println!("| Mode | Duration | Relative to CPU | Note |");
|
||||
println!("|---|---|---|---|");
|
||||
println!("| CPU Baseline | {:.2} ms | 1.00x | Reference CPU compositor |", cpu_dur.as_secs_f64() * 1000.0);
|
||||
if is_fallback {
|
||||
println!("| GPU Cold | {:.2} ms | N/A | GPU not used (CPU fallback or a CPU-only export path); no GPU speedup |", gpu_cold_dur.as_secs_f64() * 1000.0);
|
||||
println!("| GPU Warm | N/A | N/A | Not measured (GPU not used) |");
|
||||
} else {
|
||||
let is_software = gpu_renderer.is_software();
|
||||
let adapter_note = if is_software { "Software rasterizer (e.g. lavapipe/llvmpipe)" } else { "Hardware GPU" };
|
||||
println!(
|
||||
"| GPU Cold | {:.2} ms | {:.2}x | Cold adapter initialization + pipeline build ({adapter_note}) |",
|
||||
gpu_cold_dur.as_secs_f64() * 1000.0,
|
||||
cpu_dur.as_secs_f64() / gpu_cold_dur.as_secs_f64()
|
||||
);
|
||||
if !warm_durations.is_empty() {
|
||||
let avg_warm: f64 = warm_durations.iter().map(|d| d.as_secs_f64()).sum::<f64>() / (warm_durations.len() as f64);
|
||||
// Runs that fell back to the CPU are excluded from the average: say how many.
|
||||
let note = match warm_fallback_note(warm_runs, warm_fallbacks) {
|
||||
Some(fallbacks) => format!("Reused device context and pipeline caches ({adapter_note}); {fallbacks} (excluded from the average)"),
|
||||
None => format!("Reused device context and pipeline caches ({adapter_note})"),
|
||||
};
|
||||
println!("| GPU Warm (avg) | {:.2} ms | {:.2}x | {note} |", avg_warm * 1000.0, cpu_dur.as_secs_f64() / avg_warm);
|
||||
} else if let Some(note) = warm_fallback_note(warm_runs, warm_fallbacks) {
|
||||
println!("| GPU Warm | N/A | N/A | {note} |");
|
||||
} else {
|
||||
println!("| GPU Warm | N/A | N/A | Not measured (0 warm runs requested) |");
|
||||
}
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(&tmp_dir);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The warm-run summary note when every measured warm run fell back to the CPU.
|
||||
fn warm_fallback_note(warm_runs: usize, warm_fallbacks: usize) -> Option<String> {
|
||||
(warm_fallbacks > 0).then(|| format!("{warm_fallbacks} of {warm_runs} warm runs fell back to CPU"))
|
||||
}
|
||||
|
||||
fn sample_doc(w: u32, h: u32, layer_count: usize) -> Document {
|
||||
let mut doc = Document::with_background("bench", Size::new(w, h), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let blend_modes = [BlendMode::Normal, BlendMode::Multiply, BlendMode::Screen, BlendMode::Overlay, BlendMode::Darken, BlendMode::Lighten];
|
||||
|
||||
for idx in 0..layer_count {
|
||||
let mut s = Surface::new(doc.pixel_format());
|
||||
let x0 = (idx as i32 * 20) % (w as i32 / 2).max(1);
|
||||
let y0 = (idx as i32 * 20) % (h as i32 / 2).max(1);
|
||||
let rw = (w as i32 - x0).max(1);
|
||||
let rh = (h as i32 - y0).max(1);
|
||||
s.fill_rect(Rect::new(x0, y0, x0 + rw, y0 + rh), &[0.3, 0.5, 0.7, 0.8]);
|
||||
let mut layer = Layer::new(format!("Layer {}", idx + 1), LayerContent::Raster(s));
|
||||
layer.opacity = 0.85;
|
||||
layer.blend = blend_modes[idx % blend_modes.len()];
|
||||
doc.layers.push(layer);
|
||||
}
|
||||
|
||||
doc
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn synthetic_documents_allow_one_pixel_dimensions() {
|
||||
for (width, height) in [(1, 1), (1, 16), (16, 1)] {
|
||||
let doc = sample_doc(width, height, 2);
|
||||
assert_eq!(doc.size, Size::new(width, height));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warm_summary_reports_fallbacks_instead_of_zero_runs() {
|
||||
assert_eq!(warm_fallback_note(3, 3).as_deref(), Some("3 of 3 warm runs fell back to CPU"));
|
||||
assert_eq!(warm_fallback_note(3, 1).as_deref(), Some("1 of 3 warm runs fell back to CPU"));
|
||||
assert_eq!(warm_fallback_note(0, 0), None);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use std::fmt;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub(crate) use crate::gpu::GpuArgs;
|
||||
use clap::error::ErrorKind;
|
||||
use clap::parser::ValueSource;
|
||||
use clap::{ArgAction, ArgGroup, ArgMatches, Args, CommandFactory, FromArgMatches, Parser, Subcommand};
|
||||
@@ -107,6 +108,8 @@ pub(crate) struct ConvertArgs {
|
||||
#[arg(long)]
|
||||
pub(crate) approve_high_memory: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
}
|
||||
|
||||
@@ -152,6 +155,8 @@ pub(crate) struct RunArgs {
|
||||
#[arg(long)]
|
||||
pub(crate) approve_high_memory: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
/// `--cmd` and `--params` values in command-line order, set by [`parse`].
|
||||
#[arg(skip)]
|
||||
@@ -210,6 +215,8 @@ pub(crate) struct BatchArgs {
|
||||
#[arg(long)]
|
||||
pub(crate) approve_high_memory: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) export: ExportArgs,
|
||||
}
|
||||
|
||||
@@ -253,6 +260,8 @@ pub(crate) struct McpArgs {
|
||||
#[arg(skip)]
|
||||
pub(crate) bridge_from_env: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) control: ControlArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
@@ -274,6 +283,8 @@ pub(crate) struct ServeArgs {
|
||||
#[arg(skip)]
|
||||
pub(crate) port_from_env: bool,
|
||||
#[command(flatten)]
|
||||
pub(crate) gpu: GpuArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) control: ControlArgs,
|
||||
#[command(flatten)]
|
||||
pub(crate) automation: AutomationArgs,
|
||||
@@ -311,6 +322,12 @@ enum ServerOptionError {
|
||||
/// authority the bridge can't give (#8035).
|
||||
#[error("configure automation roots on the desktop app; --automation-read-root and --automation-write-root require headless MCP mode")]
|
||||
BridgeRoots,
|
||||
/// Invalid value for PHOTOCRAFT_GPU.
|
||||
#[error("invalid value '{0}' for 'PHOTOCRAFT_GPU': expected '1' or '0'")]
|
||||
GpuVar(String),
|
||||
/// Explicit GPU flags require headless MCP mode, not bridge mode.
|
||||
#[error("configure rendering on the desktop app; --gpu and --no-gpu require headless MCP mode")]
|
||||
BridgeGpu,
|
||||
/// A token flag without the bridge or port that reads it would be ignored (#8035).
|
||||
#[error("{flag} requires {transport}")]
|
||||
NeedsTransport { flag: &'static str, transport: &'static str },
|
||||
@@ -319,8 +336,8 @@ enum ServerOptionError {
|
||||
impl ServerOptionError {
|
||||
fn into_clap(self, cmd: &mut clap::Command) -> clap::Error {
|
||||
let kind = match self {
|
||||
Self::BridgeVar(_) => ErrorKind::ValueValidation,
|
||||
Self::BridgeRoots => ErrorKind::ArgumentConflict,
|
||||
Self::BridgeVar(_) | Self::GpuVar(_) => ErrorKind::ValueValidation,
|
||||
Self::BridgeRoots | Self::BridgeGpu => ErrorKind::ArgumentConflict,
|
||||
Self::NeedsTransport { .. } => ErrorKind::MissingRequiredArgument,
|
||||
};
|
||||
cmd.error(kind, self)
|
||||
@@ -425,7 +442,10 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
let mut cli = Cli::from_arg_matches(&matches)?;
|
||||
let from_env = |m: &ArgMatches, id: &str| m.value_source(id) == Some(ValueSource::EnvVariable);
|
||||
match (&mut cli.command, matches.subcommand()) {
|
||||
(Command::Run(r), Some((_, m))) => r.steps = steps(m),
|
||||
(Command::Run(r), Some((_, m))) => {
|
||||
r.steps = steps(m);
|
||||
check_gpu_env(&mut cmd, m)?;
|
||||
}
|
||||
(Command::Mcp(a), Some((name, m))) => {
|
||||
a.bridge_from_env = from_env(m, "bridge");
|
||||
if a.bridge_from_env
|
||||
@@ -448,8 +468,15 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) {
|
||||
return Err(ServerOptionError::BridgeRoots.into_clap(sub));
|
||||
}
|
||||
if a.bridge.is_some() && (m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine))
|
||||
{
|
||||
return Err(ServerOptionError::BridgeGpu.into_clap(sub));
|
||||
}
|
||||
check_server(sub, m, a.bridge.is_some(), "--bridge")?;
|
||||
}
|
||||
if a.bridge.is_none() {
|
||||
check_gpu_env(&mut cmd, m)?;
|
||||
}
|
||||
}
|
||||
(Command::Serve(a), Some((name, m))) => {
|
||||
a.port_from_env = from_env(m, "port");
|
||||
@@ -460,12 +487,32 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
}
|
||||
check_server(sub, m, a.port.is_some(), "--port")?;
|
||||
}
|
||||
check_gpu_env(&mut cmd, m)?;
|
||||
}
|
||||
(Command::Convert(_), Some((_, m))) | (Command::Batch(_), Some((_, m))) => {
|
||||
check_gpu_env(&mut cmd, m)?;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(cli)
|
||||
}
|
||||
|
||||
fn check_gpu_env(cmd: &mut clap::Command, m: &ArgMatches) -> Result<(), clap::Error> {
|
||||
if m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = std::env::var_os("PHOTOCRAFT_GPU") {
|
||||
// A non-UTF-8 value is still a value other than empty, "0" or "1": reject it rather
|
||||
// than silently treating it as unset and running on the CPU.
|
||||
let v = v.to_string_lossy();
|
||||
let trimmed = v.trim();
|
||||
if !trimmed.is_empty() && trimmed != "1" && trimmed != "0" {
|
||||
return Err(ServerOptionError::GpuVar(trimmed.to_string()).into_clap(cmd));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Refuse a token flag without the bridge or port that reads it (as a flag or its variable). A
|
||||
/// token variable alone may be a stale export, so it isn't refused.
|
||||
fn check_server(sub: &mut clap::Command, m: &ArgMatches, has_transport: bool, transport: &'static str) -> Result<(), clap::Error> {
|
||||
|
||||
@@ -34,7 +34,13 @@ pub(crate) fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result {
|
||||
|
||||
pub(crate) fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result {
|
||||
use std::sync::{Arc, Mutex};
|
||||
let h = Arc::new(Mutex::new(Headless::with_workspace(a.automation.workspace()?)));
|
||||
let mut h = Headless::with_workspace(a.automation.workspace()?);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
for d in h.drain_diagnostics() {
|
||||
let _ = writeln!(err, "warning: {d}");
|
||||
}
|
||||
let h = Arc::new(Mutex::new(h));
|
||||
match a.port {
|
||||
Some(port) => {
|
||||
if a.port_from_env {
|
||||
@@ -75,7 +81,15 @@ pub(crate) fn mcp(a: &McpArgs, err: &mut dyn Write) -> Result {
|
||||
let token = security::client_token(a.control.control_token.as_deref(), a.control.control_token_file.as_deref())?;
|
||||
PhotocraftMcp::bridge(&addr.to_string(), &token)?
|
||||
}
|
||||
None => PhotocraftMcp::headless_with_workspace(a.automation.workspace()?),
|
||||
None => {
|
||||
let mut h = Headless::with_workspace(a.automation.workspace()?);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(crate::CliError::Other)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
for d in h.drain_diagnostics() {
|
||||
let _ = writeln!(err, "warning: {d}");
|
||||
}
|
||||
PhotocraftMcp::with_headless(h)
|
||||
}
|
||||
};
|
||||
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build()?;
|
||||
Ok(rt.block_on(server.serve_stdio())?)
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::{
|
||||
CliError, Result,
|
||||
actions::load_actions_file,
|
||||
args::{BatchArgs, DropletArgs},
|
||||
output::warn_all,
|
||||
output::{warn_all, warn_dedup},
|
||||
};
|
||||
|
||||
/// Whether `a` and `b` name the same existing folder, however they are spelt (relative, with a
|
||||
@@ -51,7 +51,8 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
let (in_dir, out_dir) = (a.in_dir.as_path(), a.out.as_path());
|
||||
let (actions, mut set, warnings) = load_actions_file(&a.actions, a.action.as_deref())?;
|
||||
set.iter_mut().for_each(strip_shell_steps);
|
||||
warn_all(err, &warnings);
|
||||
let mut seen_warnings = std::collections::HashSet::<String>::new();
|
||||
warn_dedup(err, &warnings, &mut seen_warnings);
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
// Results are saved as `<out>/<stem>.<ext>`, so an `--out` that is the `--in` folder would
|
||||
// replace the originals (#492).
|
||||
@@ -109,17 +110,20 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
}
|
||||
std::fs::create_dir_all(out_dir)?;
|
||||
let mut failures = Vec::new();
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
let mut renderer = policy.create_renderer();
|
||||
for (input, target) in inputs.iter().zip(targets) {
|
||||
let input = Path::new(&input.path);
|
||||
// The selected format encodes the bytes, whatever extension `--naming` gives the file.
|
||||
// Without --format, a file PhotoCraft only opens (.kra, raw, …) is saved as PSD, the
|
||||
// same format `--naming`'s {ext} plans.
|
||||
let ext = format.map_or_else(|| photocraft_engine::file_cmds::batch_same_format(&input.to_string_lossy()), str::to_owned);
|
||||
let mut h = Headless::trusted_local();
|
||||
h.set_renderer(renderer.take());
|
||||
let r = (|| -> Result<Vec<String>> {
|
||||
if let Some(parent) = target.parent() {
|
||||
std::fs::create_dir_all(parent)?;
|
||||
}
|
||||
let mut h = Headless::trusted_local();
|
||||
// Steps that play another action find it in the set; the session's playback stack
|
||||
// stops an action that calls itself.
|
||||
h.session.actions.list = set.clone();
|
||||
@@ -140,15 +144,30 @@ pub(crate) fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
let r = h.save(None, Some(&target), Some(&ext), &opts)?;
|
||||
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
|
||||
})();
|
||||
let diags = h.drain_diagnostics();
|
||||
// Release the item's GPU caches before the renderer moves on to the next file.
|
||||
if h.session.active_index().is_some() {
|
||||
let _ = h.close(None);
|
||||
}
|
||||
if let Some(recovered) = h.take_renderer() {
|
||||
renderer = Some(recovered);
|
||||
}
|
||||
match r {
|
||||
Ok(ws) => {
|
||||
ok += 1;
|
||||
let _ = writeln!(out, "ok {} -> {}", input.display(), target.display());
|
||||
// Each file's own export warnings (e.g. transparency composited over white) are
|
||||
// reported for that file, even when an earlier file had the same warning.
|
||||
warn_all(err, &ws);
|
||||
// A fallback diagnostic can also be in this file's export warnings; report it
|
||||
// once, through the per-file warnings above, not twice.
|
||||
let pending: Vec<String> = diags.into_iter().filter(|d| !ws.contains(d)).collect();
|
||||
warn_dedup(err, &pending, &mut seen_warnings);
|
||||
}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
let _ = writeln!(err, "FAIL {}: {e}", input.display());
|
||||
warn_dedup(err, &diags, &mut seen_warnings);
|
||||
failures.push((input.to_string_lossy().into_owned(), e.to_string()));
|
||||
if a.stop_on_error {
|
||||
break;
|
||||
@@ -267,3 +286,79 @@ mod batch_action_set_tests {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use photocraft_doc::{Color, ColorMode, Document, Rect, SampleType, Size};
|
||||
use photocraft_io::{BandRenderer, IoError, RenderBand, RenderError};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
struct RecordingRenderer {
|
||||
calls: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
impl BandRenderer for RecordingRenderer {
|
||||
fn render_bands(
|
||||
&mut self,
|
||||
doc: &Document,
|
||||
rect: Rect,
|
||||
band_rows: i32,
|
||||
ctl: &photocraft_raster::Interrupt<'_>,
|
||||
sink: &mut dyn FnMut(RenderBand) -> Result<(), IoError>,
|
||||
) -> Result<(), RenderError> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
photocraft_io::CpuRenderer.render_bands(doc, rect, band_rows, ctl, sink)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_loop_recovers_renderer_after_error_on_first_item() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let mut renderer: Option<Box<dyn BandRenderer>> = Some(Box::new(RecordingRenderer { calls: calls.clone() }));
|
||||
|
||||
let tmp = std::env::temp_dir().join(format!("pc-batch-regress-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
std::fs::create_dir_all(&tmp).unwrap();
|
||||
|
||||
let bad_file = tmp.join("01_bad.png");
|
||||
std::fs::write(&bad_file, b"not a valid png or document file").unwrap();
|
||||
|
||||
let good_file = tmp.join("02_good.pcraft");
|
||||
let mut good_doc = Document::with_background("test", Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let extra_layer = good_doc.layers[0].clone();
|
||||
good_doc.layers.push(extra_layer);
|
||||
photocraft_automation::files::save(&good_doc, &good_file, None, &Default::default(), None).unwrap();
|
||||
|
||||
let target_dir = tmp.join("out");
|
||||
std::fs::create_dir_all(&target_dir).unwrap();
|
||||
|
||||
let inputs = [bad_file, good_file];
|
||||
let opts = ExportOptions::default();
|
||||
|
||||
for (idx, input) in inputs.iter().enumerate() {
|
||||
let mut h = Headless::trusted_local();
|
||||
h.set_renderer(renderer.take());
|
||||
let r = (|| -> Result<Vec<String>> {
|
||||
h.open(input)?;
|
||||
let target = target_dir.join(format!("{idx}.png"));
|
||||
let r = h.save(None, Some(&target), Some("png"), &opts)?;
|
||||
Ok(serde_json::from_value(r["warnings"].clone()).unwrap_or_default())
|
||||
})();
|
||||
if let Some(recovered) = h.take_renderer() {
|
||||
renderer = Some(recovered);
|
||||
}
|
||||
if idx == 0 {
|
||||
assert!(r.is_err(), "first corrupt item must fail");
|
||||
} else {
|
||||
assert!(r.is_ok(), "second valid item must succeed: {:?}", r);
|
||||
}
|
||||
}
|
||||
|
||||
assert!(renderer.is_some(), "renderer must be preserved across batch items");
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1, "renderer must have been invoked on the second item");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&tmp);
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use photocraft_io::ExportOptions;
|
||||
use crate::{
|
||||
CliError, Result,
|
||||
args::{ConvertArgs, InfoArgs, RunArgs, Step},
|
||||
output::{JsonStyle, print_json, warn_all},
|
||||
output::{JsonStyle, print_json, warn_all, warn_dedup},
|
||||
};
|
||||
|
||||
/// An output that is the input file itself, however it is spelt (relative, with `./`, through a
|
||||
@@ -34,10 +34,22 @@ pub(crate) fn convert(a: &ConvertArgs, _out: &mut dyn Write, err: &mut dyn Write
|
||||
let mut o = files::open_with_options(input, &import_opts)?;
|
||||
// Preferences › Raw Defaults › Resolution at its default, as `run` and `info` open a raw.
|
||||
photocraft_engine::file_cmds::raw_defaults(&photocraft_engine::Session::new(), &o.warnings, &mut o.document);
|
||||
warn_all(err, &o.warnings);
|
||||
warn_all(err, &missing_font_warnings(&o.document));
|
||||
let ws = files::save(&o.document, output, a.export.format.as_deref(), &opts, None)?;
|
||||
warn_all(err, &ws);
|
||||
let mut seen_warnings = std::collections::HashSet::<String>::new();
|
||||
warn_dedup(err, &o.warnings, &mut seen_warnings);
|
||||
warn_dedup(err, &missing_font_warnings(&o.document), &mut seen_warnings);
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
let mut renderer = policy.create_renderer();
|
||||
let ws = match renderer.as_mut() {
|
||||
Some(renderer) => files::save_with_renderer(&o.document, output, a.export.format.as_deref(), &opts, None, Some(&mut **renderer)),
|
||||
None => files::save(&o.document, output, a.export.format.as_deref(), &opts, None),
|
||||
};
|
||||
// A failed GPU export can leave fallback reasons queued: report them before the error
|
||||
// propagates, or the user would never learn why the GPU was not used.
|
||||
if let Some(renderer) = renderer.as_mut() {
|
||||
warn_dedup(err, &renderer.drain_diagnostics(), &mut seen_warnings);
|
||||
}
|
||||
let ws = ws?;
|
||||
warn_dedup(err, &ws, &mut seen_warnings);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -73,9 +85,14 @@ fn command_list(a: &RunArgs) -> Result<Vec<(String, Value)>> {
|
||||
Ok(cmds)
|
||||
}
|
||||
|
||||
/// Reported once by `run --gpu` when a step is `file.export.quickExport`.
|
||||
const QUICK_EXPORT_CPU_NOTE: &str = "file.export.quickExport runs on the CPU compositor; --gpu applies to --out and the export commands that take a renderer";
|
||||
|
||||
pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result {
|
||||
let opts = ExportOptions::from(&a.export);
|
||||
let mut h = Headless::trusted_local();
|
||||
let policy = crate::gpu::GpuPolicy::from_args(&a.gpu).map_err(CliError::Other)?;
|
||||
policy.apply_to_headless(&mut h);
|
||||
// Opening, running commands and exporting can all notice the same missing font:
|
||||
// one `run` invocation reports each warning line at most once.
|
||||
let mut reported_fonts = std::collections::HashSet::<String>::new();
|
||||
@@ -106,6 +123,11 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
let new_warnings: Vec<String> =
|
||||
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &new_warnings);
|
||||
// Quick Export composites and encodes inside the engine, which has no renderer: say so
|
||||
// once, so `--gpu` never looks as if it applied to it (docs/development.md, GPU).
|
||||
if policy.enabled && id == "file.export.quickExport" {
|
||||
warn_dedup(err, &[QUICK_EXPORT_CPU_NOTE.to_string()], &mut reported_fonts);
|
||||
}
|
||||
let mut result = json!({"command": id, "result": r});
|
||||
if !new_warnings.is_empty() {
|
||||
result["warnings"] = json!(new_warnings);
|
||||
@@ -117,11 +139,19 @@ pub(crate) fn run_cmds(a: &RunArgs, out: &mut dyn Write, err: &mut dyn Write) ->
|
||||
h.session.active().map(|st| missing_font_warnings(&st.doc)).unwrap_or_default().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &remaining);
|
||||
if let Some(o) = a.out.as_deref() {
|
||||
let r = h.save(None, Some(o), a.export.format.as_deref(), &opts)?;
|
||||
let saved = h.save(None, Some(o), a.export.format.as_deref(), &opts);
|
||||
// Report GPU diagnostics even when the export fails: the fallback reason is queued
|
||||
// during the failed export and would otherwise be lost on the error path.
|
||||
let failed_diags: Vec<String> = h.drain_diagnostics().into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &failed_diags);
|
||||
let r = saved?;
|
||||
let ws: Vec<String> = serde_json::from_value(r["warnings"].clone()).unwrap_or_default();
|
||||
let ws: Vec<String> = ws.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &ws);
|
||||
}
|
||||
let diags = h.drain_diagnostics();
|
||||
let diags: Vec<String> = diags.into_iter().filter(|w| reported_fonts.insert(w.clone())).collect();
|
||||
warn_all(err, &diags);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,8 @@ pub(crate) enum CliError {
|
||||
BatchOption(String),
|
||||
#[error("{0} file(s) failed")]
|
||||
FilesFailed(usize),
|
||||
#[error("{0}")]
|
||||
Other(String),
|
||||
}
|
||||
|
||||
pub(crate) type Result<T = (), E = CliError> = std::result::Result<T, E>;
|
||||
@@ -0,0 +1,112 @@
|
||||
//! GPU acceleration policy and options for photocraft-cli.
|
||||
|
||||
use photocraft_automation::Headless;
|
||||
use photocraft_io::BandRenderer;
|
||||
|
||||
/// Optional GPU composition for supported flat exports and full-size previews.
|
||||
#[derive(clap::Args)]
|
||||
pub(crate) struct GpuArgs {
|
||||
/// Prefer GPU rendering, falling back to CPU when unavailable or unsupported
|
||||
#[arg(long, conflicts_with = "no_gpu")]
|
||||
pub(crate) gpu: bool,
|
||||
/// Use CPU rendering, overriding PHOTOCRAFT_GPU
|
||||
#[arg(long, conflicts_with = "gpu")]
|
||||
pub(crate) no_gpu: bool,
|
||||
}
|
||||
|
||||
/// Resolved GPU rendering policy.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct GpuPolicy {
|
||||
pub(crate) enabled: bool,
|
||||
}
|
||||
|
||||
impl GpuPolicy {
|
||||
/// Resolve policy from arguments and environment.
|
||||
///
|
||||
/// Precedence:
|
||||
/// - Explicit `--gpu` enables GPU.
|
||||
/// - Explicit `--no-gpu` disables GPU.
|
||||
/// - Neither flag: `PHOTOCRAFT_GPU` env var (1 = enabled, 0 or empty/unset = disabled).
|
||||
/// Any other nonempty value is rejected.
|
||||
pub(crate) fn from_args(args: &GpuArgs) -> Result<Self, String> {
|
||||
if args.gpu {
|
||||
return Ok(Self { enabled: true });
|
||||
}
|
||||
if args.no_gpu {
|
||||
return Ok(Self { enabled: false });
|
||||
}
|
||||
match std::env::var_os("PHOTOCRAFT_GPU") {
|
||||
Some(val) => {
|
||||
let val = val.to_string_lossy();
|
||||
let trimmed = val.trim();
|
||||
if trimmed.is_empty() || trimmed == "0" {
|
||||
Ok(Self { enabled: false })
|
||||
} else if trimmed == "1" {
|
||||
Ok(Self { enabled: true })
|
||||
} else {
|
||||
Err(format!("invalid value '{trimmed}' for 'PHOTOCRAFT_GPU': expected '1' or '0'"))
|
||||
}
|
||||
}
|
||||
None => Ok(Self { enabled: false }),
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply policy to a headless automation session.
|
||||
pub(crate) fn apply_to_headless(&self, h: &mut Headless) {
|
||||
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
|
||||
if self.enabled {
|
||||
h.enable_gpu();
|
||||
}
|
||||
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
|
||||
if self.enabled {
|
||||
h.set_renderer(Some(Box::new(DisabledGpuRenderer::new())));
|
||||
}
|
||||
}
|
||||
|
||||
/// Create an optional boxed renderer under this policy.
|
||||
#[cfg(all(feature = "gpu", not(target_arch = "wasm32")))]
|
||||
pub(crate) fn create_renderer(&self) -> Option<Box<dyn BandRenderer>> {
|
||||
if self.enabled { Some(Box::new(photocraft_automation::gpu::GpuRenderer::lazy())) } else { None }
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
|
||||
pub(crate) fn create_renderer(&self) -> Option<Box<dyn BandRenderer>> {
|
||||
if self.enabled { Some(Box::new(DisabledGpuRenderer::new())) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
/// Renderer stub emitted when GPU is requested in builds compiled without `--features gpu`.
|
||||
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
|
||||
struct DisabledGpuRenderer {
|
||||
emitted: bool,
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
|
||||
impl DisabledGpuRenderer {
|
||||
fn new() -> Self {
|
||||
Self { emitted: false }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(not(feature = "gpu"), target_arch = "wasm32"))]
|
||||
impl BandRenderer for DisabledGpuRenderer {
|
||||
fn render_bands(
|
||||
&mut self,
|
||||
_doc: &photocraft_doc::Document,
|
||||
_rect: photocraft_doc::Rect,
|
||||
_band_rows: i32,
|
||||
_ctl: &photocraft_raster::Interrupt<'_>,
|
||||
_sink: &mut dyn FnMut(photocraft_io::RenderBand) -> Result<(), photocraft_io::IoError>,
|
||||
) -> Result<(), photocraft_io::RenderError> {
|
||||
Err(photocraft_io::RenderError::Unavailable("GPU support is not compiled in this build (compile with --features gpu)".into()))
|
||||
}
|
||||
|
||||
fn drain_diagnostics(&mut self) -> Vec<String> {
|
||||
if self.emitted {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.emitted = true;
|
||||
vec!["GPU acceleration requested but this build was compiled without GPU support (compile with --features gpu); falling back to CPU".into()]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ mod automation;
|
||||
mod batch;
|
||||
mod document;
|
||||
mod error;
|
||||
mod gpu;
|
||||
mod output;
|
||||
|
||||
pub use actions::{ActionsError, Steps, load_actions, load_actions_file, parse_actions};
|
||||
|
||||
@@ -43,6 +43,14 @@ pub(crate) fn warn_all(err: &mut dyn Write, ws: &[String]) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn warn_dedup(err: &mut dyn Write, ws: &[String], seen: &mut std::collections::HashSet<String>) {
|
||||
for w in ws {
|
||||
if seen.insert(w.clone()) {
|
||||
let _ = writeln!(err, "warning: {w}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`print_json`] lays the JSON out.
|
||||
pub(crate) enum JsonStyle {
|
||||
Pretty,
|
||||
|
||||
@@ -15,7 +15,7 @@ fn bin() -> Command {
|
||||
cmd
|
||||
}
|
||||
|
||||
const ENV_VARS: [&str; 3] = ["PHOTOCRAFT_CONTROL_PORT", "PHOTOCRAFT_CONTROL_TOKEN", "PHOTOCRAFT_CONTROL_TOKEN_FILE"];
|
||||
const ENV_VARS: [&str; 4] = ["PHOTOCRAFT_CONTROL_PORT", "PHOTOCRAFT_CONTROL_TOKEN", "PHOTOCRAFT_CONTROL_TOKEN_FILE", "PHOTOCRAFT_GPU"];
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pc-cli-{}-{name}", std::process::id()));
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
//! Tests for photocraft-cli GPU rendering flags, precedence, and fallback behavior.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
fn bin() -> Command {
|
||||
let mut cmd = Command::new(crate::binary());
|
||||
cmd.env_remove("PHOTOCRAFT_CONTROL_PORT");
|
||||
cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN");
|
||||
cmd.env_remove("PHOTOCRAFT_CONTROL_TOKEN_FILE");
|
||||
cmd.env_remove("PHOTOCRAFT_GPU");
|
||||
cmd
|
||||
}
|
||||
|
||||
fn tmp(name: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("pc-cli-gpu-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
fn write_png(path: &Path, w: u32, h: u32) {
|
||||
let data: Vec<u8> = (0..w * h * 4).map(|i| (i as u8).wrapping_mul(7)).collect();
|
||||
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgba, data).unwrap();
|
||||
std::fs::write(path, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_and_no_gpu_conflict() {
|
||||
let d = tmp("conflict");
|
||||
let in_png = d.join("in.png");
|
||||
let out_png = d.join("out.png");
|
||||
write_png(&in_png, 16, 16);
|
||||
|
||||
let o = bin().args(["convert", "--gpu", "--no-gpu", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("cannot be used with") || stderr.contains("conflicts with"), "{stderr}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_env_var_validation() {
|
||||
let d = tmp("env_val");
|
||||
let in_png = d.join("in.png");
|
||||
let out_png = d.join("out.png");
|
||||
write_png(&in_png, 16, 16);
|
||||
|
||||
// Invalid non-empty value rejected with usage error naming the variable
|
||||
for bad in ["2", "true", "yes", "false", "on", "off"] {
|
||||
let o = bin().env("PHOTOCRAFT_GPU", bad).args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2), "expected exit 2 for PHOTOCRAFT_GPU={bad}");
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("PHOTOCRAFT_GPU"), "expected stderr to name variable: {stderr}");
|
||||
assert!(stderr.contains("expected '1' or '0'"), "expected usage note: {stderr}");
|
||||
}
|
||||
|
||||
// Empty or blank value is accepted as unset (CPU default)
|
||||
for empty in ["", " "] {
|
||||
let out_sub = d.join(format!("out_{}.png", empty.trim()));
|
||||
let o = bin().env("PHOTOCRAFT_GPU", empty).args(["convert", in_png.to_str().unwrap(), out_sub.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "expected success for PHOTOCRAFT_GPU={empty:?}");
|
||||
assert!(out_sub.is_file());
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn gpu_env_var_rejects_a_non_utf8_value() {
|
||||
use std::ffi::OsString;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
|
||||
let d = tmp("env_non_utf8");
|
||||
let in_png = d.join("in.png");
|
||||
let out_png = d.join("out.png");
|
||||
write_png(&in_png, 16, 16);
|
||||
|
||||
let bad = OsString::from_vec(vec![0xff, 0xfe]);
|
||||
let o = bin().env("PHOTOCRAFT_GPU", bad).args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2), "a non-UTF-8 PHOTOCRAFT_GPU must be a usage error");
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("PHOTOCRAFT_GPU"), "the usage error must name the variable: {stderr}");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_flags_override_environment() {
|
||||
let d = tmp("override");
|
||||
let in_png = d.join("in.png");
|
||||
let in_layers = d.join("in.pcraft");
|
||||
let out1 = d.join("out1.png");
|
||||
let out2 = d.join("out2.png");
|
||||
write_png(&in_png, 16, 16);
|
||||
// A single-layer PNG takes the native export path and never calls the renderer; a
|
||||
// multi-layer document composites, so it observes whether `--gpu` reached the backend.
|
||||
let o = bin().args(["run", "--new", r#"{"width":16,"height":16}"#, "--cmd", "layer.new.layer", "--out", in_layers.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
|
||||
// --no-gpu overrides PHOTOCRAFT_GPU=1
|
||||
let o = bin().env("PHOTOCRAFT_GPU", "1").args(["convert", "--no-gpu", in_png.to_str().unwrap(), out1.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out1.is_file());
|
||||
|
||||
// --gpu overrides PHOTOCRAFT_GPU=0
|
||||
let o = bin().env("PHOTOCRAFT_GPU", "0").args(["convert", "--gpu", in_layers.to_str().unwrap(), out2.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out2.is_file());
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
// The renderer reports either its adapter, an unavailable adapter, or (in a build without
|
||||
// GPU support) that GPU rendering was requested; the CPU default emits none of these.
|
||||
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU"];
|
||||
assert!(markers.iter().any(|marker| stderr.contains(marker)), "explicit --gpu must reach the renderer when the environment disables it: {stderr}");
|
||||
|
||||
// Explicit flag overrides even bad environment value
|
||||
let out3 = d.join("out3.png");
|
||||
let o = bin().env("PHOTOCRAFT_GPU", "invalid").args(["convert", "--no-gpu", in_png.to_str().unwrap(), out3.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out3.is_file());
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_bridge_rejects_explicit_gpu_flags_and_ignores_env() {
|
||||
// Explicit --gpu with --bridge rejected
|
||||
let o = bin().args(["mcp", "--bridge", "127.0.0.1:50000", "--gpu"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("configure rendering on the desktop app"), "{stderr}");
|
||||
|
||||
// Explicit --no-gpu with --bridge rejected
|
||||
let o = bin().args(["mcp", "--bridge", "127.0.0.1:50000", "--no-gpu"]).output().unwrap();
|
||||
assert_eq!(o.status.code(), Some(2));
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("configure rendering on the desktop app"), "{stderr}");
|
||||
|
||||
// An invalid PHOTOCRAFT_GPU value is ignored in bridge mode: the desktop process controls
|
||||
// rendering, so the bridge must not validate the variable or reject the request for it.
|
||||
let o = bin().env("PHOTOCRAFT_GPU", "invalid").args(["mcp", "--bridge", "127.0.0.1:50000"]).stdin(std::process::Stdio::null()).output().unwrap();
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(!stderr.contains("PHOTOCRAFT_GPU"), "bridge mode must ignore the GPU environment: {stderr}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_and_run_honor_gpu_flag_and_preserve_stdout_protocol() {
|
||||
let d = tmp("protocol");
|
||||
let out_png = d.join("out.png");
|
||||
|
||||
// run --gpu output on stdout is clean JSON
|
||||
let o =
|
||||
bin().args(["run", "--gpu", "--new", r#"{"width":32,"height":32}"#, "--cmd", "layer.new.layer", "--out", out_png.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out_png.is_file());
|
||||
let stdout = String::from_utf8_lossy(&o.stdout);
|
||||
for line in stdout.lines() {
|
||||
let v: Value = serde_json::from_str(line).expect("each stdout line must be valid JSON");
|
||||
assert!(v.get("command").is_some());
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_recovers_renderer_after_failed_item_and_preserves_gpu_policy() {
|
||||
let d = tmp("batch_regress");
|
||||
let in_dir = d.join("in");
|
||||
let out_dir = d.join("out");
|
||||
std::fs::create_dir_all(&in_dir).unwrap();
|
||||
std::fs::create_dir_all(&out_dir).unwrap();
|
||||
|
||||
// First item is corrupt and fails to open
|
||||
let corrupt_png = in_dir.join("01_corrupt.png");
|
||||
std::fs::write(&corrupt_png, b"invalid png bytes").unwrap();
|
||||
|
||||
// Second item is valid
|
||||
let valid_png = in_dir.join("02_valid.png");
|
||||
write_png(&valid_png, 32, 32);
|
||||
|
||||
let actions = d.join("actions.json");
|
||||
std::fs::write(&actions, serde_json::json!([{"command": "layer.new.layer", "params": {"name": "Batch"}}]).to_string()).unwrap();
|
||||
let o = bin()
|
||||
.args(["batch", "--gpu", "--actions"])
|
||||
.arg(&actions)
|
||||
.args(["--in", in_dir.to_str().unwrap(), "--out", out_dir.to_str().unwrap()])
|
||||
.output()
|
||||
.unwrap();
|
||||
|
||||
// Exit code 1 because 1 file failed
|
||||
assert_eq!(o.status.code(), Some(1));
|
||||
let stdout = String::from_utf8_lossy(&o.stdout);
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
|
||||
assert!(stdout.contains("1 succeeded, 1 failed"), "stdout: {stdout}");
|
||||
assert!(stderr.contains("FAIL"), "stderr must report failing item: {stderr}");
|
||||
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU"];
|
||||
assert!(markers.iter().any(|marker| stderr.contains(marker)), "--gpu must reach the batch renderer: {stderr}");
|
||||
assert!(out_dir.join("02_valid.png").is_file(), "second item must have been saved successfully");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn diagnostics_preserve_clean_stdout_and_emit_to_stderr() {
|
||||
let d = tmp("diag_clean");
|
||||
let in_png = d.join("in.png");
|
||||
let out_png = d.join("out.png");
|
||||
write_png(&in_png, 32, 32);
|
||||
|
||||
let o = bin().args(["convert", "--gpu", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
|
||||
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out_png.is_file());
|
||||
// Convert emits no stdout; diagnostics must go to stderr
|
||||
assert!(o.stdout.is_empty(), "convert stdout must remain completely empty, got: {:?}", String::from_utf8_lossy(&o.stdout));
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(stderr.contains("falling back to CPU"), "single-layer convert must report its CPU fallback on stderr: {stderr}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_gpu_preserves_clean_protocol_stdout_and_drains_diagnostics_to_stderr() {
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::process::Stdio;
|
||||
|
||||
let mut child = bin().args(["serve", "--gpu"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().unwrap();
|
||||
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let mut stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
|
||||
// 1. Initial valid command
|
||||
writeln!(stdin, "{}", serde_json::json!({"id": 1, "method": "doc.new", "params": {"width": 16, "height": 16}})).unwrap();
|
||||
stdin.flush().unwrap();
|
||||
|
||||
let mut line1 = String::new();
|
||||
assert!(stdout.read_line(&mut line1).unwrap() > 0, "server must respond");
|
||||
let v1: Value = serde_json::from_str(&line1).expect("line 1 on stdout must be valid JSON");
|
||||
assert_eq!(v1["id"], 1);
|
||||
assert_eq!(v1["ok"], true, "{v1}");
|
||||
|
||||
// 2. A second layer so the render below composites instead of taking the native path.
|
||||
writeln!(stdin, "{}", serde_json::json!({"id": 2, "method": "engine.execute", "params": {"command": "layer.new.layer", "params": {"name": "Top"}}}))
|
||||
.unwrap();
|
||||
stdin.flush().unwrap();
|
||||
|
||||
let mut line2 = String::new();
|
||||
assert!(stdout.read_line(&mut line2).unwrap() > 0, "server must respond to the layer command");
|
||||
let v2: Value = serde_json::from_str(&line2).expect("line 2 on stdout must be valid JSON");
|
||||
assert_eq!(v2["id"], 2);
|
||||
assert_eq!(v2["ok"], true, "{v2}");
|
||||
|
||||
// 3. Failure recovery: invalid request receives error reply without crashing server
|
||||
writeln!(stdin, "{}", serde_json::json!({"id": 3, "method": "invalid.nonexistent.method", "params": {}})).unwrap();
|
||||
stdin.flush().unwrap();
|
||||
|
||||
let mut line3 = String::new();
|
||||
assert!(stdout.read_line(&mut line3).unwrap() > 0, "server must respond to invalid request");
|
||||
let v3: Value = serde_json::from_str(&line3).expect("line 3 on stdout must be valid JSON");
|
||||
assert_eq!(v3["id"], 3);
|
||||
assert_eq!(v3["ok"], false, "{v3}");
|
||||
|
||||
// 4. Subsequent valid command still succeeds (proves session & renderer recovery)
|
||||
writeln!(stdin, "{}", serde_json::json!({"id": 4, "method": "doc.inspect"})).unwrap();
|
||||
stdin.flush().unwrap();
|
||||
|
||||
let mut line4 = String::new();
|
||||
assert!(stdout.read_line(&mut line4).unwrap() > 0, "server must respond to the inspect request");
|
||||
let v4: Value = serde_json::from_str(&line4).expect("line 4 on stdout must be valid JSON");
|
||||
assert_eq!(v4["id"], 4);
|
||||
assert_eq!(v4["ok"], true, "{v4}");
|
||||
|
||||
// 5. Render the composite: one JSON line on stdout, diagnostics only on stderr.
|
||||
writeln!(stdin, "{}", serde_json::json!({"id": 5, "method": "doc.render", "params": {"maxSide": 16}})).unwrap();
|
||||
stdin.flush().unwrap();
|
||||
|
||||
let mut line5 = String::new();
|
||||
assert!(stdout.read_line(&mut line5).unwrap() > 0, "server must answer the render request");
|
||||
let v5: Value = serde_json::from_str(&line5).expect("line 5 on stdout must be valid JSON");
|
||||
assert_eq!(v5["id"], 5);
|
||||
assert_eq!(v5["ok"], true, "{v5}");
|
||||
assert!(v5["result"]["base64"].as_str().is_some_and(|b| !b.is_empty()), "render must return PNG bytes: {v5}");
|
||||
|
||||
// Close stdin and verify graceful exit
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
assert!(output.status.success());
|
||||
|
||||
// Every render that reaches the renderer reports its adapter or why it fell back, whichever
|
||||
// build and adapter this test runs on.
|
||||
// `doc.render` returns the diagnostics of its own render in the reply's `warnings`; any left
|
||||
// in the queue go to stderr. Either way they stay off the protocol lines' framing.
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let reported = format!("{stderr}\n{}", v5["result"]["warnings"]);
|
||||
let markers = ["GPU adapter:", "no GPU adapter available", "could not build GPU compositor", "falling back to CPU", "GPU acceleration requested"];
|
||||
assert!(markers.iter().any(|m| reported.contains(m)), "render must report its GPU backend or fallback in its reply or on stderr: {reported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_default_does_not_emit_gpu_warnings() {
|
||||
let d = tmp("cpu_default");
|
||||
let in_png = d.join("in.png");
|
||||
let out_png = d.join("out.png");
|
||||
write_png(&in_png, 16, 16);
|
||||
|
||||
let o = bin().args(["convert", in_png.to_str().unwrap(), out_png.to_str().unwrap()]).output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out_png.is_file());
|
||||
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert!(!stderr.contains("GPU"), "default CPU convert should not emit GPU warnings, got: {stderr}");
|
||||
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_gpu_quick_export_reports_that_it_runs_on_the_cpu() {
|
||||
let d = tmp("quick_export");
|
||||
let out_png = d.join("quick.png");
|
||||
let params = format!(r#"{{"path":{}}}"#, serde_json::to_string(&out_png.to_string_lossy()).unwrap());
|
||||
let args = ["run", "--new", r#"{"width":16,"height":16,"background":"white"}"#, "--cmd", "file.export.quickExport", "--params", params.as_str()];
|
||||
let o = bin().args(args).arg("--gpu").output().unwrap();
|
||||
assert!(o.status.success(), "stderr: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(out_png.is_file());
|
||||
let stderr = String::from_utf8_lossy(&o.stderr);
|
||||
assert_eq!(stderr.matches("quickExport runs on the CPU compositor").count(), 1, "one CPU note expected: {stderr}");
|
||||
|
||||
let o = bin().args(args).output().unwrap();
|
||||
assert!(o.status.success());
|
||||
assert!(!String::from_utf8_lossy(&o.stderr).contains("runs on the CPU compositor"), "no note without --gpu");
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The crate's integration tests, linked into one test binary.
|
||||
|
||||
mod cli;
|
||||
mod gpu;
|
||||
#[cfg(all(target_os = "linux", target_env = "gnu"))]
|
||||
mod malloc_tuning;
|
||||
|
||||
mod man_and_completions;
|
||||
mod orientation;
|
||||
|
||||
|
||||
@@ -73,6 +73,11 @@ impl Headless {
|
||||
self.renderer = renderer;
|
||||
}
|
||||
|
||||
/// Take the active renderer out of this session.
|
||||
pub fn take_renderer(&mut self) -> Option<Box<dyn photocraft_io::BandRenderer>> {
|
||||
self.renderer.take()
|
||||
}
|
||||
|
||||
/// Mutable reference to the active renderer if any.
|
||||
pub fn renderer_mut(&mut self) -> Option<&mut dyn photocraft_io::BandRenderer> {
|
||||
self.renderer.as_mut().map(|b| &mut **b as &mut dyn photocraft_io::BandRenderer)
|
||||
|
||||
@@ -322,6 +322,13 @@ pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
|
||||
// poisoned lock is safe to keep using, the same as the MCP server does.
|
||||
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, params)))
|
||||
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error: `{method}` panicked"))));
|
||||
// A renderer whose diagnostics panic must not lose the reply either.
|
||||
let diagnostics =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).drain_diagnostics())).unwrap_or_default();
|
||||
for diagnostic in diagnostics {
|
||||
// A broken stderr pipe must not panic the server before it writes the reply.
|
||||
let _ = writeln!(std::io::stderr(), "warning: {diagnostic}");
|
||||
}
|
||||
match r {
|
||||
Ok(v) => json!({"id": id, "ok": true, "result": v}),
|
||||
Err(e) => {
|
||||
|
||||
@@ -116,6 +116,36 @@ fn poisoned_session_keeps_serving() {
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
}
|
||||
|
||||
/// A renderer whose diagnostics panic must not cost the request its reply.
|
||||
#[test]
|
||||
fn a_panicking_renderer_diagnostic_drain_still_writes_the_reply() {
|
||||
struct PanickyDiagnostics;
|
||||
impl photocraft_io::BandRenderer for PanickyDiagnostics {
|
||||
fn render_bands(
|
||||
&mut self,
|
||||
_doc: &photocraft_doc::Document,
|
||||
_rect: photocraft_doc::Rect,
|
||||
_band_rows: i32,
|
||||
_ctl: &photocraft_raster::Interrupt<'_>,
|
||||
_sink: &mut dyn FnMut(photocraft_io::RenderBand) -> Result<(), photocraft_io::IoError>,
|
||||
) -> Result<(), photocraft_io::RenderError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn drain_diagnostics(&mut self) -> Vec<String> {
|
||||
panic!("diagnostics blew up");
|
||||
}
|
||||
}
|
||||
let h = session();
|
||||
h.lock().unwrap().set_renderer(Some(Box::new(PanickyDiagnostics)));
|
||||
let r = respond(&h, r#"{"id":7,"method":"doc.new","params":{"width":8,"height":8}}"#);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(r["id"], 7);
|
||||
// The session keeps serving afterwards.
|
||||
let r = respond(&h, r#"{"id":8,"method":"doc.new","params":{"width":8,"height":8}}"#);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_stops_on_error_unless_told_not_to() {
|
||||
let h = session();
|
||||
|
||||
@@ -579,8 +579,12 @@ impl PhotocraftMcp {
|
||||
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(Headless::new()))))
|
||||
}
|
||||
|
||||
pub fn with_headless(headless: Headless) -> Self {
|
||||
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(headless))))
|
||||
}
|
||||
|
||||
pub fn headless_with_workspace(workspace: AuthorizedWorkspace) -> Self {
|
||||
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(Headless::with_workspace(workspace)))))
|
||||
Self::with_headless(Headless::with_workspace(workspace))
|
||||
}
|
||||
|
||||
pub fn bridge(addr: &str, token: &str) -> Result<Self, AutomationError> {
|
||||
|
||||
@@ -56,6 +56,12 @@ fn native_save_refuses_previews_rendered_from_unreadable_scratch() {
|
||||
file.sync_all().unwrap();
|
||||
|
||||
let on = photocraft_io::ExportOptions { pcraft_full_composite: true, ..Default::default() };
|
||||
// A flat export refused after its provisional result (the unreadable tile is only noticed
|
||||
// while reading) keeps that result's renderer notes queued for the caller.
|
||||
let mut renderer = QueuedDiagnosticsRenderer(Vec::new());
|
||||
let err = photocraft_io::export_with_renderer(&doc, "png", &on, &Interrupt::NONE, Some(&mut renderer)).unwrap_err();
|
||||
assert!(matches!(err, IoError::Unsupported(_)), "{err:?}");
|
||||
assert!(renderer.0.iter().any(|d| d.contains("single-layer export copies")), "refused export must re-queue its notes: {:?}", renderer.0);
|
||||
// Refused while rendering the previews, before the bundle is assembled.
|
||||
let err = files::save_bytes(&doc, "Scratch.pcraft", None, &on).unwrap_err();
|
||||
assert!(matches!(err, AutomationError::Io(_)), "{err:?}");
|
||||
|
||||
+46
-13
@@ -704,6 +704,11 @@ pub fn document_to_image_with_renderer(doc: &Document, warnings: &mut Vec<String
|
||||
document_to_image_for_with_renderer(doc, warnings, true, false, &Interrupt::NONE, renderer)
|
||||
}
|
||||
|
||||
/// Reported in the export's own warnings (not through the renderer's diagnostics, which a custom
|
||||
/// renderer may ignore) when a single plain layer is copied natively although a renderer was given.
|
||||
const NATIVE_COPY_CPU_NOTICE: &str =
|
||||
"custom renderer unsupported: a single-layer export copies the document's own pixels with the CPU path; falling back to CPU";
|
||||
|
||||
fn document_to_image_for_with_renderer(
|
||||
doc: &Document,
|
||||
warnings: &mut Vec<String>,
|
||||
@@ -713,6 +718,9 @@ fn document_to_image_for_with_renderer(
|
||||
renderer: Option<&mut dyn BandRenderer>,
|
||||
) -> Result<Image, IoError> {
|
||||
let src = FlatSource::new(doc, warnings, cmyk_target, lab_target)?;
|
||||
if renderer.is_some() && src.native.is_some() {
|
||||
warnings.push(NATIVE_COPY_CPU_NOTICE.into());
|
||||
}
|
||||
let (w, h) = (doc.size.width, doc.size.height);
|
||||
// The single layer's alpha is dropped up front when it is opaque. A composite is rendered
|
||||
// with alpha, dropped afterwards, in place, when every pixel turned out opaque.
|
||||
@@ -767,8 +775,15 @@ pub fn export_preview_png_with_renderer(doc: &Document, renderer: Option<&mut dy
|
||||
// Keep the fallback reason in this export's warnings only. Move this attempt's
|
||||
// queued diagnostics into its retry result too: leaving either on the renderer
|
||||
// would leak them into a later successful GPU export. If the retry fails, `?`
|
||||
// returns early and they stay with the renderer for the caller.
|
||||
let mut cpu_result = export_preview_png_with_renderer(doc, None)?;
|
||||
// returns the CPU error and the fallback reason is queued on the renderer for the caller.
|
||||
let mut cpu_result = match export_preview_png_with_renderer(doc, None) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
// Keep the reason the CPU retry happened queued on the renderer, so the caller reports it next to the CPU error.
|
||||
r.push_diagnostic(fallback_warning);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
cpu_result.warnings.extend(r.drain_diagnostics());
|
||||
cpu_result.warnings.push(fallback_warning);
|
||||
return Ok(cpu_result);
|
||||
@@ -904,11 +919,6 @@ impl<'a> FlatSource<'a> {
|
||||
if let Some(s) = self.native {
|
||||
// Native path: keep model and depth. The surface's encoded samples are the codec's raw
|
||||
// native-endian samples, copied a band of rows at a time (alpha dropped when opaque).
|
||||
if let Some(r) = renderer.as_mut() {
|
||||
r.push_diagnostic(
|
||||
"custom renderer unsupported: a single-layer export copies the document's own pixels with the CPU path; falling back to CPU".into(),
|
||||
);
|
||||
}
|
||||
let ch = fmt.channels();
|
||||
let bps = fmt.sample.bytes();
|
||||
let keep = (ch - 1) * bps;
|
||||
@@ -1151,10 +1161,20 @@ pub fn export_flat_with_renderer(
|
||||
// Keep the fallback reason in this export's warnings only. Move this attempt's
|
||||
// queued diagnostics into its retry result too: leaving either on the renderer
|
||||
// would leak them into a later successful GPU export. If the retry fails, `?`
|
||||
// returns early and they stay with the renderer for the caller.
|
||||
// returns the CPU error and the fallback reason is queued on the renderer for the caller.
|
||||
// A cancelled export stops before compositing the document again.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut cpu_result = export_flat_with_renderer(doc, format, opts, ctl, None)?;
|
||||
if ctl.check().is_err() {
|
||||
r.push_diagnostic(fallback_warning);
|
||||
return Err(IoError::Cancelled);
|
||||
}
|
||||
let mut cpu_result = match export_flat_with_renderer(doc, format, opts, ctl, None) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
// Keep the reason the CPU retry happened queued on the renderer, so the caller reports it next to the CPU error.
|
||||
r.push_diagnostic(fallback_warning);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
cpu_result.warnings.extend(r.drain_diagnostics());
|
||||
cpu_result.warnings.push(fallback_warning);
|
||||
return Ok(cpu_result);
|
||||
@@ -1298,10 +1318,20 @@ pub fn export_png_streamed_with_renderer(
|
||||
// Keep the fallback reason in this export's warnings only. Move this attempt's
|
||||
// queued diagnostics into its retry result too: leaving either on the renderer
|
||||
// would leak them into a later successful GPU export. If the retry fails, `?`
|
||||
// returns early and they stay with the renderer for the caller.
|
||||
// returns the CPU error and the fallback reason is queued on the renderer for the caller.
|
||||
// A cancelled export stops before streaming the PNG again.
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
let mut cpu_result = export_png_streamed_with_renderer(doc, opts, ctl, rows, None)?;
|
||||
if ctl.check().is_err() {
|
||||
r.push_diagnostic(fallback_warning);
|
||||
return Err(IoError::Cancelled);
|
||||
}
|
||||
let mut cpu_result = match export_png_streamed_with_renderer(doc, opts, ctl, rows, None) {
|
||||
Ok(res) => res,
|
||||
Err(e) => {
|
||||
// Keep the reason the CPU retry happened queued on the renderer, so the caller reports it next to the CPU error.
|
||||
r.push_diagnostic(fallback_warning);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
cpu_result.warnings.extend(r.drain_diagnostics());
|
||||
cpu_result.warnings.push(fallback_warning);
|
||||
return Ok(cpu_result);
|
||||
@@ -1357,6 +1387,9 @@ fn stream_png_with_renderer(
|
||||
let cmyk_target = format.caps().layouts.iter().any(|layout| layout.is_cmyk());
|
||||
let lab_target = format.caps().layouts.iter().any(|layout| layout.is_lab());
|
||||
let src = FlatSource { rows, ..FlatSource::new(doc, &mut warnings, cmyk_target, lab_target)? };
|
||||
if renderer.is_some() && src.native.is_some() {
|
||||
warnings.push(NATIVE_COPY_CPU_NOTICE.into());
|
||||
}
|
||||
let mut encode = opts.encode.clone();
|
||||
let mut late = Vec::new();
|
||||
if encode.png_interlaced {
|
||||
|
||||
+17
-3
@@ -967,9 +967,23 @@ fn checked_stages(
|
||||
photocraft_compose::discard_unreadable_pixel_caches();
|
||||
doc.scratch_health().map_err(IoError::Unsupported)?;
|
||||
let scratch_generation = photocraft_raster::spill::read_error_generation();
|
||||
let r = export_stages_with_renderer(doc, name_or_ext, opts, ctl, renderer)?;
|
||||
photocraft_raster::spill::check_since(scratch_generation).map_err(IoError::Unsupported)?;
|
||||
doc.scratch_health().map_err(IoError::Unsupported)?;
|
||||
let mut renderer = renderer;
|
||||
// `as_deref_mut` would tie the trait object's lifetime to this function's; the closure shortens it.
|
||||
#[allow(clippy::option_as_ref_deref)]
|
||||
let r = export_stages_with_renderer(doc, name_or_ext, opts, ctl, renderer.as_mut().map(|r| -> &mut dyn BandRenderer { &mut **r }))?;
|
||||
if let Err(e) = photocraft_raster::spill::check_since(scratch_generation)
|
||||
.map_err(IoError::Unsupported)
|
||||
.and_then(|()| doc.scratch_health().map_err(IoError::Unsupported))
|
||||
{
|
||||
// The provisional result is discarded: queue its renderer notes (fallback reasons, CPU-only
|
||||
// formats) back on the renderer so the caller can still report them next to the error.
|
||||
if let Some(renderer) = renderer {
|
||||
for w in r.warnings.iter().filter(|w| w.starts_with("custom renderer") || w.contains("CPU compositor")) {
|
||||
renderer.push_diagnostic(w.clone());
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
ctl.check().map_err(|_| IoError::Cancelled)?;
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
@@ -26,6 +26,8 @@ fn synthetic_doc() -> Document {
|
||||
#[derive(Default)]
|
||||
struct RecordingRenderer {
|
||||
diagnostics: Vec<String>,
|
||||
/// How many times `render_bands` was called.
|
||||
renders: usize,
|
||||
}
|
||||
|
||||
impl BandRenderer for RecordingRenderer {
|
||||
@@ -37,6 +39,7 @@ impl BandRenderer for RecordingRenderer {
|
||||
ctl: &Interrupt<'_>,
|
||||
sink: &mut dyn FnMut(RenderBand) -> Result<(), IoError>,
|
||||
) -> Result<(), RenderError> {
|
||||
self.renders += 1;
|
||||
let mut cpu = CpuRenderer;
|
||||
cpu.render_bands(doc, rect, band_rows, ctl, sink)
|
||||
}
|
||||
@@ -132,11 +135,8 @@ fn single_layer_and_cmyk_exports_report_that_the_renderer_was_not_used() {
|
||||
let mut renderer = RecordingRenderer::default();
|
||||
let mut warnings = Vec::new();
|
||||
document_to_image_with_renderer(&single, &mut warnings, Some(&mut renderer)).expect("single-layer export");
|
||||
let diagnostics = renderer.drain_diagnostics();
|
||||
assert!(
|
||||
diagnostics.iter().any(|d| d.contains("single-layer") && d.contains("CPU")),
|
||||
"a requested renderer that is bypassed must report why: {diagnostics:?}"
|
||||
);
|
||||
assert!(warnings.iter().any(|d| d.contains("single-layer") && d.contains("CPU")), "a requested renderer that is bypassed must report why: {warnings:?}");
|
||||
assert_eq!(renderer.renders, 0, "the native copy never calls the renderer");
|
||||
|
||||
// A CMYK composite mixed on ink values likewise returns before the renderer branch.
|
||||
let mut cmyk = Document::with_background("cmyk", Size::new(32, 32), ColorMode::Cmyk, SampleType::U8, Color::WHITE);
|
||||
@@ -303,8 +303,9 @@ fn renderer_preview_is_8bit_rgba_while_saved_export_keeps_depth() {
|
||||
s.fill_rect(Rect::new(8, 8, 56, 40), &[0.2, 0.4, 0.8, 0.5]);
|
||||
doc.layers.push(Layer::new("top", LayerContent::Raster(s)));
|
||||
|
||||
let mut preview_renderer = CpuRenderer;
|
||||
let mut preview_renderer = RecordingRenderer::default();
|
||||
let preview = export_preview_png_with_renderer(&doc, Some(&mut preview_renderer)).expect("preview export");
|
||||
assert!(preview_renderer.renders > 0, "the preview must render through the supplied renderer");
|
||||
let img = photocraft_codecs::decode(&preview.bytes).expect("decode preview");
|
||||
assert_eq!((img.width(), img.height()), (64, 48));
|
||||
assert_eq!(img.layout(), photocraft_codecs::ChannelLayout::Rgba, "a preview is always RGBA");
|
||||
@@ -437,3 +438,67 @@ fn unknown_export_format_is_rejected() {
|
||||
let export_err = photocraft_io::export(&doc, "invalid_unknown_extension_xyz", &opts);
|
||||
assert!(export_err.is_err());
|
||||
}
|
||||
|
||||
/// A renderer that fails retryably on its first call and, as it does, requests cancellation, so
|
||||
/// the complete CPU retry that follows cannot succeed. It queues pushed diagnostics for the test.
|
||||
struct FailThenCancelRenderer {
|
||||
cancel: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||
diagnostics: Vec<String>,
|
||||
}
|
||||
|
||||
impl BandRenderer for FailThenCancelRenderer {
|
||||
fn render_bands(
|
||||
&mut self,
|
||||
_doc: &Document,
|
||||
_rect: Rect,
|
||||
_band_rows: i32,
|
||||
_ctl: &Interrupt<'_>,
|
||||
_sink: &mut dyn FnMut(RenderBand) -> Result<(), IoError>,
|
||||
) -> Result<(), RenderError> {
|
||||
self.cancel.store(true, Ordering::SeqCst);
|
||||
Err(RenderError::Device("forced device loss".into()))
|
||||
}
|
||||
|
||||
fn drain_diagnostics(&mut self) -> Vec<String> {
|
||||
std::mem::take(&mut self.diagnostics)
|
||||
}
|
||||
|
||||
fn push_diagnostic(&mut self, diagnostic: String) {
|
||||
self.diagnostics.push(diagnostic);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_cpu_retry_keeps_the_fallback_reason_on_the_renderer() {
|
||||
let doc = synthetic_doc();
|
||||
let opts = ExportOptions::default();
|
||||
for streamed in [false, true] {
|
||||
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let seen = flag.clone();
|
||||
let cancel = move || seen.load(Ordering::SeqCst);
|
||||
let ctl = Interrupt::cancel_only(&cancel);
|
||||
let mut renderer = FailThenCancelRenderer { cancel: flag, diagnostics: Vec::new() };
|
||||
let res = if streamed {
|
||||
export_png_streamed_with_renderer(&doc, &opts, &ctl, 0, Some(&mut renderer))
|
||||
} else {
|
||||
export_flat_with_renderer(&doc, Format::Png, &opts, &ctl, Some(&mut renderer))
|
||||
};
|
||||
assert!(matches!(res, Err(IoError::Cancelled)), "the CPU retry is cancelled (streamed: {streamed}): {res:?}");
|
||||
let diagnostics = renderer.drain_diagnostics();
|
||||
assert!(
|
||||
diagnostics.iter().any(|d| d.contains("custom renderer unavailable") && d.contains("falling back to CPU")),
|
||||
"the fallback reason must survive the failed retry (streamed: {streamed}): {diagnostics:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_layer_notice_reaches_the_export_warnings_without_renderer_diagnostics() {
|
||||
// `FailingRenderer` keeps the default no-op `push_diagnostic`, like any renderer that ignores it.
|
||||
let single = Document::with_background("single", Size::new(24, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
let mut renderer = FailingRenderer::new(usize::MAX, "device");
|
||||
let res = export_flat_with_renderer(&single, Format::Png, &ExportOptions::default(), &Interrupt::NONE, Some(&mut renderer)).expect("single-layer export");
|
||||
assert!(res.warnings.iter().any(|w| w.contains("single-layer") && w.contains("CPU")), "{:?}", res.warnings);
|
||||
let res = export_png_streamed_with_renderer(&single, &ExportOptions::default(), &Interrupt::NONE, 0, Some(&mut renderer)).expect("streamed single layer");
|
||||
assert!(res.warnings.iter().any(|w| w.contains("single-layer") && w.contains("CPU")), "{:?}", res.warnings);
|
||||
}
|
||||
@@ -358,8 +358,8 @@ magenta alignment lines. `ui.pointer` drives the same code, so agents get identi
|
||||
|
||||
`photocraft-automation` provides an MCP server built on the official Rust SDK (`rmcp`). It runs in one of two modes:
|
||||
|
||||
- **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window.
|
||||
- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <path>`): every tool is forwarded to a running `photocraft --control 7878 --control-token-file <path>` over this protocol, so agents see and drive the live app. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:<port>`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots.
|
||||
- **Headless** (`photocraft-cli mcp`): an in-process `photocraft_engine::Session`. There is no window. CPU composition is the default; `--gpu` or `PHOTOCRAFT_GPU=1` enables optional GPU rendering with automatic CPU fallback.
|
||||
- **Bridge** (`photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <path>`): every tool is forwarded to a running `photocraft --control 7878 --control-token-file <path>` over this protocol, so agents see and drive the live app. Explicit `--gpu` / `--no-gpu` flags are rejected with a usage error because the desktop controls rendering; `PHOTOCRAFT_GPU` is ignored in bridge mode. `--bridge 7878` is short for `--bridge 127.0.0.1:7878`. With no `--bridge`, `PHOTOCRAFT_CONTROL_PORT` selects the bridge port (`127.0.0.1:<port>`), and the CLI says so on standard error; with neither (or the variable empty), the MCP runs headless. A value that is not a port is a usage error naming the variable. `--automation-read-root` or `--automation-write-root` with the variable set is a usage error, since the bridge would drop the roots.
|
||||
|
||||
The bridge keeps one authenticated TCP connection open, and drops and reconnects before a call once the connection has been idle long enough that the app (which closes idle connections after 30s) may have dropped it. A transport failure while sending a request or waiting for its reply, including a reply timeout, drops the connection and reports that the operation may have completed; inspect the document before retrying an edit. Edits are never automatically resent (#1007); a connection that could not be established is reported as "the request was not sent" instead. The MCP server opts its pure-read tools (`ui_inspect`, `doc_inspect`, `command_list`, `jobs_list`, `session_list`, `ui_screenshot`) into one automatic retry on a fresh connection, since a read applies nothing; clients driving `BridgeClient` directly opt in per call with `call_read`. The next separate call reconnects and authenticates, and reply lines whose `id` does not match the request are skipped. The client's call timeout is 55s, strictly below the server's 60s reply deadline, so the bridge's error is the one callers see; commands that can run longer should pass `"wait": false` and poll `jobs.list`. It only accepts loopback addresses, because the app only listens on loopback. Supply its bearer token with `--control-token-file`, `--control-token`, `PHOTOCRAFT_CONTROL_TOKEN_FILE`, or `PHOTOCRAFT_CONTROL_TOKEN`:
|
||||
|
||||
@@ -425,7 +425,7 @@ its listening port so a later session can reuse it (#3682). An active connection
|
||||
idle shutdown, including during a long command. Clients should reconnect by restarting
|
||||
`photocraft-cli serve` if they need a server after the idle deadline.
|
||||
|
||||
`photocraft-cli serve` keeps one headless engine session (no window, no GPU) and answers the same
|
||||
`photocraft-cli serve` keeps one headless engine session (no window; CPU by default, optional GPU acceleration via `--gpu` or `PHOTOCRAFT_GPU=1`) and answers the same
|
||||
JSON-lines envelope on stdio, or on `127.0.0.1:<port>` with `--port <port>` or, without the flag,
|
||||
`PHOTOCRAFT_CONTROL_PORT` (loopback only; each
|
||||
authenticated connection shares the session). TCP uses the same first-frame `auth` exchange and
|
||||
|
||||
@@ -169,6 +169,7 @@ By default PhotoCraft's own crates log at `info` and everything else at `warn`.
|
||||
|
||||
| Variable | Effect |
|
||||
|---|---|
|
||||
| `PHOTOCRAFT_GPU=1` (or `=0`) | Headless CLI: prefer GPU composition and flat export (0 to disable, empty to unset). Explicit `--gpu`/`--no-gpu` CLI flags override this variable. `file.export.quickExport` composites and encodes inside the engine, which has no renderer, so it always runs on the CPU; `run --gpu` prints a one-time warning when a step uses it |
|
||||
| `PHOTOCRAFT_CONTROL_PORT` | Same as `--control <port>`; also the port for `photocraft-cli serve --port` and `mcp --bridge` when the flag is absent. Empty is unset |
|
||||
| `PHOTOCRAFT_NO_PRINT` | Set to anything but `0`: `file.print` / `file.printOneCopy` refuse to spool (`dryRun` still works). CI sets it, with `LPDEST=photocraft-no-such-printer` as a second net; set both when running the panic hunt or fuzzers locally |
|
||||
| `RUST_LOG` | Log levels for standard error and the log file (see [Logs](#logs)) |
|
||||
@@ -268,6 +269,17 @@ ln -s photocraft-<version>-linux-x86_64.AppImage photocraft-cli
|
||||
|
||||
The `--cli` selector is removed; all remaining arguments, stdin, stdout, stderr and the exit status are passed through. CLI launches skip desktop integration. The symlink form uses the AppImage runtime's `ARGV0`; the normal AppImage name launches the GUI.
|
||||
|
||||
### GPU rendering
|
||||
|
||||
PhotoCraft CLI supports optional native GPU acceleration for flat exports and composition in `convert`, `run`, `batch`, `serve`, and headless `mcp`:
|
||||
|
||||
- `--gpu`: Opt into GPU acceleration. Prefers a hardware adapter, performs bounded multi-band readback, and automatically falls back to CPU if an unsupported document feature (such as unsupported blend modes or layered saves) is encountered or if the GPU device becomes unavailable.
|
||||
- `--no-gpu`: Explicitly disable GPU rendering and use CPU composition (the default).
|
||||
- `PHOTOCRAFT_GPU`: Environment variable equivalent when neither flag is supplied (`1` enables GPU, `0` disables it). An empty or whitespace-only value is treated as unset (defaulting to CPU). Any other value is rejected with a usage error naming the variable. Explicit `--gpu` or `--no-gpu` flags always override the environment variable.
|
||||
- **Backend scope and limitations**: GPU acceleration applies to flat exports (e.g. PNG, JPEG, WebP, flat TIFF). Layered/native saves (`.pcraft`, PSD, TIFF with layers) and embedded thumbnail generation remain CPU operations.
|
||||
- **Diagnostics and protocol safety**: GPU initialization status, adapter information, and deduplicated fallback warnings are written to standard error. Standard output (JSON lines in `run`, MCP protocol frames, etc.) is never polluted with diagnostics.
|
||||
- **Bridge MCP**: When `photocraft-cli mcp` is bridged to a running desktop app (`--bridge`), explicit `--gpu` / `--no-gpu` flags are rejected because the desktop process controls rendering. `PHOTOCRAFT_GPU` is ignored in bridge mode to prevent ambient environment variables from disrupting live bridges.
|
||||
|
||||
`actions.json` holds the steps of a recorded action: `[["<id>", {…}], …]`, `[{"command": "<id>", "params": {…}}, …]` or bare ids, as a list or wrapped in `{"actions": …}` or `{"steps": …}`; a droplet file works too. It can also be an Actions set (the Actions panel's `actions.json`, `{"actions": [{"name": …, "steps": […]}, …]}`): `--action <name>` picks the action to play (optional when the set holds one), and the whole set is loaded for each file, so a step that plays another action of the set works. `batch` refuses an `--out` folder that is the `--in` folder, since the results would replace the originals, unless `--in-place` is given. `run` prints one JSON line per command result.
|
||||
|
||||
## Native format (.pcraft)
|
||||
|
||||
Reference in new issue
Block a user