Compare commits

...

100 Commits

Author SHA1 Message Date
Dandaedre c8dbf21e83 docs: disclose open-source and LLM-assisted development
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-20 16:47:47 +01:00
Dandaedre cfbcfb0883 Add forced whole-pixel snapping
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 15:52:26 +01:00
Dandaedre a15bf92d7f Remove inspector clipboard buttons 2026-11-19 15:34:54 +01:00
Dandaedre 3a0592d093 Infer geometry import scope from matching layer counts 2026-11-19 15:31:26 +01:00
Dandaedre 423d3fb99d Keep alignment target menu usable 2026-11-19 15:26:54 +01:00
Dandaedre 1b4f7377e9 Place size presets before toolbar options 2026-11-19 15:20:13 +01:00
Dandaedre ec656f85cd Toggle layer properties from resolution row 2026-11-19 15:15:24 +01:00
Dandaedre 9940efd0ac Tighten selected layer inspector spacing 2026-11-19 15:09:11 +01:00
Dandaedre a42c4e93f6 Store resize aspect lock per layer 2026-11-19 15:05:52 +01:00
Dandaedre 97df9bd164 Remove empty inspector scroll range 2026-11-19 14:53:40 +01:00
Dandaedre d55a105a92 Record v0.10.0-rc.18 publication
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 12:29:56 +01:00
Dandaedre 171a9198b6 Prepare v0.10.0-rc.18 release
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 11:51:40 +01:00
Dandaedre c2ae6fc256 Prefer whole pixels during canvas edits 2026-11-19 11:42:20 +01:00
Dandaedre 3cdd303b45 Keep extreme canvas zoom responsive 2026-11-19 11:31:50 +01:00
Dandaedre e228cc82bb Record v0.10.0-rc.16 publication
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 09:41:41 +01:00
Dandaedre 72dc29837a Prepare v0.10.0-rc.16 release notes
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 08:56:13 +01:00
Dandaedre 59ba4a63de Keep crop conversion menu labels on one line 2026-11-19 08:44:35 +01:00
Dandaedre 0c438ebbca Add inverse conversion from smart to edge crop 2026-11-19 08:38:50 +01:00
Dandaedre a872be4766 Request a fresh still when enabling an input preview 2026-11-19 08:32:22 +01:00
Dandaedre cbbcde2a92 Normalize rounded Midra fits to exact smart crop on import 2026-11-19 08:25:32 +01:00
Dandaedre 7daf2d18e8 Normalize exact device fits and add deferred advanced edge cropping 2026-11-19 08:12:11 +01:00
Dandaedre 46ace1fe25 Open crop properties from shortcuts for automatic fit layers 2026-11-19 07:58:25 +01:00
Dandaedre 6f777f7455 Review partial transfers and resolution conversions; log geometry discrepancies
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-19 07:41:51 +01:00
Dandaedre fa0c7722bc Improve bounded send verification recovery and device address handling 2026-11-19 07:02:32 +01:00
Dandaedre 6cc89e405e Adapt processed input geometry when enabling Follow input
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 19:39:08 +01:00
Dandaedre 73bd3ca03d Suppress stale preview warnings during followed input transitions
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 19:34:30 +01:00
Dandaedre 168f66b6b2 Identify alternate preview inputs with color-coded picture warnings 2026-11-18 19:28:48 +01:00
Dandaedre b1c8a72af9 Show preview mismatch warnings beside input controls
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 19:23:48 +01:00
Dandaedre 36f841abe5 Default previews to follow input and warn about mismatched ratios 2026-11-18 19:10:27 +01:00
Dandaedre 5a574686a3 Support switching to cropped Midra inputs 2026-11-18 19:00:45 +01:00
Dandaedre 99260367ac Fix capture GUI test timing races with a controlled clock 2026-11-18 18:34:43 +01:00
Dandaedre f7294e8d02 Paste proportional crops using the destination layer fit
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 18:26:47 +01:00
Dandaedre df36648397 Adapt layer framing when switching input resolutions 2026-11-18 18:18:29 +01:00
Dandaedre ef8fcf90e8 Read Midra crop controls when validating input switches
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 18:06:52 +01:00
Dandaedre 28f5709b94 Stabilize input picker rows with background hover feedback 2026-11-18 17:50:28 +01:00
Dandaedre eb1f7e856b Tighten input reference picture row spacing 2026-11-18 17:44:44 +01:00
Dandaedre b4e17e7844 Prepare 0.10.0 release candidate 1 2026-11-18 17:34:07 +01:00
Dandaedre b6c4afb511 Preserve cropped input picture aspect before layer fitting 2026-11-18 17:20:37 +01:00
Dandaedre ee0b67c6d7 Highlight pending input changes and allow protected view navigation 2026-11-18 17:13:38 +01:00
Dandaedre 79beaa8392 Reorganize input settings around crop preview and focused categories 2026-11-18 16:46:53 +01:00
Dandaedre 57cd9c7d80 Allow cancelling draft-close confirmations without losing edits 2026-11-18 16:38:36 +01:00
Dandaedre 0a13642c8f Handle Midra cropped input snapshots in the crop editor 2026-11-18 16:31:37 +01:00
Dandaedre 9f5a8d737d Add local reference pictures for layer crop previews
Gitea/canvas-pilot/pipeline/head There was a failure building this commit Details
2026-11-18 16:21:36 +01:00
Dandaedre 709fdcbb59 Fix clipboard text detection and embedded format fallback
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 16:13:34 +01:00
Dandaedre 4ab2a2e855 Allow Enter to open crop editing for the selected layer 2026-11-18 16:05:07 +01:00
Dandaedre 6f5c24ed6b Move input send controls above editor and preserve capture brightness 2026-11-18 15:59:41 +01:00
Dandaedre 7e80311797 Protect input categories by default and refine crop zoom
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-18 15:52:41 +01:00
Dandaedre f954551711 Resume saved automatic previews when reopening projects 2026-11-18 15:46:57 +01:00
Dandaedre 4b411aa020 Add per-destination send options to mapping mockup 2026-11-18 15:41:13 +01:00
Dandaedre b686cdb3ea Add opt-in input routing on Send and preview following 2026-11-18 15:39:56 +01:00
Dandaedre 637a4e4e17 Offer explicit resolution choices for device state conflicts 2026-11-18 15:27:59 +01:00
Dandaedre 52f39d58cb Refresh device state after rejected sends without disconnecting 2026-11-18 15:18:53 +01:00
Dandaedre dc4ba98e88 Simplify shared input settings to direct sending 2026-11-18 15:12:44 +01:00
Dandaedre f66105cb81 Pool live input captures and anchor previews to device crop 2026-11-18 15:06:37 +01:00
Dandaedre b3845ef1c6 Add per-category protection for device input settings 2026-11-18 14:57:57 +01:00
Dandaedre 9ac81b7a36 Polish input crop handles zoom slider and option labels 2026-11-18 14:50:43 +01:00
Dandaedre e8341d5395 Remove legacy input crops and recover partial project loads 2026-11-18 14:42:06 +01:00
Dandaedre b5b2d3638c Remove legacy input controls and layer-send staging 2026-11-18 14:22:21 +01:00
Dandaedre c41d40e184 Add shared device input editor with verified Aquilon capture fallback 2026-11-18 14:16:34 +01:00
Dandaedre 61ff1284ac Record shared input refactor requirements and capture investigation 2026-11-18 13:46:25 +01:00
Dandaedre b71123904c Restore uncropped bounds when choosing crop ratio presets 2026-11-18 13:44:01 +01:00
Dandaedre 1d47b24ab7 Document ATEM SuperSource and vMix adapter feasibility 2026-11-18 13:26:23 +01:00
Dandaedre 5ad1bcfccb Update accepted stretch goal statuses 2026-11-18 13:18:28 +01:00
Dandaedre e0da8f6ea1 Add standalone mapping window visual study 2026-11-18 13:17:33 +01:00
Dandaedre e0e9c8d969 Plan GUI controls for directional device mappings 2026-11-18 13:11:53 +01:00
Dandaedre 3f299b1d5f Separate load mappings from extensible send destinations 2026-11-18 13:11:09 +01:00
Dandaedre f27baa3f41 Fix clipped layer header icons 2026-11-18 11:59:28 +01:00
Dandaedre 13796190cf
Detect optional software at startup and expose integration capabilities
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 21:24:56 +01:00
Dandaedre ba63d4cf52
Add PDF and document artwork imports as reference pictures 2026-11-17 19:35:26 +01:00
Dandaedre dfbfc89945
Split bundled palettes into video-game and classic theme packs 2026-11-17 19:14:42 +01:00
Dandaedre b20e88e917
Prepare a polished conference showcase kit with editable and raster handoffs 2026-11-17 18:56:17 +01:00
Dandaedre 9bbb19c9e3
Add Ravenswatch theme with ivory and crimson accents 2026-11-17 18:43:12 +01:00
Dandaedre 1f31d0d409
Replace Minecraft theme with Vivid World 2026-11-17 18:39:40 +01:00
Dandaedre 1141cf102a
Retune Deep Rock Galactic with gold and molten-orange accents 2026-11-17 18:36:46 +01:00
Dandaedre 91e7539b7b
Retune Dispatch theme with yellow and cyan accents 2026-11-17 18:35:50 +01:00
Dandaedre fb6ff02d5a
Compact theme and language choices by removing secondary labels 2026-11-17 18:34:40 +01:00
Dandaedre 6fe9b83391
Keep covered editing guides dashed and handles visible
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 18:32:18 +01:00
Dandaedre af93ba4579
Group size presets and add proportional placement 2026-11-17 18:27:06 +01:00
Dandaedre f12df5897b
Make theme pack archives reproducible across build hosts
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 17:45:11 +01:00
Dandaedre bc2844c931
Bundle sixteen themes in one importable extra-themes pack
Gitea/canvas-pilot/pipeline/head There was a failure building this commit Details
2026-11-17 16:53:25 +01:00
Dandaedre 3d40d9c05e
Replace expanding pack managers with compact searchable browsers 2026-11-17 16:34:24 +01:00
Dandaedre 0f232ac4e8
Record verified v0.9.34 publication and pack downloads
Gitea/canvas-pilot/pipeline/head There was a failure building this commit Details
2026-11-17 16:18:15 +01:00
Dandaedre 952f409e52
Prepare v0.9.34 release notes and changelog
Gitea/canvas-pilot/pipeline/head There was a failure building this commit Details
2026-11-17 16:11:14 +01:00
Dandaedre 6594de9bb4
Make layer-border snapping independently disable moving border anchors 2026-11-17 16:09:10 +01:00
Dandaedre e7caaf806e
Keep mapping and import scrollbars visible when content overflows 2026-11-17 16:04:29 +01:00
Dandaedre 108c0a98a0
Make dragging layers out of folders more forgiving 2026-11-17 15:48:07 +01:00
Dandaedre 88e00c94d3
Snap to visible masked-area centers during layer editing 2026-11-17 15:08:55 +01:00
Dandaedre fa2ee8e957
Pair toolbar import and export with inward and outward arrow icons 2026-11-17 15:05:19 +01:00
Dandaedre 86762435cd
Add crop ratio presets for embedded presentation borders 2026-11-17 15:00:37 +01:00
Dandaedre 328bb722ff
Add size preset icon box for single and multiple layers 2026-11-17 14:55:04 +01:00
Dandaedre c54a3fd4aa
Finish crop and mask editing with Enter 2026-11-17 14:39:01 +01:00
Dandaedre 31e545a426
Add installable theme packs and four example palettes 2026-11-17 14:33:17 +01:00
Dandaedre 2b988f9c84
Prevent Load from collapsing the device transfer window
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 14:18:23 +01:00
Dandaedre 70553daff3
Group language pack contents under collapsible headings 2026-11-17 14:13:29 +01:00
Dandaedre b922531337
Restore previous theme when reselecting High Contrast 2026-11-17 14:11:09 +01:00
Dandaedre f57a301de8
Fix High Contrast coordinate labels on white helper tiles 2026-11-17 14:08:48 +01:00
Dandaedre 8c3ab04bf4
Keep theme picker open while previewing themes
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 14:06:05 +01:00
Dandaedre a1425f78c6
Improve layer folder drops and add quick creation and ordering controls 2026-11-17 14:03:54 +01:00
Dandaedre 025128b36b
Support Aquilon rectangular masks with verified RS1 round trips
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 13:46:31 +01:00
Dandaedre 65588cf765
Record v0.9.18 publication and language pack downloads
Gitea/canvas-pilot/pipeline/head This commit looks good Details
2026-11-17 12:46:33 +01:00
175 changed files with 20452 additions and 2749 deletions

1
.gitignore vendored
View File

@ -12,3 +12,4 @@ __pycache__/
# Local showcase recordings, profiles and generated exchange files.
/showcase-videos/
/showcase-conference-kit/

View File

@ -25,6 +25,7 @@ Versioned examples and sanitized fixtures remain beside their contracts and in
| --- | --- |
| [Project](docs/interfaces/canvas-pilot.md) | Project schema, versions and migrations |
| [Settings](docs/interfaces/canvas-pilot-settings.md) | User preferences and settings compatibility |
| [Theme packs](docs/interfaces/theme-packs.md) | Runtime palette ZIPs, installation, updates and fallback |
| [Language packs](docs/interfaces/language-packs.md) | Runtime ZIP catalogs, installation and fallback |
| [Recovery](docs/interfaces/canvas-pilot-recovery.md) | Recovery storage and restoration |
| [Layer clipboard](docs/interfaces/canvas-pilot-clipboard.md) | Versioned geometry, crop, fit and blanking payload |

745
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@ default-members = ["crates/canvas-pilot"]
resolver = "3"
[workspace.package]
version = "0.9.18"
version = "0.10.10"
edition = "2024"
license = "MIT"
repository = "https://proxy.dandaedre.com/gitea/idle-org/canvas-pilot"

View File

@ -32,6 +32,13 @@ You can use the editor and file exchange without any connected equipment.
*Slides + Presenter on a Full HD canvas. Screenshots predate the Canvas Pilot
rename and still show the former “Midra Layout” name.*
## Open source and development
Canvas Pilot is open-source software under the [MIT license](LICENSE). Its
development includes LLM-generated or LLM-assisted work, with human review.
It is used in professional settings; supported workflows and current
limitations are documented in this repository.
## From an idea to a screen layout
1. **Set the stage.** Choose a canvas size or import geometry. Add a reference

View File

@ -13,7 +13,7 @@ bin-dir = "{ name }-{ target }-v{ version }/{ bin }{ binary-ext }"
[features]
default = ["vendor_formats"]
vendor_formats = ["dep:craft-dwg", "dep:deckcraft-pptx", "dep:deckcraft-model", "dep:deckcraft-geom", "dep:figcraft-format", "dep:figcraft-doc", "dep:figcraft-geom"]
vendor_formats = ["dep:craft-dwg", "dep:deckcraft-pptx", "dep:deckcraft-model", "dep:deckcraft-geom", "dep:figcraft-format", "dep:figcraft-doc", "dep:figcraft-geom", "dep:figcraft-svg"]
# Use with --no-default-features to exclude the optional codecs and their dependencies.
no_proprietary = []
@ -40,9 +40,13 @@ base64 = "0.22"
flate2 = "1"
csv = "1.4"
tempfile = "3"
url = "2"
directories = "6"
reqwest = { version = "0.12.28", default-features = false, features = ["blocking"] }
tungstenite = { version = "0.28", default-features = false, features = ["handshake"] }
hayro = "0.9"
resvg = "0.50"
figcraft-svg = { version = "=0.5.1", optional = true }
[build-dependencies]
winresource = "0.1.17"

View File

@ -3,10 +3,14 @@ use canvas_pilot::{
Geometry, Layout,
device::{self, Profile},
device_send::{self, Plan, Sizing, Target},
formats::Framing,
formats::{Framing, Mask, MaskOrigin},
};
use serde_json::{Value, json};
use std::{net::TcpStream, time::Duration};
use std::{
io::{Read, Write},
net::TcpStream,
time::Duration,
};
fn write(host: &str, changes: &[(String, Value)]) -> Result<(), String> {
let address = device::address(host)?;
let stream =
@ -30,17 +34,53 @@ fn write(host: &str, changes: &[(String, Value)]) -> Result<(), String> {
}
fn main() -> Result<(), String> {
let args: Vec<_> = std::env::args().collect();
if args.len() != 3
if !(3..=4).contains(&args.len())
|| args
.get(3)
.is_some_and(|scope| !matches!(scope.as_str(), "preview" | "program"))
|| !matches!(
args[1].as_str(),
"--apply-and-restore" | "--visual-check-and-restore"
)
{
return Err("Usage: check_aquilon_send --apply-and-restore|--visual-check-and-restore IP:PORT (temporarily routes S1 layer 1 to LIVE_1 in both banks)".into());
return Err("Usage: check_aquilon_send --apply-and-restore|--visual-check-and-restore IP:PORT [preview|program] (temporarily routes S1 layer 1 to LIVE_1 in selected banks; default both)".into());
}
let visual = args[1] == "--visual-check-and-restore";
let host = &args[2];
let targets: &[Target] = match args.get(3).map(String::as_str) {
Some("program") if visual => return Err("Visual check uses Preview only".into()),
Some("program") => &[Target::Program],
Some("preview") => &[Target::Preview],
_ if visual => &[Target::Preview],
_ => &[Target::Preview, Target::Program],
};
let baseline = device::fetch(host)?;
println!("Connected: {}", baseline.identity);
let client = reqwest::blocking::Client::builder()
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.timeout(Duration::from_secs(5))
.build()
.map_err(|e| e.to_string())?;
let mut bytes = Vec::new();
client
.get(format!(
"http://{}/api/tpp/v1/system",
device::address(host)?
))
.send()
.and_then(|r| r.error_for_status())
.map_err(|e| e.to_string())?
.take(4097)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 4096 {
return Err("Oversized identity".into());
}
let identity: Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;
if device::Snapshot::parse(&identity, &baseline.raw)?.identity != baseline.identity {
return Err("Identity changed before diagnostic".into());
}
if baseline.profile != Profile::Aquilon6 {
return Err("Expected Aquilon 6.2 emulator".into());
}
@ -52,7 +92,11 @@ fn main() -> Result<(), String> {
let s = &baseline.screens[screen];
let mut restore = vec![];
let mut setup = vec![];
for bank in [&s.preview_bank, &s.program_bank] {
for target in targets {
let bank = match target {
Target::Preview => &s.preview_bank,
Target::Program => &s.program_bank,
};
let base = baseline.profile.layer_path("S1", bank, "1");
for suffix in [
"source/pp/inputNum",
@ -65,6 +109,10 @@ fn main() -> Result<(), String> {
"cropping/classic/pp/right",
"cropping/classic/pp/top",
"cropping/classic/pp/bottom",
"cropping/mask/pp/left",
"cropping/mask/pp/right",
"cropping/mask/pp/top",
"cropping/mask/pp/bottom",
] {
let path = format!("{base}/{suffix}");
restore.push((
@ -78,15 +126,35 @@ fn main() -> Result<(), String> {
}
setup.push((format!("{base}/source/pp/inputNum"), json!("LIVE_1")));
}
// Keep a recovery record before the first write, including on interruption.
let backup_path = std::env::temp_dir().join(format!(
"canvas-pilot-aquilon-{}-{}.json",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|e| e.to_string())?
.as_millis()
));
let mut backup = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&backup_path)
.map_err(|e| e.to_string())?;
backup
.write_all(
serde_json::to_string_pretty(
&json!({"identity":identity,"host":host,"fields":restore}),
)
.map_err(|e| e.to_string())?
.as_bytes(),
)
.map_err(|e| e.to_string())?;
backup.sync_all().map_err(|e| e.to_string())?;
println!("Recovery baseline: {}", backup_path.display());
let result = (|| {
write(host, &setup)?;
let mut layout = Layout::default();
layout.set_output(s.resolution)?;
let targets: &[Target] = if visual {
&[Target::Preview]
} else {
&[Target::Preview, Target::Program]
};
for &target in targets {
let strategies: &[Sizing] = if visual {
&[Sizing::OutputBox]
@ -109,59 +177,128 @@ fn main() -> Result<(), String> {
},
)?;
layout.set_framing(0, Framing { zoom, offset })?;
let current = device::fetch(host)?;
let plan = Plan::prepare(
&current,
&layout,
screen,
&[(layout.layer_info(0).id, "1".into())],
target,
sizing,
)?;
println!("Testing {target:?} {sizing:?}, {width} × {height}, zoom {zoom}");
let applied = device_send::send(host, &plan)?;
let mut raw = applied.raw.clone();
// Decode the written physical bank as Preview in a local copy only.
let group = &mut raw["device"]["screenAuxGroupList"]["items"]["S1"];
group["status"]["pp"]["transition"] =
json!(if group["control"]["pp"]["presetDown"] == plan.bank {
"AT_UP"
} else {
"AT_DOWN"
});
let decoded = device::Snapshot::parse(
&json!({"type":"AQL Cmax","isLinked":false,"version":{"major":6,"minor":2,"patch":79}}),
&raw,
)?;
let layer = &decoded.screens[screen].layers[0];
if let Some(reason) = &layer.unsupported {
return Err(reason.clone());
}
let g = layer.geometry;
let want = layout.layers()[0];
if (g.x - want.x).abs() > 1.0
|| (g.y - want.y).abs() > 1.0
|| (g.width - want.width).abs() > 1.0
|| (g.height - want.height).abs() > 1.0
{
return Err(format!("Geometry mismatch: {g:?} vs {want:?}"));
}
if visual {
let masks: Vec<_> = if visual {
vec![Mask {
left: 0.2,
right: 0.1,
top: 0.3,
bottom: 0.2,
..Default::default()
}]
} else {
[MaskOrigin::Layer, MaskOrigin::Source]
.into_iter()
.flat_map(|origin| {
[
Mask {
origin,
left: 0.2,
right: 0.1,
top: 0.3,
bottom: 0.2,
},
Mask {
origin,
left: 0.8,
right: 0.2,
..Default::default()
},
Mask {
origin,
top: 0.4,
bottom: 0.6,
..Default::default()
},
Mask::default(),
]
})
.collect()
};
for mask in masks {
layout.set_mask(0, mask)?;
let current = device::fetch(host)?;
let plan = Plan::prepare(
&current,
&layout,
screen,
&[(layout.layer_info(0).id, "1".into())],
target,
sizing,
)?;
println!("Testing {target:?} {sizing:?}, {width} × {height}, zoom {zoom}");
let applied = device_send::send(host, &plan)?;
let mut raw = applied.raw.clone();
// Decode the written physical bank as Preview in a local copy only.
let group = &mut raw["device"]["screenAuxGroupList"]["items"]["S1"];
group["status"]["pp"]["transition"] =
json!(if group["control"]["pp"]["presetDown"] == plan.bank {
"AT_UP"
} else {
"AT_DOWN"
});
let decoded = device::Snapshot::parse(&identity, &raw)?;
let layer = &decoded.screens[screen].layers[0];
if let Some(reason) = &layer.unsupported {
return Err(reason.clone());
}
let g = layer.geometry;
let want = layout.layers()[0];
if (g.x - want.x).abs() > 1.0
|| (g.y - want.y).abs() > 1.0
|| (g.width - want.width).abs() > 1.0
|| (g.height - want.height).abs() > 1.0
{
return Err(format!("Geometry mismatch: {g:?} vs {want:?}"));
}
let expected = layout.formats().mask_bounds(0, want)?;
let clip = |r: Geometry| {
let x = r.x.clamp(g.x, g.x + g.width);
let y = r.y.clamp(g.y, g.y + g.height);
Geometry {
x,
y,
width: (r.x + r.width).clamp(g.x, g.x + g.width) - x,
height: (r.y + r.height).clamp(g.y, g.y + g.height) - y,
}
};
let expected = clip(expected);
let actual = layer.mask.bounds(g);
for (a, b) in [
(expected.x, actual.x),
(expected.y, actual.y),
(expected.width, actual.width),
(expected.height, actual.height),
] {
if (a - b).abs() > 1.0 {
return Err(format!(
"Mask bounds mismatch: {expected:?} vs {actual:?}"
));
}
}
if visual {
println!(
"Visual check ready: S1 Preview layer 1 at 12.125,34.375, size {width} × {height}; restoring in 60 seconds."
);
std::thread::sleep(Duration::from_secs(60));
return Ok(());
}
println!(
"Visual check ready: S1 Preview layer 1 at 12.125,34.375, size {width} × {height}; restoring in 60 seconds."
"Verified {target:?} {sizing:?}: {width} × {height}, zoom {zoom}, mask {mask:?}"
);
std::thread::sleep(Duration::from_secs(60));
return Ok(());
}
println!(
"Verified {target:?} {sizing:?}: {width} × {height}, zoom {zoom}, fractional center and asymmetric crop"
);
}
}
}
Ok(())
})();
let restored = write(host, &restore).and_then(|()| device::fetch(host));
// Release opposing edges before restoring the original crop and mask.
let mut restoration: Vec<_> = restore
.iter()
.filter(|(p, _)| p.contains("/cropping/") && !p.ends_with("aspectOverride"))
.map(|(p, _)| (p.clone(), json!(0)))
.collect();
restoration.extend(restore.clone());
let restored = write(host, &restoration).and_then(|()| device::fetch(host));
let restored =
restored.map_err(|e| format!("RESTORE FAILED: {e}; diagnostic result: {result:?}"))?;
for (path, value) in restore {
@ -169,6 +306,15 @@ fn main() -> Result<(), String> {
return Err(format!("RESTORE MISMATCH {path}"));
}
}
println!("Original routing, geometry and crop restored and read back.");
for list in ["screenList", "auxiliaryList"] {
if restored.raw["device"][list] != baseline.raw["device"][list] {
return Err(format!(
"RESTORE MISMATCH: {list} differs from the full targeted baseline"
));
}
}
println!(
"Original routing, geometry, crop and masks restored; all targeted screens/auxiliaries match baseline."
);
result
}

View File

@ -0,0 +1,101 @@
//! Explicit Midra/Aquilon emulator diagnostic. Changes Input 1, verifies readback, then restores it.
//! Never run automatically or against a live show.
use canvas_pilot::{device, device_capture, device_inputs::InputDraft, device_send};
fn main() -> Result<(), String> {
let host = std::env::args()
.nth(1)
.ok_or("Specify an authorized emulator address")?;
let state = device::fetch_input(&host, 1)?;
let mut draft = InputDraft::read(&state, 1)?;
println!("{}: {} editable fields", state.identity, draft.fields.len());
let original = draft.values.clone();
let before = device_capture::capture_for(&host, state.profile, 1);
let mut crop = draft.crop();
crop.left += 24.;
crop.top += 12.;
draft.set_crop(crop)?;
let paths: Vec<_> = draft
.changes(&state)?
.iter()
.map(|c| format!("/{}", c.path.join("/")))
.collect();
let result = device_send::send_inputs(&host, &draft);
let check = (|| {
let after = result?;
println!("Crop readback verified");
let capture = device_capture::capture_for(&host, state.profile, 1);
if let Some(dir) = std::env::args().nth(2) {
if let Ok(bytes) = &before {
let _ = std::fs::write(std::path::Path::new(&dir).join("input-before.png"), bytes);
}
if let Ok(bytes) = &capture {
let _ = std::fs::write(std::path::Path::new(&dir).join("input-after.png"), bytes);
}
}
let input_key = if state.profile == device::Profile::Aquilon6 {
"IN_1"
} else {
"INPUT_1"
};
for (label, snapshot) in [("before", &state), ("after", &after)] {
println!(
"{label} dimensions: {}",
snapshot
.raw
.pointer(&format!(
"/device/inputList/items/{input_key}/plugList/items/{}/status/signal/pp",
draft.plug
))
.unwrap()
);
}
match (&before, &capture) {
(Ok(a), Ok(b)) => println!(
"Capture bytes: before {}, after {}, identical {} (does not establish physical processing order)",
a.len(),
b.len(),
a == b
),
_ => println!(
"Capture unavailable: before {:?}, after {:?}",
before.as_ref().err(),
capture.as_ref().err()
),
}
// Compare editable screen state, excluding computed status fields.
fn remove_status(v: &mut serde_json::Value) {
match v {
serde_json::Value::Object(o) => {
o.remove("status");
for v in o.values_mut() {
remove_status(v);
}
}
serde_json::Value::Array(a) => {
for v in a {
remove_status(v)
}
}
_ => {}
}
}
let mut a = state.raw["device"]["screenList"].clone();
let mut b = after.raw["device"]["screenList"].clone();
remove_status(&mut a);
remove_status(&mut b);
if a != b {
return Err("Screen editable state changed during input-only test".into());
}
println!("Screen editable state unchanged");
Ok(())
})();
// Always attempt restoration, including after uncertain write outcomes.
let fresh = device::fetch_input(&host, 1)?;
let mut restore = InputDraft::read(&fresh, 1)?;
for path in paths {
restore.values.insert(path.clone(), original[&path].clone());
}
device_send::send_inputs(&host, &restore)?;
println!("Original input settings restored and verified");
check
}

View File

@ -39,9 +39,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
height: 251.0,
},
)?;
let mut source = layout.formats().sources[0];
source.input_crop.top = 40.0;
source.input_crop.bottom = 40.0;
let source = layout.formats().sources[0];
layout.configure(0, 0, source, layout.layers()[0], true)?;
layout.set_framing(
0,

View File

@ -0,0 +1,30 @@
//! Explicit read-only check of input capture framing; never changes device settings.
use canvas_pilot::{device, device_capture, device_inputs::InputDraft};
fn main() -> Result<(), String> {
let mut args = std::env::args().skip(1);
let host = args
.next()
.ok_or("Usage: read_input_capture DEVICE_IP INPUT_NUMBER")?;
let input: u32 = args
.next()
.ok_or("Input number required")?
.parse()
.map_err(|_| "Invalid input number")?;
let before = device::fetch_input(&host, input)?;
let draft = InputDraft::read(&before, input)?;
let processed = device::input_content_resolution(&before, input)?;
let bytes = device_capture::capture_for(&host, before.profile, input)?;
let image = image::load_from_memory(&bytes).map_err(|e| e.to_string())?;
let size = [image.width(), image.height()];
let after = device::fetch_input(&host, input)?;
draft.changes(&after)?;
let geometry = device_capture::capture_geometry(&before, input, size)?;
if geometry != device_capture::capture_geometry(&after, input, size)? {
return Err("Capture geometry changed during the request".into());
}
println!(
"{} · input {input} · processed {processed:?} · PNG {} × {} · {geometry:?}",
before.identity, size[0], size[1]
);
Ok(())
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "Not displaying selected layer input",
"ui.preview-size-mismatch": "Preview resolution mismatch",
"ui.preview-ratio-mismatch": "Preview ratio mismatch",
"ui.preview-ratio-warning": "Preview has a different aspect ratio. Framing may be misleading; enable Follow input.",
"ui.preview-size-warning": "Preview has a different resolution. Enable Follow input to use the selected source.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "Language packs",
"language.remove-pack": "Remove pack…",
"language.overwrite-pack": "Overwrite pack",
"ui.mask-edges": "Mask edges",
"ui.mask-edges": "Mask edges & centers",
"ui.rename-layer": "Rename layer…",
"ui.move-to-folder": "Move to folder",
"ui.no-folder": "No folder",
@ -42,7 +50,9 @@
"ui.rows": "Rows",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Equal divisions of the output. Visibility and snapping are independent.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Snapping",
"ui.example-backdrop-title-saved-in-project": "Example backdrop title (saved in project)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Updates immediately. Leave blank to hide the title.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Snap movement & resizing",
"ui.pixel-edges": "Pixel edges",
"ui.screen-edges-center-quarters": "Screen edges, center & quarters",
"ui.visible-layer-edges": "Visible layer edges",
"ui.visible-layer-edges": "Layer borders",
"ui.outline-only-layers-this-project": "Outline-only layers (this project)",
"ui.show-toolbar-icon-names": "Show toolbar icon names",
"ui.show-source-patterns-on-other-layers-while-cropping": "Show source patterns on other layers while cropping",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Review pasted values",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Choose a destination for each item below. Other layers stay unchanged.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "Toki Pona",
"language.install-pack": "Install language pack…",
"ui.crop-mask": "Crop & mask",
"ui.canvas": "Canvas"
"ui.canvas": "Canvas",
"theme.packs": "Theme packs",
"theme.install-pack": "Install theme pack…",
"preset.fullscreen": "Fullscreen",
"preset.quarter": "Quarter",
"preset.tiling": "Tiling",
"preset.portrait": "Portrait",
"preset.landscape": "Landscape",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "La elektita tavola enigo ne estas montrata",
"ui.preview-size-mismatch": "Malsama distingivo de antaŭvido",
"ui.preview-ratio-mismatch": "Malsama bildformato de antaŭvido",
"ui.preview-ratio-warning": "La antaŭvido havas alian bildformaton. La enkadrigo povas misgvidi; ŝaltu Sekvi enigon.",
"ui.preview-size-warning": "La antaŭvido havas alian distingivon. Ŝaltu Sekvi enigon por uzi la elektitan fonton.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "Lingvopakaĵoj",
"language.remove-pack": "Forigi pakaĵon…",
"language.overwrite-pack": "Anstataŭigi pakaĵon",
"ui.mask-edges": "Randoj de maskoj",
"ui.mask-edges": "Maskaj randoj kaj centroj",
"ui.rename-layer": "Renomi tavolon…",
"ui.move-to-folder": "Movi al dosierujo",
"ui.no-folder": "Sen dosierujo",
@ -42,7 +50,9 @@
"ui.rows": "Vicoj",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Egalaj dividoj de la eligo. Videbleco kaj algluiĝo estas sendependaj.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Inkluzivas kontakton inter spegule aŭ kontraŭe regrandigataj tavoloj.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: inversigi algluiĝon · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Algluiĝo",
"ui.example-backdrop-title-saved-in-project": "Titolo de ekzempla fono (konservita en projekto)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Ĝisdatigas tuj. Lasu malplena por kaŝi la titolon.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Algluiĝo dum movo kaj regrandigo",
"ui.pixel-edges": "Bilderaj randoj",
"ui.screen-edges-center-quarters": "Ekranaj randoj, centro kaj kvaronoj",
"ui.visible-layer-edges": "Randoj de videblaj tavoloj",
"ui.visible-layer-edges": "Tavolaj randoj",
"ui.outline-only-layers-this-project": "Nur konturoj de tavoloj (ĉi tiu projekto)",
"ui.show-toolbar-icon-names": "Montri nomojn de ilobretaj piktogramoj",
"ui.show-source-patterns-on-other-layers-while-cropping": "Montri fontajn ŝablonojn sur aliaj tavoloj dum tondado",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Kontroli algluitajn valorojn",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Elektu celon por ĉiu suba ero. Aliaj tavoloj restas senŝanĝaj.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Uzu liveritajn fontajn nomojn. Sennomaj eroj kaj celaj dosierujoj restas senŝanĝaj.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Kopiu precizajn tondajn randojn, deŝovojn kaj adaptan reĝimon. Fontaj dimensioj post enira tondo devas kongrui; fontaj atribuoj restas senŝanĝaj.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Kopiu la kvar proporciajn maskajn randojn sen regrandigi la tavolon.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Nemarkitaj valoroj konservas la celajn agordojn. Formataj ŝanĝoj povas adapti ekzistantajn tondojn.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Kontura adapto bezonas Formaton. Pozicio uzas la supran maldekstran fontan angulon kiam ŝaltita.",
@ -486,5 +496,16 @@
"language.name.tok": "Tokipono",
"language.install-pack": "Instali lingvopakaĵon…",
"ui.crop-mask": "Tondado kaj masko",
"ui.canvas": "Kanvaso"
"ui.canvas": "Kanvaso",
"theme.packs": "Temaj pakoj",
"theme.install-pack": "Instali teman pakon…",
"preset.fullscreen": "Plenekrane",
"preset.quarter": "Kvarono",
"preset.tiling": "Kahelado",
"preset.portrait": "Vertikale",
"preset.landscape": "Horizontale",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "No se muestra la entrada seleccionada de la capa",
"ui.preview-size-mismatch": "Resolución de vista previa distinta",
"ui.preview-ratio-mismatch": "Relación de vista previa distinta",
"ui.preview-ratio-warning": "La vista previa tiene otra relación de aspecto. El encuadre puede ser engañoso; active Seguir entrada.",
"ui.preview-size-warning": "La vista previa tiene otra resolución. Active Seguir entrada para usar la fuente seleccionada.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "Paquetes de idiomas",
"language.remove-pack": "Eliminar paquete…",
"language.overwrite-pack": "Sobrescribir paquete",
"ui.mask-edges": "Bordes de máscara",
"ui.mask-edges": "Bordes y centros de máscara",
"ui.rename-layer": "Renombrar capa…",
"ui.move-to-folder": "Mover a carpeta",
"ui.no-folder": "Sin carpeta",
@ -42,7 +50,9 @@
"ui.rows": "Filas",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Divisiones iguales de la salida. Visibilidad y ajuste son independientes.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Incluye el contacto entre capas redimensionadas en espejo o en sentido opuesto.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invertir ajuste · Mayús: 10 px · Ctrl+Mayús: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Ajuste magnético",
"ui.example-backdrop-title-saved-in-project": "Título del fondo de ejemplo (guardado en el proyecto)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Se actualiza al instante. Déjelo vacío para ocultar el título.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Ajustar movimiento y tamaño",
"ui.pixel-edges": "Bordes de píxeles",
"ui.screen-edges-center-quarters": "Bordes, centro y cuartos de pantalla",
"ui.visible-layer-edges": "Bordes de capas visibles",
"ui.visible-layer-edges": "Bordes de capa",
"ui.outline-only-layers-this-project": "Solo contornos de capas (este proyecto)",
"ui.show-toolbar-icon-names": "Mostrar nombres de iconos",
"ui.show-source-patterns-on-other-layers-while-cropping": "Mostrar patrones de otras capas al recortar",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Revisar valores pegados",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Elija un destino para cada elemento. Las otras capas no cambian.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Usa los nombres de origen proporcionados. Los elementos sin nombre y las carpetas de destino no cambian.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copia bordes, desplazamientos y modo de ajuste exactos. Las dimensiones tras el recorte de entrada deben coincidir; las asignaciones de fuentes no cambian.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Adaptar los bordes de recorte proporcionalmente a la entrada de destino. Mantener Advanced fit de esta capa; por defecto, Centered (fit). Las asignaciones de fuentes no cambian.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copia los cuatro bordes proporcionales de máscara sin redimensionar la capa.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Los valores desmarcados conservan el destino. Cambiar el formato puede ajustar los recortes existentes.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "El ajuste de contorno requiere Formato. Posición usa la esquina superior izquierda de origen cuando está activada.",
@ -486,5 +496,16 @@
"language.name.tok": "Toki Pona",
"language.install-pack": "Instalar paquete de idiomas…",
"ui.crop-mask": "Recorte y máscara",
"ui.canvas": "Lienzo"
"ui.canvas": "Lienzo",
"theme.packs": "Paquetes de temas",
"theme.install-pack": "Instalar paquete de temas…",
"preset.fullscreen": "Pantalla completa",
"preset.quarter": "Cuarto",
"preset.tiling": "Mosaico",
"preset.portrait": "Vertical",
"preset.landscape": "Horizontal",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "L’entrée sélectionnée du calque n’est pas affichée",
"ui.preview-size-mismatch": "Résolution de prévisualisation différente",
"ui.preview-ratio-mismatch": "Ratio de prévisualisation différent",
"ui.preview-ratio-warning": "Le ratio de la prévisualisation est différent. Le cadrage peut être trompeur ; activez Suivre l’entrée.",
"ui.preview-size-warning": "La résolution de la prévisualisation est différente. Activez Suivre l’entrée pour utiliser la source sélectionnée.",
"ui.change-input": "Changer l’entrée",
"ui.follow-input": "Suivre l’entrée",
"ui.device-input": "Entrée de l’appareil",
"language.packs": "Packs de langues",
"language.remove-pack": "Supprimer le pack…",
"language.overwrite-pack": "Remplacer le pack",
"ui.mask-edges": "Bords des masques",
"ui.mask-edges": "Bords et centres des masques",
"ui.rename-layer": "Renommer le calque…",
"ui.move-to-folder": "Déplacer vers un dossier",
"ui.no-folder": "Sans dossier",
@ -42,7 +50,9 @@
"ui.rows": "Lignes",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Divisions égales de la sortie. Visibilité et aimantation sont indépendantes.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Inclut le contact entre les calques redimensionnés en miroir ou en opposition.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt : inverser l’aimantation · Maj : 10 px · Ctrl+Maj : 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Aimantation",
"ui.example-backdrop-title-saved-in-project": "Titre du fond d’exemple (enregistré dans le projet)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Mise à jour immédiate. Laissez vide pour masquer le titre.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Aimantation du déplacement et du redimensionnement",
"ui.pixel-edges": "Bords des pixels",
"ui.screen-edges-center-quarters": "Bords, centre et quarts de l’écran",
"ui.visible-layer-edges": "Bords des calques visibles",
"ui.visible-layer-edges": "Bords des calques",
"ui.outline-only-layers-this-project": "Contours seuls (ce projet)",
"ui.show-toolbar-icon-names": "Afficher les noms des outils",
"ui.show-source-patterns-on-other-layers-while-cropping": "Afficher les mires des autres calques pendant le recadrage",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Vérifier les valeurs collées",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Choisissez une destination pour chaque élément. Les autres calques restent inchangés.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Utiliser les noms fournis. Les éléments sans nom et les dossiers de destination restent inchangés.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copier les bords de recadrage, décalages et mode d’ajustement exacts. Les dimensions après recadrage d’entrée doivent correspondre ; les affectations de sources restent inchangées.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Adapter les bords de recadrage proportionnellement à l’entrée de destination. Conserver le mode Advanced fit de ce calque ; par défaut, Centered (fit). Les affectations de sources restent inchangées.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copier les quatre bords proportionnels du masque sans redimensionner le calque.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Les valeurs décochées conservent les réglages de destination. Les changements de format peuvent adapter les recadrages existants.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "L’ajustement des contours nécessite Format. Position utilise le coin supérieur gauche de la source quand cette option est active.",
@ -486,5 +496,16 @@
"language.name.tok": "Toki Pona",
"language.install-pack": "Installer un pack de langues…",
"ui.crop-mask": "Recadrage et masque",
"ui.canvas": "Canevas"
"ui.canvas": "Canevas",
"theme.packs": "Packs de thèmes",
"theme.install-pack": "Installer un pack de thèmes…",
"preset.fullscreen": "Plein écran",
"preset.quarter": "Quart",
"preset.tiling": "Mosaïque",
"preset.portrait": "Portrait",
"preset.landscape": "Paysage",
"ui.reference-picture": "Image de référence",
"ui.load-reference-picture": "Charger une image de référence…",
"ui.input-reference-pictures": "Images de référence des entrées",
"ui.reference-picture-help": "Référence locale uniquement ; jamais envoyée à l’appareil. Utilise le format source, le crop, le zoom, le fit et le masque du calque. Choisissez une entrée à capturer pour la remplacer."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "Ἡ τοῦ στρώματος ᾑρημένη εἴσοδος οὐ δείκνυται",
"ui.preview-size-mismatch": "Ἀνόμοιον μέγεθος προθεωρίας",
"ui.preview-ratio-mismatch": "Ἀνόμοιος λόγος προθεωρίας",
"ui.preview-ratio-warning": "Ἡ προθεωρία ἕτερον λόγον ἔχει· τὸ σχῆμα πλανᾶν δύναται. Τῇ εἰσόδῳ ἀκολούθει.",
"ui.preview-size-warning": "Ἡ προθεωρία ἕτερον μέγεθος ἔχει. Τῇ εἰσόδῳ ἀκολούθει, ἵνα τῇ ᾑρημένῃ πηγῇ χρῇ.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "Δέματα γλωσσῶν",
"language.remove-pack": "Ἀφαιρεῖν τὸ δέμα…",
"language.overwrite-pack": "Ἀντικαθιστάναι τὸ δέμα",
"ui.mask-edges": "Ἄκρα τῶν καλυμμάτων",
"ui.mask-edges": "Ἄκρα καὶ κέντρα καλυμμάτων",
"ui.rename-layer": "Μετονόμασον τὸ στρῶμα…",
"ui.move-to-folder": "Εἰς φάκελον μετάθεσον",
"ui.no-folder": "Ἄνευ φακέλου",
@ -42,7 +50,9 @@
"ui.rows": "Στίχοι",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Ἴσαι διαιρέσεις τῆς ἐξόδου. Ὁρατότης καὶ πρόσφυσις χωρισταί εἰσιν.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Περιέχει καὶ τὴν ἐπαφὴν στρωμάτων κατοπτρικῶς ἢ ἐναντίως μεταβαλλομένων.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: ἀντιστροφὴ προσφύσεως · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Πρόσφυσις",
"ui.example-backdrop-title-saved-in-project": "Τίτλος ὑποδείγματος βάθους (ἐν τῷ σχεδίῳ σῴζεται)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Εὐθὺς μεταβάλλεται. Κενὸν ἔα ἵνα ὁ τίτλος κρύπτηται.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Ἐνέργει πρόσφυσιν κινήσεως καὶ μεγέθους",
"ui.pixel-edges": "Ὅρια ψηφίδων",
"ui.screen-edges-center-quarters": "Ὅρια, κέντρον καὶ τεταρτημόρια πετάσματος",
"ui.visible-layer-edges": "Ὅρια ὁρατῶν στρωμάτων",
"ui.visible-layer-edges": "Ἄκρα στρωμάτων",
"ui.outline-only-layers-this-project": "Μόνα περιγράμματα στρωμάτων (τόδε τὸ σχέδιον)",
"ui.show-toolbar-icon-names": "Δεῖξον τὰ ὀνόματα τῶν εἰκονιδίων",
"ui.show-source-patterns-on-other-layers-while-cropping": "Ἐν τῇ ἀποτομῇ δεῖξον τὰ ὑποδείγματα πηγῶν τῶν ἄλλων στρωμάτων",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Σκέψαι τὰς ἐπικολληθείσας τιμάς",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Ἕλου προορισμὸν ἑκάστῳ τῶν κάτω. Τὰ ἄλλα στρώματα μένει.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Χρῶ τοῖς δοθεῖσιν ὀνόμασι πηγῆς. Ἀνώνυμα καὶ φάκελοι προορισμοῦ μένουσιν.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Ἀντίγραψον ἀκριβῆ ὅρια, μετατοπίσεις καὶ τρόπον προσαρμογῆς. Αἱ διαστάσεις μετὰ τὴν ἀποτομὴν εἰσόδου δεῖ συμφωνεῖν· αἱ ἀναθέσεις πηγῶν μένουσιν.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Τὰ ὅρια τῆς ἀποτομῆς κατὰ λόγον τῆς εἰσόδου προσαρμόζεται. Ὁ τρόπος Advanced fit τοῦ στρώματος μένει· ὁ συνήθης Centered (fit). Αἱ ἀναθέσεις πηγῶν μένουσιν.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Ἀντίγραψον τὰ τέσσαρα ἀνάλογα ὅρια καλύμματος ἄνευ μεταβολῆς μεγέθους στρώματος.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Αἱ μὴ ἐκλελεγμέναι τιμαὶ τηροῦσι τὰ τοῦ προορισμοῦ. Μεταβολαὶ μορφῆς δύνανται προσαρμόζειν ὑπαρχούσας ἀποτομάς.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Ἡ διόρθωσις περιγράμματος δεῖται Μορφῆς. Ἡ Θέσις τῇ ἄνω ἀριστερᾷ γωνίᾳ τῆς πηγῆς χρῆται ἐνεργοῦσα.",
@ -486,5 +496,16 @@
"language.name.tok": "Τόκι Πόνα",
"language.install-pack": "Install language pack…",
"ui.crop-mask": "Περικοπὴ καὶ κάλυμμα",
"ui.canvas": "Πίναξ"
"ui.canvas": "Πίναξ",
"theme.packs": "Δέσμαι θεμάτων",
"theme.install-pack": "Ἐγκατάστησον δέσμην θεμάτων…",
"preset.fullscreen": "Ὅλη ὀθόνη",
"preset.quarter": "Τέταρτον",
"preset.tiling": "Πλακόστρωσις",
"preset.portrait": "Ὄρθιον",
"preset.landscape": "Πλάγιον",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "परत का चयनित इनपुट प्रदर्शित नहीं हो रहा है",
"ui.preview-size-mismatch": "पूर्वावलोकन का रिज़ॉल्यूशन अलग है",
"ui.preview-ratio-mismatch": "पूर्वावलोकन का अनुपात अलग है",
"ui.preview-ratio-warning": "पूर्वावलोकन का पहलू अनुपात अलग है। फ़्रेमिंग भ्रामक हो सकती है; इनपुट का अनुसरण सक्षम करें।",
"ui.preview-size-warning": "पूर्वावलोकन का रिज़ॉल्यूशन अलग है। चयनित स्रोत के लिए इनपुट का अनुसरण सक्षम करें।",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "भाषा पैक",
"language.remove-pack": "पैक हटाएँ…",
"language.overwrite-pack": "पैक बदलें",
"ui.mask-edges": "मास्क के किनारे",
"ui.mask-edges": "मास्क के किनारे और केंद्र",
"ui.rename-layer": "परत का नाम बदलें…",
"ui.move-to-folder": "फ़ोल्डर में ले जाएँ",
"ui.no-folder": "कोई फ़ोल्डर नहीं",
@ -42,7 +50,9 @@
"ui.rows": "पंक्तियाँ",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "आउटपुट के बराबर भाग। दृश्यता और स्नैपिंग स्वतंत्र हैं।",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "स्नैपिंग",
"ui.example-backdrop-title-saved-in-project": "उदाहरण पृष्ठभूमि शीर्षक (परियोजना में सहेजा जाता है)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "तुरंत अपडेट होता है। शीर्षक छिपाने के लिए खाली छोड़ें।",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "स्थान और आकार बदलते समय स्नैप करें",
"ui.pixel-edges": "पिक्सेल के किनारे",
"ui.screen-edges-center-quarters": "स्क्रीन के किनारे, केंद्र और चौथाई",
"ui.visible-layer-edges": "दृश्यमान परतों के किनारे",
"ui.visible-layer-edges": "लेयर की सीमाएँ",
"ui.outline-only-layers-this-project": "केवल परतों की रूपरेखा (इस परियोजना में)",
"ui.show-toolbar-icon-names": "टूलबार आइकन के नाम दिखाएँ",
"ui.show-source-patterns-on-other-layers-while-cropping": "क्रॉप करते समय अन्य परतों पर स्रोत पैटर्न दिखाएँ",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "चिपकाए गए मान जाँचें",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "नीचे हर वस्तु का गंतव्य चुनें। अन्य परतें बनी रहती हैं।",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "टोकी पोना",
"language.install-pack": "भाषा पैक स्थापित करें…",
"ui.crop-mask": "क्रॉप और मास्क",
"ui.canvas": "कैनवास"
"ui.canvas": "कैनवास",
"theme.packs": "थीम पैक",
"theme.install-pack": "थीम पैक स्थापित करें…",
"preset.fullscreen": "पूर्ण स्क्रीन",
"preset.quarter": "चौथाई",
"preset.tiling": "टाइल व्यवस्था",
"preset.portrait": "लंबवत",
"preset.landscape": "क्षैतिज",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "レイヤーで選択した入力を表示していません",
"ui.preview-size-mismatch": "プレビューの解像度が異なります",
"ui.preview-ratio-mismatch": "プレビューの縦横比が異なります",
"ui.preview-ratio-warning": "プレビューの縦横比が異なるため、構図が正確でない場合があります。入力に追従を有効にしてください。",
"ui.preview-size-warning": "プレビューの解像度が異なります。選択したソースを使うには入力に追従を有効にしてください。",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "言語パック",
"language.remove-pack": "パックを削除…",
"language.overwrite-pack": "パックを上書き",
"ui.mask-edges": "マスクの端",
"ui.mask-edges": "マスクの端と中心",
"ui.rename-layer": "レイヤー名を変更…",
"ui.move-to-folder": "フォルダーに移動",
"ui.no-folder": "フォルダーなし",
@ -42,7 +50,9 @@
"ui.rows": "行",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "出力を等分します。表示とスナップは独立しています。",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "対称・逆方向にサイズ変更するレイヤー同士の接触も含みます。",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt:スナップ反転 · Shift:10 px · Ctrl+Shift:100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "スナップ",
"ui.example-backdrop-title-saved-in-project": "背景サンプルのタイトル(プロジェクトに保存)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "すぐに反映されます。空欄でタイトルを非表示にします。",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "移動とサイズ変更をスナップ",
"ui.pixel-edges": "ピクセル境界",
"ui.screen-edges-center-quarters": "画面の端、中央、四分点",
"ui.visible-layer-edges": "表示レイヤーの端",
"ui.visible-layer-edges": "レイヤーの境界",
"ui.outline-only-layers-this-project": "レイヤーを輪郭のみ表示(このプロジェクト)",
"ui.show-toolbar-icon-names": "ツールバーのアイコン名を表示",
"ui.show-source-patterns-on-other-layers-while-cropping": "クロップ中に他レイヤーのソースパターンを表示",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "貼り付けた値を確認",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "下の各項目の宛先を選んでください。他のレイヤーは変更されません。",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "提供されたソース名を使用します。名前のない項目と宛先フォルダーは変更されません。",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "クロップの端、オフセット、fit モードを正確にコピーします。入力クロップ後のソース寸法は一致する必要があります。ソースの割り当ては変わりません。",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "クロップの各辺を宛先入力の寸法に比例して調整します。このレイヤーの Advanced fit を維持し、既定は Centered (fit) です。ソースの割り当ては変更しません。",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "レイヤーのサイズを変えず、マスクの四辺の比率をコピーします。",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "未選択の値は宛先の設定を保持します。フォーマットを変更すると既存クロップが調整される場合があります。",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "輪郭調整にはフォーマットが必要です。位置を有効にするとソースの左上を使用します。",
@ -486,5 +496,16 @@
"language.name.tok": "トキポナ",
"language.install-pack": "言語パックをインストール…",
"ui.crop-mask": "クロップとマスク",
"ui.canvas": "キャンバス"
"ui.canvas": "キャンバス",
"theme.packs": "テーマパック",
"theme.install-pack": "テーマパックをインストール…",
"preset.fullscreen": "全画面",
"preset.quarter": "4分の1",
"preset.tiling": "タイル配置",
"preset.portrait": "縦向き",
"preset.landscape": "横向き",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "तहको चयन गरिएको इनपुट देखाइएको छैन",
"ui.preview-size-mismatch": "पूर्वावलोकनको रिजोलुसन फरक छ",
"ui.preview-ratio-mismatch": "पूर्वावलोकनको अनुपात फरक छ",
"ui.preview-ratio-warning": "पूर्वावलोकनको पक्ष अनुपात फरक छ। फ्रेमिङ भ्रामक हुन सक्छ; इनपुट पछ्याउनुहोस् सक्षम गर्नुहोस्।",
"ui.preview-size-warning": "पूर्वावलोकनको रिजोलुसन फरक छ। चयन गरिएको स्रोत प्रयोग गर्न इनपुट पछ्याउनुहोस् सक्षम गर्नुहोस्।",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "भाषा प्याकहरू",
"language.remove-pack": "प्याक हटाउनुहोस्…",
"language.overwrite-pack": "प्याक बदल्नुहोस्",
"ui.mask-edges": "मास्कका किनाराहरू",
"ui.mask-edges": "मास्कका किनारा र केन्द्रहरू",
"ui.rename-layer": "तहको नाम फेर्नुहोस्…",
"ui.move-to-folder": "फोल्डरमा सार्नुहोस्",
"ui.no-folder": "फोल्डर छैन",
@ -42,7 +50,9 @@
"ui.rows": "पङ्क्तिहरू",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "आउटपुटका बराबर भागहरू। दृश्यता र स्न्यापिङ स्वतन्त्र छन्।",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "स्न्यापिङ",
"ui.example-backdrop-title-saved-in-project": "उदाहरण पृष्ठभूमिको शीर्षक (परियोजनामा सेभ हुन्छ)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "तुरुन्त अद्यावधिक हुन्छ। शीर्षक लुकाउन खाली छोड्नुहोस्।",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "सार्दा र आकार बदल्दा स्न्याप गर्नुहोस्",
"ui.pixel-edges": "पिक्सेलका किनाराहरू",
"ui.screen-edges-center-quarters": "स्क्रिनका किनारा, केन्द्र र चौथाइ",
"ui.visible-layer-edges": "देखिने तहका किनाराहरू",
"ui.visible-layer-edges": "तहका किनाराहरू",
"ui.outline-only-layers-this-project": "तहको रूपरेखा मात्र (यो परियोजना)",
"ui.show-toolbar-icon-names": "उपकरणपट्टीका आइकन नाम देखाउनुहोस्",
"ui.show-source-patterns-on-other-layers-while-cropping": "क्रप गर्दा अन्य तहहरूमा स्रोत ढाँचा देखाउनुहोस्",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "टाँसिएका मानहरू समीक्षा गर्नुहोस्",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "तलका हरेक वस्तुको गन्तव्य छान्नुहोस्। अरू तह उही रहन्छन्।",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "टोकी पोना",
"language.install-pack": "भाषा प्याक स्थापना गर्नुहोस्…",
"ui.crop-mask": "क्रप र मास्क",
"ui.canvas": "क्यानभास"
"ui.canvas": "क्यानभास",
"theme.packs": "थिम प्याकहरू",
"theme.install-pack": "थिम प्याक स्थापना गर्नुहोस्…",
"preset.fullscreen": "पूरा पर्दा",
"preset.quarter": "चौथाइ",
"preset.tiling": "टाइल मिलान",
"preset.portrait": "ठाडो",
"preset.landscape": "तेर्सो",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "Não mostra a entrada selecionada da camada",
"ui.preview-size-mismatch": "Resolução da pré-visualização diferente",
"ui.preview-ratio-mismatch": "Proporção da pré-visualização diferente",
"ui.preview-ratio-warning": "A pré-visualização tem outra proporção. O enquadramento pode ser enganador; ative Seguir entrada.",
"ui.preview-size-warning": "A pré-visualização tem outra resolução. Ative Seguir entrada para usar a fonte selecionada.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "Pacotes de idiomas",
"language.remove-pack": "Remover pacote…",
"language.overwrite-pack": "Substituir pacote",
"ui.mask-edges": "Limites da máscara",
"ui.mask-edges": "Bordas e centros da máscara",
"ui.rename-layer": "Mudar nome da camada…",
"ui.move-to-folder": "Mover para pasta",
"ui.no-folder": "Sem pasta",
@ -42,7 +50,9 @@
"ui.rows": "Linhas",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "Divisões iguais da saída. Visibilidade e encaixe são independentes.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "Encaixe",
"ui.example-backdrop-title-saved-in-project": "Título do fundo de exemplo (guardado no projeto)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "Atualiza de imediato. Deixe vazio para ocultar o título.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "Encaixar movimento e tamanho",
"ui.pixel-edges": "Limites dos píxeis",
"ui.screen-edges-center-quarters": "Limites, centro e quartos do ecrã",
"ui.visible-layer-edges": "Limites das camadas visíveis",
"ui.visible-layer-edges": "Bordas das camadas",
"ui.outline-only-layers-this-project": "Só contornos das camadas (neste projeto)",
"ui.show-toolbar-icon-names": "Mostrar nomes dos ícones",
"ui.show-source-patterns-on-other-layers-while-cropping": "Mostrar padrões nas outras camadas durante o recorte",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "Rever valores colados",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "Escolha um destino para cada elemento. As outras camadas mantêm-se.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "Toki Pona",
"language.install-pack": "Instalar pacote de idiomas…",
"ui.crop-mask": "Recorte e máscara",
"ui.canvas": "Tela"
"ui.canvas": "Tela",
"theme.packs": "Pacotes de temas",
"theme.install-pack": "Instalar pacote de temas…",
"preset.fullscreen": "Ecrã inteiro",
"preset.quarter": "Quarto",
"preset.tiling": "Mosaico",
"preset.portrait": "Retrato",
"preset.landscape": "Paisagem",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "ไม่ได้แสดงอินพุตที่เลือกของเลเยอร์",
"ui.preview-size-mismatch": "ความละเอียดภาพตัวอย่างไม่ตรงกัน",
"ui.preview-ratio-mismatch": "อัตราส่วนภาพตัวอย่างไม่ตรงกัน",
"ui.preview-ratio-warning": "ภาพตัวอย่างมีอัตราส่วนต่างกัน การจัดกรอบอาจทำให้เข้าใจผิด โปรดเปิดติดตามอินพุต",
"ui.preview-size-warning": "ภาพตัวอย่างมีความละเอียดต่างกัน เปิดติดตามอินพุตเพื่อใช้แหล่งสัญญาณที่เลือก",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "ชุดภาษา",
"language.remove-pack": "ลบชุดภาษา…",
"language.overwrite-pack": "เขียนทับชุดภาษา",
"ui.mask-edges": "ขอบมาสก์",
"ui.mask-edges": "ขอบและจุดกึ่งกลางของมาสก์",
"ui.rename-layer": "เปลี่ยนชื่อเลเยอร์…",
"ui.move-to-folder": "ย้ายไปโฟลเดอร์",
"ui.no-folder": "ไม่มีโฟลเดอร์",
@ -42,7 +50,9 @@
"ui.rows": "แถว",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "แบ่งเอาต์พุตเท่า ๆ กัน การมองเห็นและการดูดตำแหน่งแยกจากกัน",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "การดูดเข้าตำแหน่ง",
"ui.example-backdrop-title-saved-in-project": "ชื่อพื้นหลังตัวอย่าง (บันทึกในโครงการ)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "อัปเดตทันที เว้นว่างเพื่อซ่อนชื่อ",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "ดูดตำแหน่งเมื่อย้ายและปรับขนาด",
"ui.pixel-edges": "ขอบพิกเซล",
"ui.screen-edges-center-quarters": "ขอบ กึ่งกลาง และหนึ่งในสี่ของหน้าจอ",
"ui.visible-layer-edges": "ขอบเลเยอร์ที่มองเห็น",
"ui.visible-layer-edges": "ขอบเลเยอร์",
"ui.outline-only-layers-this-project": "แสดงเฉพาะเส้นขอบเลเยอร์ (โครงการนี้)",
"ui.show-toolbar-icon-names": "แสดงชื่อไอคอนแถบเครื่องมือ",
"ui.show-source-patterns-on-other-layers-while-cropping": "แสดงลวดลายต้นทางบนเลเยอร์อื่นขณะครอบตัด",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "ตรวจสอบค่าที่วาง",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "เลือกปลายทางสำหรับแต่ละรายการด้านล่าง เลเยอร์อื่นคงเดิม",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "โทกิโพนา",
"language.install-pack": "ติดตั้งชุดภาษา…",
"ui.crop-mask": "ครอบตัดและมาสก์",
"ui.canvas": "พื้นที่ทำงาน"
"ui.canvas": "พื้นที่ทำงาน",
"theme.packs": "แพ็กธีม",
"theme.install-pack": "ติดตั้งแพ็กธีม…",
"preset.fullscreen": "เต็มหน้าจอ",
"preset.quarter": "หนึ่งส่วนสี่",
"preset.tiling": "เรียงกระเบื้อง",
"preset.portrait": "แนวตั้ง",
"preset.landscape": "แนวนอน",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "sitelen ni li tan ala sitelen pi wile sina",
"ui.preview-size-mismatch": "suli pi sitelen lukin li ante",
"ui.preview-ratio-mismatch": "suli pi sitelen lukin li ante",
"ui.preview-ratio-warning": "nasin suli pi sitelen lukin li ante. sitelen li ken pana e sona ike. o kepeken sitelen pi tomo Follow input.",
"ui.preview-size-warning": "suli pi sitelen lukin li ante. o kepeken tomo Follow input tawa sitelen tan wile.",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "kulupu toki",
"language.remove-pack": "o weka e kulupu…",
"language.overwrite-pack": "o ante e kulupu",
"ui.mask-edges": "poka pi len sitelen",
"ui.mask-edges": "poka pi len sitelen en insa ona",
"ui.rename-layer": "o ante e nimi lipu…",
"ui.move-to-folder": "o tawa kulupu",
"ui.no-folder": "kulupu ala",
@ -42,7 +50,9 @@
"ui.rows": "kulupu supa",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "kipisi sama pi sitelen tawa. lukin en awen lon linja li wan ala.",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "Includes contact between mirrored/opposite resizing layers.",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "awen lon linja",
"ui.example-backdrop-title-saved-in-project": "nimi pi sitelen monsi (awen lon pali)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "ona li sin lon tenpo ni. nimi ala la nimi li len.",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "o awen e tawa e suli lon linja",
"ui.pixel-edges": "poka pi poki sitelen",
"ui.screen-edges-center-quarters": "poka supa en insa en kipisi tu tu",
"ui.visible-layer-edges": "poka pi lipu lukin",
"ui.visible-layer-edges": "poka pi sitelen supa",
"ui.outline-only-layers-this-project": "linja lipu taso (pali ni)",
"ui.show-toolbar-icon-names": "o lukin e nimi ilo",
"ui.show-source-patterns-on-other-layers-while-cropping": "o lukin e sitelen tan lon lipu ante lon tenpo kipisi",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "o lukin e nanpa kama",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "o anu e tawa pi ijo ale ni. lipu ante li awen.",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "Use supplied source names. Unnamed items and destination folders stay unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Copy exact crop edges, offsets and fit mode. Source dimensions after input crop must match; source assignments remain unchanged.",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "Scale crop edges proportionally to the destination input. Keep this layer’s Advanced fit; default to Centered (fit). Source assignments stay unchanged.",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "Copy the four proportional mask edges without resizing the layer.",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "Unchecked values keep the destination settings. Format changes may adjust existing crops to fit.",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "Outline adjustment requires Format. Position uses the source top-left when enabled.",
@ -486,5 +496,16 @@
"language.name.tok": "toki pona",
"language.install-pack": "o pana e kulupu toki…",
"ui.crop-mask": "kipisi en len",
"ui.canvas": "supa sitelen"
"ui.canvas": "supa sitelen",
"theme.packs": "kulupu kule",
"theme.install-pack": "o pana e kulupu kule…",
"preset.fullscreen": "selo ale",
"preset.quarter": "kipisi pi tu tu",
"preset.tiling": "kulupu leko",
"preset.portrait": "poka sewi",
"preset.landscape": "poka lili",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

View File

@ -1,8 +1,16 @@
{
"ui.preview-other-input": "当前显示的不是图层所选输入",
"ui.preview-size-mismatch": "预览分辨率不匹配",
"ui.preview-ratio-mismatch": "预览宽高比不匹配",
"ui.preview-ratio-warning": "预览宽高比不同,构图可能产生误导。请启用跟随输入。",
"ui.preview-size-warning": "预览分辨率不同。请启用跟随输入以使用所选信号源。",
"ui.change-input": "Change input",
"ui.follow-input": "Follow input",
"ui.device-input": "Device input",
"language.packs": "语言包",
"language.remove-pack": "移除语言包…",
"language.overwrite-pack": "覆盖语言包",
"ui.mask-edges": "蒙版边缘",
"ui.mask-edges": "遮罩边缘和中心",
"ui.rename-layer": "重命名图层…",
"ui.move-to-folder": "移至文件夹",
"ui.no-folder": "无文件夹",
@ -42,7 +50,9 @@
"ui.rows": "行",
"ui.equal-divisions-of-the-output-visibility-and-snapping-are-independent": "等分输出区域。显示与吸附互不影响。",
"ui.includes-contact-between-mirrored-opposite-resizing-layers": "也包括镜像或反向缩放图层之间的接触。",
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px": "Alt:反转吸附 · Shift:10 px · Ctrl+Shift:100 px",
"ui.snapping-modifiers-help": "Alt: invert snapping · Shift: 10 px · Ctrl+Shift: 100 px · Shift+Space: force whole pixels",
"ui.force-snapping-to-whole-pixels": "Force snapping to whole pixels",
"ui.force-whole-pixels-help": "Always snap moved positions and resized edges to integer pixels. Ratio-locked resizing may slightly approximate the ratio.",
"ui.snapping": "吸附",
"ui.example-backdrop-title-saved-in-project": "示例背景标题(保存在项目中)",
"ui.updates-immediately-leave-blank-to-hide-the-title": "立即更新。留空可隐藏标题。",
@ -78,7 +88,7 @@
"ui.snap-movement-resizing": "移动和缩放吸附",
"ui.pixel-edges": "像素边缘",
"ui.screen-edges-center-quarters": "屏幕边缘、中心和四分点",
"ui.visible-layer-edges": "可见图层边缘",
"ui.visible-layer-edges": "图层边框",
"ui.outline-only-layers-this-project": "仅显示图层轮廓(此项目)",
"ui.show-toolbar-icon-names": "显示工具栏图标名称",
"ui.show-source-patterns-on-other-layers-while-cropping": "裁剪时显示其他图层的源图案",
@ -253,7 +263,7 @@
"ui.review-pasted-values": "检查粘贴数值",
"ui.choose-a-destination-for-each-item-below-other-layers-stay-unchanged": "为以下各项选择目标。其他图层保持不变。",
"ui.use-supplied-source-names-unnamed-items-and-destination-folders-stay-unchanged": "使用提供的源名称。无名称项目和目标文件夹保持不变。",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "精确复制裁剪边缘、偏移和适配模式。输入裁剪后的源尺寸必须匹配;源分配保持不变。",
"ui.copy-exact-crop-edges-offsets-and-fit-mode-source-dimensions-after-input-crop-must-ma": "按目标输入尺寸等比例调整各轴的裁剪边缘。保留此图层的 Advanced fit,默认使用 Centered (fit)。不改变源分配。",
"ui.copy-the-four-proportional-mask-edges-without-resizing-the-layer": "复制遮罩四边比例,不改变图层尺寸。",
"ui.unchecked-values-keep-the-destination-settings-format-changes-may-adjust-existing-cro": "未勾选的值保留目标设置。格式更改可能调整现有裁剪。",
"ui.outline-adjustment-requires-format-position-uses-the-source-top-left-when-enabled": "轮廓调整需要启用格式。启用位置时使用源左上角。",
@ -486,5 +496,16 @@
"language.name.tok": "道本语",
"language.install-pack": "安装语言包…",
"ui.crop-mask": "裁剪与遮罩",
"ui.canvas": "画布"
"ui.canvas": "画布",
"theme.packs": "主题包",
"theme.install-pack": "安装主题包…",
"preset.fullscreen": "全屏",
"preset.quarter": "四分之一",
"preset.tiling": "平铺",
"preset.portrait": "纵向",
"preset.landscape": "横向",
"ui.reference-picture": "Reference picture",
"ui.load-reference-picture": "Load reference picture…",
"ui.input-reference-pictures": "Input reference pictures",
"ui.reference-picture-help": "Local reference only; never sent to the device. Uses this layer’s source format, crop, zoom, fit and mask. Choose a capture input to replace it."
}

File diff suppressed because it is too large Load Diff

View File

@ -167,7 +167,7 @@ impl Layout {
}
}
let mut seen = std::collections::BTreeSet::new();
for &(i, a) in appearances {
for &(i, _) in appearances {
if i >= self.layers.len() || !self.selectable(i) {
return Err("Clipboard destination must be an editable layer.".into());
}
@ -177,28 +177,39 @@ impl Layout {
if zooms.iter().any(|(target, _)| *target == i) {
return Err("Choose full crop and fit or legacy zoom, not both.".into());
}
if crop_fit {
let input = self.formats.input(i)?;
if input
.iter()
.zip(a.input_size)
.any(|(v, expected)| (v - expected).abs() > 1e-8)
{
return Err("Crop & fit requires matching source dimensions after input crop. Match the destination source or uncheck Crop & fit.".into());
}
}
}
let mut draft = self.clone();
draft.apply_mapped_import_with_zoom(values, zooms)?;
for &(i, appearance) in appearances {
if crop_fit {
appearance.validate(draft.layers[i]).map_err(|error| {
format!(
"Cannot paste Crop & fit: {error} Include Format or uncheck Crop & fit."
)
})?;
draft.formats.advanced[i] = appearance.crop;
draft.formats.layer_fit[i] = appearance.fit;
formats::validate_size(appearance.input_size)?;
appearance.crop.remaining(appearance.input_size)?;
let input = draft.formats.input(i)?;
let scale = [
input[0] / appearance.input_size[0],
input[1] / appearance.input_size[1],
];
let crop = Crop {
left: appearance.crop.left * scale[0],
right: appearance.crop.right * scale[0],
top: appearance.crop.top * scale[1],
bottom: appearance.crop.bottom * scale[1],
};
let g = draft.layers[i];
let fit = draft.formats.layer_fit[i].or_else(|| {
formats::mapping(input, [g.width, g.height], crop)
.is_err()
.then_some(LayerFit::Centered)
});
let adapted = Appearance {
input_size: input,
crop,
fit,
mask: appearance.mask,
};
adapted.validate(g)?;
draft.formats.advanced[i] = crop;
draft.formats.layer_fit[i] = fit;
}
if masks {
draft.formats.masks[i] = appearance.mask.validate()?;

View File

@ -154,13 +154,15 @@ fn read_json(
}
serde_json::from_slice(&bytes).map_err(|e| format!("Invalid device JSON: {e}"))
}
/// Parse an IP address with an optional TCP port (default 80).
/// Parse an IP address with an optional TCP port (default 80), or a root HTTP URL.
/// IPv6 with a port uses bracket notation: `[::1]:3000`.
pub fn address(host: &str) -> Result<SocketAddr, String> {
let host = host.trim();
let host = host.strip_prefix("http://").unwrap_or(host);
let host = host.strip_suffix('/').unwrap_or(host);
let address = host.parse::<IpAddr>().map(|ip| SocketAddr::new(ip, 80))
.or_else(|_| host.parse::<SocketAddr>())
.map_err(|_| "Enter a device IP address, optionally with a port, e.g. 192.168.10.146:3000 or [::1]:3000; omit http:// and paths.")?;
.map_err(|_| "Enter a device IP address, optionally with a port, e.g. 192.168.10.146:3000 or [::1]:3000; HTTP root URLs are also accepted; omit credentials, queries and paths.")?;
if address.port() == 0 {
return Err("Device port must be between 1 and 65535.".into());
}
@ -229,3 +231,60 @@ impl<R: Read> Read for CancelReader<'_, R> {
self.inner.read(bytes)
}
}
/// Read one input's preprocessing controls without downloading the whole Aquilon store.
pub fn fetch_input(host: &str, input: u32) -> Result<Snapshot, String> {
let mut snapshot = fetch(host)?;
enrich_input(host, &mut snapshot, input, 10606)?;
Ok(snapshot)
}
pub(crate) fn enrich_input(
host: &str,
snapshot: &mut Snapshot,
input: u32,
port: u16,
) -> Result<(), String> {
if !(1..=snapshot.profile.input_limit()).contains(&input) {
return Err("Invalid input".into());
}
if snapshot.profile == Profile::Aquilon6 {
state::input_settings(SocketAddr::new(address(host)?.ip(), port), snapshot, input)?;
}
Ok(())
}
/// Dimensions of the selected input after device preprocessing. Midra input crop
/// is already included in imageWidth/imageHeight and must not be subtracted twice.
pub fn input_content_resolution(snapshot: &Snapshot, input: u32) -> Result<[u32; 2], String> {
let raw = value(
&snapshot.raw,
&format!(
"/device/inputList/items/{}",
snapshot.profile.input_key(input)
),
)?;
let plug = text(raw, "/status/pp/plug")?;
let settings = value(raw, &format!("/plugList/items/{plug}"))?;
if settings
.pointer("/status/signal/pp/isValid")
.and_then(Value::as_bool)
!= Some(true)
{
return Err("Input has no valid signal".into());
}
match snapshot.profile {
Profile::Midra4k => midra::cropped_input_resolution(settings),
Profile::Aquilon6 => crate::formats::resolution_from_values([
number(settings, "/status/signal/pp/imageWidth")?,
number(settings, "/status/signal/pp/imageHeight")?,
]),
}
}
/// Processed source dimensions supported by the Aquilon adapter; preserves its compatibility checks.
pub(crate) fn aquilon_source_resolution(
raw: &Value,
layer: &Value,
) -> Result<Option<[u32; 2]>, String> {
aquilon::source_resolution(raw, layer)
}

View File

@ -3,7 +3,7 @@ use super::*;
use crate::{
Layout,
device_send::{Change, Plan, Sizing, Target},
formats::{Aspect, Crop, Source},
formats::{Aspect, Crop, Mask, Source},
};
use serde_json::json;
use std::collections::BTreeSet;
@ -39,7 +39,6 @@ fn source_info(raw: &Value, source: &str) -> Result<Option<(Source, String)>, St
Source {
native,
aspect: Aspect::Custom,
input_crop: Crop::default(),
},
text(plug, "/settings/aspect/pp/layerFill")?,
)))
@ -59,12 +58,39 @@ fn crop(layer: &Value, native: [u32; 2]) -> Result<Crop, String> {
bottom: edge("bottom", 1)?,
})
}
fn unmasked(layer: &Value) -> Result<(), String> {
for edge in ["left", "right", "top", "bottom"] {
if number(layer, &format!("/cropping/mask/pp/{edge}"))? != 0.0 {
return Err("Nonzero mask: visible-bound conversion is not supported.".into());
fn native_mask(layer: &Value) -> Result<Mask, String> {
let edge = |key: &str| -> Result<f64, String> {
let n = number(layer, &format!("/cropping/mask/pp/{key}"))?;
if n.fract() != 0.0 || !(0.0..=65535.0).contains(&n) {
return Err("Invalid Aquilon mask units.".into());
}
Ok(n / 65535.0)
};
Mask {
left: edge("left")?,
right: edge("right")?,
top: edge("top")?,
bottom: edge("bottom")?,
..Default::default()
}
.validate()
}
// Aquilon blanking is relative to its container; the normal editor workflow
// uses the visible centered image. Preserve their intersection without resizing.
fn relative_mask(reveal: Geometry, reference: Geometry) -> Mask {
let left = ((reveal.x - reference.x) / reference.width).clamp(0.0, 1.0);
let top = ((reveal.y - reference.y) / reference.height).clamp(0.0, 1.0);
Mask {
left,
right: ((reference.x + reference.width - reveal.x - reveal.width) / reference.width)
.clamp(0.0, 1.0 - left),
top,
bottom: ((reference.y + reference.height - reveal.y - reveal.height) / reference.height)
.clamp(0.0, 1.0 - top),
..Default::default()
}
}
fn anchor(layer: &Value) -> Result<(), String> {
if text(layer, "/position/pp/anchor")? != "MIDDLE_CENTER" {
return Err("Only middle-center layer anchors are currently supported.".into());
}
@ -76,7 +102,7 @@ fn framing(
source: &str,
container: Geometry,
) -> Result<(Geometry, Option<(Source, Crop)>), String> {
unmasked(layer)?;
anchor(layer)?;
let Some((source, inherited)) = source_info(raw, source)? else {
if ["left", "right", "top", "bottom"]
.iter()
@ -169,10 +195,19 @@ pub(super) fn parse(identity: String, raw: &Value) -> Result<Snapshot, String> {
height,
}
.validate()?;
let (geometry, framing, unsupported) = match framing(raw, layer, &source, container)
{
Ok((geometry, framing)) => (geometry, framing, None),
Err(error) => (container, None, Some(error)),
let appearance =
framing(raw, layer, &source, container).and_then(|(geometry, framing)| {
let mask = native_mask(layer)?;
let mask = if mask.is_empty() {
mask
} else {
relative_mask(mask.bounds(container), geometry)
};
Ok((geometry, framing, mask))
});
let (geometry, framing, mask, unsupported) = match appearance {
Ok((geometry, framing, mask)) => (geometry, framing, mask, None),
Err(error) => (container, None, Mask::default(), Some(error)),
};
layers.push(Layer {
id: layer_id,
@ -180,7 +215,7 @@ pub(super) fn parse(identity: String, raw: &Value) -> Result<Snapshot, String> {
geometry,
container,
fit: None,
mask: Default::default(),
mask,
framing,
unsupported,
warning: None,
@ -229,6 +264,10 @@ pub(super) fn prepare(
Target::Program => &screen.program_bank,
};
let mut plan = Plan {
mappings: mappings.to_vec(),
conversion: Default::default(),
conversions: vec![],
discrepancies: vec![],
profile: snapshot.profile,
observed: vec![],
screen: screen.id.clone(),
@ -236,11 +275,10 @@ pub(super) fn prepare(
target,
changes: vec![],
};
let mut locals = BTreeSet::new();
let mut destinations = BTreeSet::new();
for (id, destination) in mappings {
if !locals.insert(id) || !destinations.insert(destination) {
return Err("Map each editor layer to a different device layer.".into());
if !destinations.insert(destination) {
return Err("Map each device destination only once.".into());
}
if !screen.layers.iter().any(|l| &l.id == destination) {
return Err("Destination is not allocated.".into());
@ -248,11 +286,6 @@ pub(super) fn prepare(
let i = (0..layout.layers().len())
.find(|&i| layout.layer_info(i).id == *id)
.ok_or("An editor layer was removed.")?;
if !layout.formats().masks[i].is_empty() {
return Err(format!(
"Layer {destination}: Aquilon masking conversion is not supported yet."
));
}
if layout.formats().layer_fit[i].is_some() {
return Err("Explicit layer fit is currently supported for Midra only. Disable advanced layer fit before sending to Aquilon.".into());
}
@ -261,7 +294,8 @@ pub(super) fn prepare(
let source = &layout.formats().sources[layout.formats().source_for[i]];
let path = snapshot.profile.layer_path(&screen.id, bank, destination);
let layer = value(&snapshot.raw, &path)?;
unmasked(layer)?;
anchor(layer)?;
native_mask(layer)?;
let routed = text(layer, "/source/pp/inputNum")?;
if let Some((native, _)) = source_info(&snapshot.raw, &routed)?
&& native.native != source.native
@ -271,14 +305,8 @@ pub(super) fn prepare(
native.native[0], native.native[1]
));
}
let input = source.input_crop;
let advanced = layout.formats().advanced[i];
let crop = [
input.left + advanced.left,
input.right + advanced.right,
input.top + advanced.top,
input.bottom + advanced.bottom,
];
let crop = [advanced.left, advanced.right, advanced.top, advanced.bottom];
let native = source.native.map(f64::from);
let units = crop
.iter()
@ -311,13 +339,13 @@ pub(super) fn prepare(
native[1] * (1.0 - (units[2] + units[3]) / 65535.0),
];
let scale = (size[0] / retained[0]).min(size[1] / retained[1]);
if (retained[0] * scale - g.width).abs() > 1.0
|| (retained[1] * scale - g.height).abs() > 1.0
{
return Err(
"Quantized crop differs from the visible box by more than one pixel.".into(),
);
}
crate::device_send::record_discrepancy(
&mut plan.discrepancies,
destination,
"visible_size",
&[g.width, g.height],
&[retained[0] * scale, retained[1] * scale],
);
let center = g.center().map(f64::round);
let mut requested = vec![
("position/pp/sizeH", json!(size[0])),
@ -337,6 +365,66 @@ pub(super) fn prepare(
{
requested.push((suffix, json!(units[j] as u32)));
}
let editor_mask = layout.formats().masks[i].validate()?;
let container = Geometry {
x: center[0] - size[0] / 2.0,
y: center[1] - size[1] / 2.0,
width: size[0],
height: size[1],
};
let reveal = layout.formats().mask_bounds(i, g)?;
let mask = if editor_mask.is_empty() {
Mask::default()
} else {
relative_mask(reveal, container)
};
let mut mask_units = [mask.left, mask.right, mask.top, mask.bottom]
.map(|edge| (edge * 65535.0).round() as u32);
mask_units[1] = mask_units[1].min(65535 - mask_units[0]);
mask_units[3] = mask_units[3].min(65535 - mask_units[2]);
if !editor_mask.is_empty() {
let quantized = Mask {
left: mask_units[0] as f64 / 65535.0,
right: mask_units[1] as f64 / 65535.0,
top: mask_units[2] as f64 / 65535.0,
bottom: mask_units[3] as f64 / 65535.0,
..Default::default()
};
let visible = Geometry {
x: center[0] - retained[0] * scale / 2.0,
y: center[1] - retained[1] * scale / 2.0,
width: retained[0] * scale,
height: retained[1] * scale,
};
let expected = relative_mask(reveal, visible).bounds(visible);
let actual = relative_mask(quantized.bounds(container), visible).bounds(visible);
crate::device_send::record_discrepancy(
&mut plan.discrepancies,
destination,
"mask_bounds",
&[expected.x, expected.y, expected.width, expected.height],
&[actual.x, actual.y, actual.width, actual.height],
);
}
for (edge, units) in ["left", "right", "top", "bottom"]
.into_iter()
.zip(mask_units)
{
let full = format!("{path}/cropping/mask/pp/{edge}");
let before = value(&snapshot.raw, &full)?.clone();
let after = json!(units);
if before != after {
plan.changes.push(Change {
path: full
.trim_start_matches('/')
.split('/')
.map(str::to_owned)
.collect(),
before,
after,
});
}
}
for (suffix, after) in requested {
let full = format!("{path}/{suffix}");
let before = value(&snapshot.raw, &full)?.clone();
@ -354,7 +442,7 @@ pub(super) fn prepare(
}
}
plan.changes.sort_by_key(|c| {
!(c.path.iter().any(|p| p == "classic")
!(c.path.iter().any(|p| p == "classic" || p == "mask")
&& c.after
.as_f64()
.zip(c.before.as_f64())
@ -362,3 +450,7 @@ pub(super) fn prepare(
});
Ok(plan)
}
pub(super) fn source_resolution(raw: &Value, layer: &Value) -> Result<Option<[u32; 2]>, String> {
Ok(source_info(raw, &text(layer, "/source/pp/inputNum")?)?.map(|(source, _)| source.native))
}

View File

@ -106,7 +106,6 @@ pub(super) fn parse(identity: String, raw: &Value) -> Result<Snapshot, String> {
let source = crate::formats::Source {
aspect: crate::formats::Aspect::Custom,
native,
input_crop: Default::default(),
};
mode.image(crop.remaining(source.input()?)?, container)?;
Ok((source, crop))
@ -167,3 +166,41 @@ pub(super) fn parse(identity: String, raw: &Value) -> Result<Snapshot, String> {
raw: raw.clone(),
})
}
/// Midra image dimensions already exclude the shared input crop. Verify that
/// controls and signal readback agree before using that processed pixel space.
pub(super) fn cropped_input_resolution(plug: &Value) -> Result<[u32; 2], String> {
let native = crate::formats::resolution_from_values([
number(plug, "/status/signal/pp/imageWidth")?,
number(plug, "/status/signal/pp/imageHeight")?,
])?;
let edge = |key| {
plug.pointer(&format!("/settings/cropping/control/pp/{key}"))
.and_then(Value::as_f64)
.filter(|v| v.is_finite() && *v >= 0.)
.ok_or_else(|| {
"Input crop status unavailable; refresh before switching input.".to_owned()
})
};
let crop = crate::formats::Crop {
left: edge("left")?,
right: edge("right")?,
top: edge("top")?,
bottom: edge("bottom")?,
};
if crop != crate::formats::Crop::default() {
let full = [
number(plug, "/status/signal/pp/aspectWidth")?,
number(plug, "/status/signal/pp/aspectHeight")?,
];
let retained = crop.remaining(full)?;
if retained
.iter()
.zip(native)
.any(|(expected, actual)| (*expected - actual as f64).abs() > 1.)
{
return Err("Input crop has not settled; refresh before switching input.".into());
}
}
Ok(native)
}

View File

@ -150,6 +150,121 @@ pub(super) fn fetch(
};
collect(&mut connection, identity)
}
pub(super) fn input_settings(
address: SocketAddr,
snapshot: &mut Snapshot,
input: u32,
) -> Result<(), String> {
let root = format!("/device/inputList/items/IN_{input}");
let plug = snapshot
.raw
.pointer(&format!("{root}/status/pp/plug"))
.and_then(Value::as_str)
.ok_or("Input plug unavailable")?;
if plug.is_empty() || !plug.bytes().all(|b| b.is_ascii_digit()) {
return Err("Invalid input plug".into());
}
let base = format!("{root}/plugList/items/{plug}");
let mut paths = Vec::new();
for (group, keys) in [
(
"status/signal/pp",
&[
"aspectWidth",
"aspectHeight",
"imageWidth",
"imageHeight",
"isValid",
][..],
),
(
"settings/aspect/pp",
&["signal", "transformTo", "layerFill", "customRatio"][..],
),
(
"settings/cropping/control/pp",
&["left", "right", "top", "bottom"][..],
),
(
"settings/cropping/status/pp",
&["left", "right", "top", "bottom"][..],
),
("settings/pp", &["xUpdate"][..]),
("control/pp", &["enableCropFinder"][..]),
(
"settings/color/pp",
&[
"brightness",
"contrast",
"saturation",
"hue",
"gainR",
"gainG",
"gainB",
"offsetR",
"offsetG",
"offsetB",
][..],
),
(
"settings/processing/pp",
&["sharpness", "pulldown22", "pulldown32"][..],
),
("settings/keying/control/pp", &["mode"][..]),
("settings/keying/status/pp", &["modeValidity"][..]),
(
"settings/keying/chroma/pp",
&[
"hue",
"transparency",
"colorCorrection",
"foreground",
"background",
][..],
),
(
"settings/keying/luma/pp",
&["luma", "foreground", "transparency", "invert"][..],
),
("settings/correctionLut/control/pp", &["mode", "source"][..]),
(
"settings/correctionLut/status/pp",
&["isEnabled", "sourceValidity"][..],
),
] {
for key in keys {
paths.push(format!("{base}/{group}/{key}"));
}
}
paths.push(format!("{root}/status/pp/plug"));
let stream =
TcpStream::connect_timeout(&address, Duration::from_secs(3)).map_err(|e| e.to_string())?;
stream
.set_read_timeout(Some(Duration::from_millis(250)))
.map_err(|e| e.to_string())?;
stream
.set_write_timeout(Some(Duration::from_secs(3)))
.map_err(|e| e.to_string())?;
let cancelled = AtomicBool::new(false);
let mut reader = Connection {
reader: BufReader::new(stream),
cancelled: &cancelled,
deadline: Instant::now() + Duration::from_secs(30),
bytes: 0,
};
let values = reader.get(&paths)?;
if reader.get(&paths)? != values {
return Err("Input changed during read; retry".into());
}
if values.last().and_then(Value::as_str) != Some(plug) {
return Err("Input plug changed during read; retry".into());
}
for (path, value) in paths.iter().zip(values) {
set(&mut snapshot.raw, path, value);
}
Ok(())
}
fn set(raw: &mut Value, path: &str, value: Value) {
let mut node = raw;
for key in path.trim_start_matches('/').split('/') {

View File

@ -50,6 +50,128 @@ pub fn inputs(snapshot: &Snapshot) -> Vec<Input> {
inputs
}
/// How the PNG represents the applied input crop.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CaptureFraming {
/// Aquilon retains full-source coordinates, blanking the cropped edges.
FullFrame,
/// Midra returns only the retained image, without the removed edges.
Cropped,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct CaptureGeometry {
pub native: [f64; 2],
pub crop: crate::formats::Crop,
pub framing: CaptureFraming,
}
/// Interpret device readback, never an unsent editor draft. Callers must also
/// verify that input state stayed unchanged across the capture request.
pub fn capture_geometry(
snapshot: &Snapshot,
input: u32,
image_size: [u32; 2],
) -> Result<CaptureGeometry, String> {
use crate::device::Profile;
let draft = crate::device_inputs::InputDraft::read(snapshot, input)?;
let native = draft.native.ok_or("No valid input signal dimensions")?;
let prefix = if snapshot.profile == Profile::Aquilon6 {
"IN"
} else {
"INPUT"
};
let base = format!(
"/device/inputList/items/{prefix}_{input}/plugList/items/{}",
draft.plug
);
let plug = snapshot
.raw
.pointer(&base)
.ok_or("Input plug unavailable")?;
if plug
.pointer("/control/pp/enableCropFinder")
.and_then(serde_json::Value::as_bool)
== Some(true)
{
return Err("Disable Crop Finder to preview the applied input crop".into());
}
let (crop, framing) = match snapshot.profile {
Profile::Aquilon6 => {
let status = plug
.pointer("/settings/cropping/status/pp")
.ok_or("Applied input crop unavailable")?;
let edge = |key: &str| {
status
.get(key)
.and_then(serde_json::Value::as_f64)
.ok_or("Applied crop edge unavailable")
};
(
crate::formats::Crop {
left: edge("left")?,
right: edge("right")?,
top: edge("top")?,
bottom: edge("bottom")?,
},
CaptureFraming::FullFrame,
)
}
Profile::Midra4k => {
// Midra exposes crop controls plus the resulting image dimensions,
// not Aquilon's separate cropping/status object.
let controls = plug
.pointer("/settings/cropping/control/pp")
.ok_or("Input crop unavailable")?;
let edge = |key: &str| {
controls
.get(key)
.and_then(serde_json::Value::as_f64)
.ok_or("Crop edge unavailable")
};
(
crate::formats::Crop {
left: edge("left")?,
right: edge("right")?,
top: edge("top")?,
bottom: edge("bottom")?,
},
CaptureFraming::Cropped,
)
}
};
let retained = crop.remaining(native)?;
let expected = match framing {
CaptureFraming::FullFrame => native,
CaptureFraming::Cropped => {
for (key, expected) in [("imageWidth", retained[0]), ("imageHeight", retained[1])] {
let actual = plug
.pointer(&format!("/status/signal/pp/{key}"))
.and_then(serde_json::Value::as_f64)
.ok_or("Applied image dimensions unavailable")?;
if (actual - expected).abs() > 1.0 {
return Err(
"Input crop has not settled; waiting for matching image dimensions".into(),
);
}
}
retained
}
};
if image_size.contains(&0) {
return Err("Empty capture image".into());
}
let longest = usize::from(expected[1] > expected[0]);
let scale = image_size[longest] as f64 / expected[longest];
if (0..2).any(|axis| (image_size[axis] as f64 - expected[axis] * scale).abs() > 1.1) {
return Err("Capture dimensions do not match the applied input crop".into());
}
Ok(CaptureGeometry {
native,
crop,
framing,
})
}
/// A single on-demand GET; no routing, capture-library or device-setting writes.
pub fn capture(host: &str, input: u32) -> Result<Vec<u8>, String> {
capture_for(host, crate::device::Profile::Midra4k, input)
@ -155,6 +277,87 @@ mod tests {
assert!(capture("not a host", 1).is_err());
assert!(capture("127.0.0.1", 0).is_err());
}
fn geometry_snapshot(profile: crate::device::Profile, crop: [f64; 4]) -> Snapshot {
let [left, right, top, bottom] = crop;
let prefix = if profile == crate::device::Profile::Aquilon6 {
"IN"
} else {
"INPUT"
};
Snapshot {
profile,
identity: "capture geometry fixture".into(),
screens: vec![],
raw: serde_json::json!({"device":{"inputList":{"items":{format!("{prefix}_6"):{
"status":{"pp":{"isAvailable":true,"plug":"1"}},
"plugList":{"items":{"1":{
"control":{"pp":{"enableCropFinder":false}},
"status":{"signal":{"pp":{"isValid":true,"aspectWidth":1920,"aspectHeight":1080,"imageWidth":1920.-left-right,"imageHeight":1080.-top-bottom}}},
"settings":{"cropping":{
"control":{"pp":{"left":left,"right":right,"top":top,"bottom":bottom,"predefined":"NONE"}},
"status":{"pp":{"left":left,"right":right,"top":top,"bottom":bottom}}
}}
}}}
}}}}}),
}
}
#[test]
fn midra_capture_uses_retained_dimensions_including_portrait_and_pixel_rounding() {
use crate::device::Profile;
for (crop, size) in [
([0.; 4], [512, 288]),
([1157., 0., 0., 0.], [361, 512]),
([279., 0., 0., 338.], [512, 231]),
] {
let mut snapshot = geometry_snapshot(Profile::Midra4k, crop);
// Actual Eikos 4K state has no cropping/status subtree.
snapshot
.raw
.pointer_mut("/device/inputList/items/INPUT_6/plugList/items/1/settings/cropping")
.unwrap()
.as_object_mut()
.unwrap()
.remove("status");
let geometry = capture_geometry(&snapshot, 6, size).unwrap();
assert_eq!(geometry.framing, CaptureFraming::Cropped);
assert_eq!(geometry.native, [1920., 1080.]);
assert_eq!(geometry.crop.left, crop[0]);
}
}
#[test]
fn aquilon_capture_keeps_full_frame_coordinates_and_applied_status() {
let mut snapshot =
geometry_snapshot(crate::device::Profile::Aquilon6, [480., 480., 270., 270.]);
// Pending controls do not describe the captured pixels.
snapshot.raw["device"]["inputList"]["items"]["IN_6"]["plugList"]["items"]["1"]["settings"]
["cropping"]["control"]["pp"]["left"] = serde_json::json!(0);
let geometry = capture_geometry(&snapshot, 6, [512, 288]).unwrap();
assert_eq!(geometry.framing, CaptureFraming::FullFrame);
assert_eq!(geometry.crop.left, 480.);
assert!(capture_geometry(&snapshot, 6, [361, 512]).is_err());
}
#[test]
fn capture_geometry_rejects_unsettled_crop_missing_edges_finder_and_stale_image() {
let snapshot = geometry_snapshot(crate::device::Profile::Midra4k, [1157., 0., 0., 0.]);
assert!(capture_geometry(&snapshot, 6, [512, 288]).is_err());
assert!(capture_geometry(&snapshot, 6, [0, 512]).is_err());
for (path, value) in [
("status/signal/pp/imageWidth", serde_json::json!(1920)),
("status/signal/pp/isValid", serde_json::json!(false)),
("settings/cropping/control/pp/left", serde_json::Value::Null),
("control/pp/enableCropFinder", serde_json::json!(true)),
] {
let mut changed = snapshot.clone();
*changed
.raw
.pointer_mut(&format!(
"/device/inputList/items/INPUT_6/plugList/items/1/{path}"
))
.unwrap() = value;
assert!(capture_geometry(&changed, 6, [361, 512]).is_err(), "{path}");
}
}
#[test]
fn input_choices_use_available_hardware_and_current_plug_signal() {
let snapshot = Snapshot {

View File

@ -0,0 +1,705 @@
//! Adapter-aware input-owned preprocessing drafts. No layer crop or routing mutations.
use crate::{
device::{Profile, Snapshot},
device_send::Change,
formats::Crop,
};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Clone, Debug)]
pub enum Kind {
Number(i64, i64),
Choice(Vec<String>),
Toggle,
}
#[derive(Clone, Debug)]
pub struct Field {
pub path: String,
pub label: String,
pub group: &'static str,
pub kind: Kind,
}
#[derive(Clone, Debug)]
pub struct InputDraft {
pub input: u32,
pub profile: Profile,
pub plug: String,
pub native: Option<[f64; 2]>,
pub fields: Vec<Field>,
pub values: BTreeMap<String, Value>,
original: BTreeMap<String, Value>,
observed: Vec<(String, Value)>,
kept_groups: BTreeSet<String>,
}
impl InputDraft {
pub fn read(snapshot: &Snapshot, input: u32) -> Result<Self, String> {
let aquilon = snapshot.profile == Profile::Aquilon6;
if !(1..=snapshot.profile.input_limit()).contains(&input) {
return Err("Invalid device input.".into());
}
let prefix = if aquilon { "IN" } else { "INPUT" };
let root = format!("/device/inputList/items/{prefix}_{input}");
let item = snapshot.raw.pointer(&root).ok_or("Input unavailable")?;
if item
.pointer("/status/pp/isAvailable")
.and_then(Value::as_bool)
!= Some(true)
{
return Err("Input unavailable".into());
}
let plug = item
.pointer("/status/pp/plug")
.and_then(Value::as_str)
.ok_or("Active plug unavailable")?
.to_owned();
if plug.is_empty() || !plug.bytes().all(|b| b.is_ascii_digit()) {
return Err("Invalid input plug".into());
}
let base = format!("{root}/plugList/items/{plug}");
let p = snapshot.raw.pointer(&base).ok_or("Plug unavailable")?;
let dimensions = ["imageWidth", "imageHeight"].map(|key| {
p.pointer(&format!(
"/status/signal/pp/{}",
key.replace("image", "aspect")
))
.or_else(|| p.pointer(&format!("/status/signal/pp/{key}")))
.and_then(Value::as_f64)
.unwrap_or(0.0)
});
let native = dimensions
.iter()
.all(|v| v.is_finite() && *v >= 1.0)
.then_some(dimensions)
.filter(|_| {
p.pointer("/status/signal/pp/isValid")
.and_then(Value::as_bool)
== Some(true)
});
let mut fields = Vec::new();
let mut add = |suffix: &str, label: &str, group, kind| {
if let Some(value) = p.pointer(&format!("/{suffix}")) {
let valid = match &kind {
Kind::Number(_, _) => value.as_i64().is_some(),
Kind::Choice(_) => value.is_string(),
Kind::Toggle => value.is_boolean(),
};
if valid {
fields.push(Field {
path: format!("{base}/{suffix}"),
label: label.into(),
group,
kind,
});
}
}
};
let choices =
|options: &[&str]| Kind::Choice(options.iter().map(|v| (*v).into()).collect());
for (key, label, options) in [
(
"signal",
"Content ratio",
&[
"NATIVE", "5_4", "4_3", "16_10", "15_9", "16_9", "21_9", "256_135", "64_27",
][..],
),
(
"transformTo",
"Transform to",
&[
if aquilon {
"KEEP_INPUT_RATIO"
} else {
"SIGNAL"
},
"5_4",
"4_3",
"16_10",
"15_9",
"16_9",
"21_9",
"CUSTOM",
][..],
),
(
"layerFill",
"Layer fill option",
&["LAYER_SETTING", "1_1", "CENTERED", "FULLSCREEN", "CROPPED"][..],
),
] {
add(
&format!("settings/aspect/pp/{key}"),
label,
"Aspect",
choices(
&options
.iter()
.copied()
.filter(|v| !aquilon || !matches!(*v, "256_135" | "LAYER_SETTING"))
.collect::<Vec<_>>(),
),
);
}
add(
"settings/aspect/pp/customRatio",
"Custom ratio",
"Aspect",
Kind::Number(250, 10000),
);
add(
"settings/cropping/control/pp/predefined",
"Crop preset",
"Crop",
choices(&[
"NONE",
"LETTERBOX_1_78",
"LETTERBOX_1_85",
"LETTERBOX_2_35",
"PILLARBOX_1_33",
]),
);
for edge in ["left", "right", "top", "bottom"] {
add(
&format!("settings/cropping/control/pp/{edge}"),
edge,
"Crop",
Kind::Number(
0,
if aquilon && matches!(edge, "left" | "right") {
32767
} else {
8191
},
),
);
}
for (key, label) in [
("brightness", "Brightness"),
("contrast", "Contrast"),
("saturation", "Saturation"),
("hue", "Hue"),
("gainR", "Red contrast"),
("gainG", "Green contrast"),
("gainB", "Blue contrast"),
("offsetR", "Red brightness"),
("offsetG", "Green brightness"),
("offsetB", "Blue brightness"),
] {
add(
&format!("settings/color/pp/{key}"),
label,
"Color",
match (aquilon, key) {
(true, "hue") => Kind::Number(90, 270),
(true, _) => Kind::Number(0, 255),
(false, "hue") => Kind::Number(-90, 90),
(false, _) => Kind::Number(-128, 127),
},
);
}
add(
"settings/processing/pp/sharpness",
"Sharpness",
"Processing",
choices(&["LOW", "MEDIUM", "HIGH"]),
);
for key in ["pulldown22", "pulldown32"] {
add(
&format!("settings/processing/pp/{key}"),
key,
"Processing",
Kind::Toggle,
);
}
if aquilon
|| item
.pointer("/status/keying/pp/isAvailable")
.and_then(Value::as_bool)
== Some(true)
{
let mut modes = vec!["DISABLE", "CHROMA", "LUMA"];
if item
.pointer("/status/keying/cutNFill/pp/isAvailable")
.and_then(Value::as_bool)
== Some(true)
{
modes.push("CUT_AND_FILL");
}
if aquilon {
let available = p
.pointer("/settings/keying/status/pp/modeValidity")
.and_then(Value::as_array);
modes.retain(|mode| {
available.is_some_and(|values| values.iter().any(|v| v.as_str() == Some(mode)))
});
}
add(
"settings/keying/control/pp/mode",
"Keying mode",
"Keying",
choices(&modes),
);
for (kind, key, max) in [
("chroma", "hue", 360),
("chroma", "transparency", 255),
("chroma", "colorCorrection", 255),
("chroma", "foreground", 255),
("chroma", "background", 255),
("luma", "luma", 1023),
("luma", "foreground", 255),
("luma", "transparency", 255),
] {
add(
&format!("settings/keying/{kind}/pp/{key}"),
&format!("{kind}: {key}"),
"Keying",
Kind::Number(0, max),
);
}
add(
"settings/keying/luma/pp/invert",
"Invert luma key",
"Keying",
Kind::Toggle,
);
}
// Use the device's published validity list for resource-dependent LUT selection.
if p.pointer("/settings/correctionLut/status/pp/isEnabled")
.and_then(Value::as_bool)
== Some(true)
{
add(
"settings/correctionLut/control/pp/mode",
"Correction mode",
"LUT",
choices(&["MANUAL", "LUT"]),
);
if let Some(list) = p
.pointer("/settings/correctionLut/status/pp/sourceValidity")
.and_then(Value::as_array)
{
let options = list
.iter()
.filter_map(Value::as_str)
.map(str::to_owned)
.collect();
add(
"settings/correctionLut/control/pp/source",
"Correction LUT",
"LUT",
Kind::Choice(options),
);
}
}
let original: BTreeMap<_, _> = fields
.iter()
.map(|f| {
(
f.path.clone(),
snapshot.raw.pointer(&f.path).unwrap().clone(),
)
})
.collect();
let mut observed = vec![(
format!("{root}/status/pp"),
item.pointer("/status/pp").unwrap().clone(),
)];
for suffix in [
"status/signal/pp",
"settings/cropping/control/pp",
"settings/cropping/status/pp",
"settings/aspect/pp",
"settings/keying/control/pp",
"settings/correctionLut/status/pp",
] {
if let Some(value) = p.pointer(&format!("/{suffix}")) {
observed.push((format!("{base}/{suffix}"), value.clone()));
}
}
Ok(Self {
input,
profile: snapshot.profile,
plug,
native,
fields,
values: original.clone(),
original,
observed,
kept_groups: BTreeSet::new(),
})
}
pub fn dirty(&self) -> bool {
self.fields.iter().any(|f| {
!self.keeps_group(f.group) && self.values.get(&f.path) != self.original.get(&f.path)
})
}
pub fn keeps_group(&self, group: &str) -> bool {
self.kept_groups.contains(group)
}
/// Keep means no writes, never restoring stale device values.
pub fn keep_group(&mut self, group: &str, keep: bool) {
if keep {
self.kept_groups.insert(group.to_owned());
} else {
self.kept_groups.remove(group);
}
self.restore_kept_groups();
}
pub fn restore_kept_groups(&mut self) {
for field in &self.fields {
if self.keeps_group(field.group) {
self.values
.insert(field.path.clone(), self.original[&field.path].clone());
}
}
}
pub fn reset(&mut self) {
self.values = self.original.clone();
}
pub fn crop(&self) -> Crop {
let value = |edge| {
self.values
.get(&self.crop_path(edge))
.and_then(Value::as_f64)
.unwrap_or(0.0)
};
Crop {
left: value("left"),
right: value("right"),
top: value("top"),
bottom: value("bottom"),
}
}
fn crop_path(&self, edge: &str) -> String {
format!(
"/device/inputList/items/{}_{}/plugList/items/{}/settings/cropping/control/pp/{edge}",
if self.profile == Profile::Aquilon6 {
"IN"
} else {
"INPUT"
},
self.input,
self.plug
)
}
pub fn set_crop(&mut self, crop: Crop) -> Result<(), String> {
let crop = Crop {
left: crop.left.round(),
right: crop.right.round(),
top: crop.top.round(),
bottom: crop.bottom.round(),
};
crop.remaining(self.native.ok_or("No valid input dimensions")?)?;
for (edge, v) in [
("left", crop.left),
("right", crop.right),
("top", crop.top),
("bottom", crop.bottom),
] {
let max = if self.profile == Profile::Aquilon6 && matches!(edge, "left" | "right") {
32767.
} else {
8191.
};
if !(0.0..=max).contains(&v) {
return Err("Input crop exceeds device range".into());
}
}
if ["left", "right", "top", "bottom"]
.iter()
.any(|edge| !self.values.contains_key(&self.crop_path(edge)))
{
return Err("Input crop field unavailable".into());
}
for (edge, v) in [
("left", crop.left),
("right", crop.right),
("top", crop.top),
("bottom", crop.bottom),
] {
let path = self.crop_path(edge);
if !self.values.contains_key(&path) {
return Err("Input crop field unavailable".into());
}
self.values.insert(path, json!(v as i64));
}
let path = self.crop_path("predefined");
if self.values.contains_key(&path) {
self.values.insert(path, json!("NONE"));
}
Ok(())
}
pub fn zoom_crop(&mut self, factor: f64, pivot: [f64; 2]) -> Result<(), String> {
if !factor.is_finite()
|| factor <= 0.0
|| pivot
.iter()
.any(|p| !p.is_finite() || !(0.0..=1.0).contains(p))
{
return Err("Invalid crop zoom/pivot".into());
}
let native = self.native.ok_or("No valid input dimensions")?;
let c = self.crop();
let retained = c.remaining(native)?;
let size = [
(retained[0] / factor).clamp(1.0, native[0]),
(retained[1] / factor).clamp(1.0, native[1]),
];
let left = (c.left + (retained[0] - size[0]) * pivot[0]).clamp(0.0, native[0] - size[0]);
let top = (c.top + (retained[1] - size[1]) * pivot[1]).clamp(0.0, native[1] - size[1]);
self.set_crop(Crop {
left,
top,
right: native[0] - left - size[0],
bottom: native[1] - top - size[1],
})
}
pub fn changes(&self, fresh: &Snapshot) -> Result<Vec<Change>, String> {
if fresh.profile != self.profile {
return Err("Device family changed".into());
}
for (path, value) in &self.observed {
if fresh.raw.pointer(path) != Some(value) {
return Err("Input signal, plug or preprocessing changed. Refresh and review before sending.".into());
}
}
if self.values.keys().ne(self.original.keys()) {
return Err("Incomplete input draft".into());
}
let mut changes = Vec::new();
for (path, after) in &self.values {
let before = self.original.get(path).ok_or("Unknown input setting")?;
if after == before {
continue;
}
let field = self
.fields
.iter()
.find(|f| &f.path == path)
.ok_or("Unknown input setting")?;
if self.keeps_group(field.group) {
continue;
}
let valid = match &field.kind {
Kind::Number(min, max) => {
after.as_i64().is_some_and(|v| (*min..=*max).contains(&v))
}
Kind::Choice(options) => after
.as_str()
.is_some_and(|v| options.iter().any(|o| o == v)),
Kind::Toggle => after.is_boolean(),
};
if !valid {
return Err(format!("Invalid {}", field.label));
}
if fresh.raw.pointer(path) != Some(before) {
return Err(format!("{} changed on device; refresh first", field.label));
}
changes.push(Change {
path: path
.trim_start_matches('/')
.split('/')
.map(str::to_owned)
.collect(),
before: before.clone(),
after: after.clone(),
});
}
if changes
.iter()
.any(|c| c.path.iter().any(|p| p == "cropping"))
{
self.crop().remaining(
self.native
.ok_or("A valid input signal is required to change crop")?,
)?;
}
changes.sort_by_key(|c| {
!(c.path.iter().any(|p| p == "cropping")
&& c.after
.as_i64()
.zip(c.before.as_i64())
.is_some_and(|(a, b)| a < b))
});
Ok(changes)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn snapshot() -> Snapshot {
Snapshot {
identity: "test".into(),
profile: Profile::Midra4k,
screens: vec![],
raw: json!({"device":{"inputList":{"items":{"INPUT_1":{
"status":{"pp":{"isAvailable":true,"plug":"1"}},
"plugList":{"items":{"1":{
"status":{"signal":{"pp":{"isValid":true,"imageWidth":1920,"imageHeight":1080}}},
"settings":{
"cropping":{"control":{"pp":{"left":0,"right":0,"top":0,"bottom":0,"predefined":"NONE","xUpdate":true}}},
"aspect":{"pp":{"signal":"NATIVE","transformTo":"SIGNAL","customRatio":1778,"layerFill":"LAYER_SETTING"}},
"color":{"pp":{"brightness":0,"hue":0}}
}
}}}
}}}}}),
}
}
#[test]
fn kept_categories_never_send_and_discard_their_edits() {
let s = snapshot();
let mut d = InputDraft::read(&s, 1).unwrap();
let brightness = d
.fields
.iter()
.find(|f| f.label == "Brightness")
.unwrap()
.path
.clone();
d.values.insert(brightness.clone(), json!(10));
d.keep_group("Color", true);
assert_eq!(d.values[&brightness], json!(0));
assert!(!d.dirty());
// Even a stale undo value cannot bypass the send boundary.
d.values.insert(brightness.clone(), json!(20));
assert!(d.changes(&s).unwrap().is_empty());
assert!(!d.dirty());
d.zoom_crop(2., [0.5, 0.5]).unwrap();
assert!(
d.changes(&s)
.unwrap()
.iter()
.all(|c| !c.path.iter().any(|p| p == "color"))
);
d.restore_kept_groups();
d.keep_group("Color", false);
d.values.insert(brightness, json!(15));
assert!(
d.changes(&s)
.unwrap()
.iter()
.any(|c| c.path.iter().any(|p| p == "color"))
);
d.keep_group("Crop", true);
assert_eq!(d.crop(), Crop::default());
d.reset();
assert!(!d.dirty());
assert!(d.keeps_group("Crop"));
}
#[test]
fn aquilon_uses_aspect_bounds_and_unsigned_color_ranges() {
let mut s = snapshot();
s.profile = Profile::Aquilon6;
let mut input = s.raw["device"]["inputList"]["items"]["INPUT_1"].take();
let plug = &mut input["plugList"]["items"]["1"];
plug["status"]["signal"]["pp"]["aspectWidth"] = json!(3840);
plug["status"]["signal"]["pp"]["aspectHeight"] = json!(2160);
plug["settings"]["aspect"]["pp"]["transformTo"] = json!("KEEP_INPUT_RATIO");
plug["settings"]["color"]["pp"]["brightness"] = json!(128);
plug["settings"]["color"]["pp"]["hue"] = json!(180);
s.raw["device"]["inputList"]["items"]["IN_1"] = input;
let mut d = InputDraft::read(&s, 1).unwrap();
assert_eq!(d.native, Some([3840., 2160.]));
let path = d
.fields
.iter()
.find(|f| f.label == "Brightness")
.unwrap()
.path
.clone();
d.values.insert(path.clone(), json!(255));
assert!(d.changes(&s).is_ok());
d.values.insert(path, json!(-1));
assert!(d.changes(&s).is_err());
d.reset();
d.zoom_crop(2., [0.5, 0.5]).unwrap();
assert_eq!(d.crop().left, 960.);
}
#[test]
fn crop_zoom_anchors_and_rounds_native_pixels() {
let s = snapshot();
let mut d = InputDraft::read(&s, 1).unwrap();
d.zoom_crop(2., [0.5, 0.5]).unwrap();
assert_eq!(
d.crop(),
Crop {
left: 480.,
right: 480.,
top: 270.,
bottom: 270.
}
);
assert_eq!(d.changes(&s).unwrap().len(), 4);
d.reset();
d.zoom_crop(2., [0., 1.]).unwrap();
assert_eq!(
d.crop(),
Crop {
left: 0.,
right: 960.,
top: 540.,
bottom: 0.
}
);
d.zoom_crop(0.5, [0., 1.]).unwrap();
assert!(!d.dirty());
}
#[test]
fn invalid_or_incomplete_crop_is_atomic() {
let mut d = InputDraft::read(&snapshot(), 1).unwrap();
let before = d.values.clone();
assert!(
d.set_crop(Crop {
left: 1920.,
..Crop::default()
})
.is_err()
);
assert_eq!(before, d.values);
d.values.remove(&d.crop_path("bottom"));
let before = d.values.clone();
assert!(d.zoom_crop(2., [0.5, 0.5]).is_err());
assert_eq!(before, d.values);
}
#[test]
fn preflight_rejects_stale_signal_plug_crop_and_changed_value() {
let s = snapshot();
let mut d = InputDraft::read(&s, 1).unwrap();
let key = d
.fields
.iter()
.find(|f| f.label == "Brightness")
.unwrap()
.path
.clone();
d.values.insert(key.clone(), json!(12));
assert_eq!(d.changes(&s).unwrap().len(), 1);
for (path, value) in [
("/device/inputList/items/INPUT_1/status/pp/plug", json!("2")),
(
"/device/inputList/items/INPUT_1/plugList/items/1/status/signal/pp/imageWidth",
json!(1280),
),
(&d.crop_path("left"), json!(30)),
(&key, json!(1)),
] {
let mut fresh = s.clone();
*fresh.raw.pointer_mut(path).unwrap() = value;
assert!(d.changes(&fresh).is_err(), "{path}");
}
d.values.insert(key, json!(128));
assert!(d.changes(&s).is_err());
}
#[test]
fn unavailable_input_and_unknown_family_are_not_editable() {
let mut s = snapshot();
s.profile = Profile::Aquilon6;
assert!(InputDraft::read(&s, 1).is_err());
s.profile = Profile::Midra4k;
s.raw["device"]["inputList"]["items"]["INPUT_1"]["status"]["pp"]["isAvailable"] =
json!(false);
assert!(InputDraft::read(&s, 1).is_err());
}
}

View File

@ -0,0 +1,56 @@
//! Directional routing, independent of controls and device protocol paths.
use crate::DeviceLink;
use serde::{Deserialize, Serialize};
/// Connection scope is explicit, but only the current connection exists today.
/// A future saved-connection identity can be added without changing fan-out shape.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionTarget {
Current,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SendDestination {
pub connection: ConnectionTarget,
pub layer: DeviceLink,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SendMapping {
pub destinations: Vec<SendDestination>,
}
impl SendMapping {
pub fn linked(link: Option<DeviceLink>) -> Self {
Self {
destinations: link
.into_iter()
.map(|layer| SendDestination {
connection: ConnectionTarget::Current,
layer,
})
.collect(),
}
}
pub fn validate(&self) -> Result<(), String> {
for (i, destination) in self.destinations.iter().enumerate() {
destination.layer.validate()?;
if self.destinations[..i].contains(destination) {
return Err("A send mapping contains a duplicate destination.".into());
}
}
Ok(())
}
pub fn current_links(&self) -> impl Iterator<Item = &DeviceLink> {
self.destinations
.iter()
.map(|destination| match destination.connection {
ConnectionTarget::Current => &destination.layer,
})
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,96 @@
//! Bounded local diagnostics for transfer approximations; never a condition for sending.
use crate::device_send::Plan;
use serde_json::json;
use std::{io::Write, path::Path, time::SystemTime};
const LIMIT: u64 = 1024 * 1024;
pub(crate) fn record(plan: &Plan, success: bool) {
if plan.discrepancies.is_empty() {
return;
}
let Some(dirs) = directories::ProjectDirs::from("org", "beffroi", "midra-layout") else {
return;
};
let entry = json!({
"version": 1,
"unix_seconds": SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap_or_default().as_secs(),
"application_version": env!("CARGO_PKG_VERSION"),
"profile": format!("{:?}", plan.profile),
"screen": plan.screen, "bank": plan.bank, "target": format!("{:?}", plan.target),
"verified": success, "discrepancies": plan.discrepancies,
});
if let Err(error) = append(&dirs.config_dir().join("logs"), &entry) {
eprintln!("Cannot save transfer discrepancy log: {error}");
}
}
fn append(directory: &Path, entry: &serde_json::Value) -> std::io::Result<()> {
std::fs::create_dir_all(directory)?;
let path = directory.join("device-transfers.jsonl");
let mut bytes = serde_json::to_vec(entry)?;
bytes.push(b'\n');
if bytes.len() as u64 > LIMIT {
return Err(std::io::Error::other("Transfer log entry too large"));
}
if std::fs::metadata(&path).is_ok_and(|m| m.len() + bytes.len() as u64 > LIMIT) {
let previous = directory.join("device-transfers.previous.jsonl");
match std::fs::remove_file(&previous) {
Ok(()) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(error),
}
std::fs::rename(&path, previous)?;
}
std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(path)?
.write_all(&bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn documented_log_example_has_supported_units_and_version() {
let entry: serde_json::Value = serde_json::from_str(include_str!(
"../../../docs/interfaces/device-transfer-log-v1.example.jsonl"
))
.unwrap();
assert_eq!(entry["version"], 1);
let discrepancy = &entry["discrepancies"][0];
assert_eq!(discrepancy["field"], "mask_bounds");
assert_eq!(discrepancy["actual"].as_array().unwrap().len(), 4);
assert!(
(discrepancy["actual"][0].as_f64().unwrap()
- discrepancy["requested"][0].as_f64().unwrap())
.abs()
> 1.
);
}
#[test]
fn logs_are_json_lines_and_rotate_to_one_previous_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("device-transfers.jsonl");
append(dir.path(), &json!({"version":1,"requested": [10.25,20.0]})).unwrap();
let line = std::fs::read_to_string(&path).unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&line).unwrap()["version"],
1
);
std::fs::OpenOptions::new()
.write(true)
.open(&path)
.unwrap()
.set_len(LIMIT)
.unwrap();
append(dir.path(), &json!({"version":1})).unwrap();
assert_eq!(
std::fs::metadata(dir.path().join("device-transfers.previous.jsonl"))
.unwrap()
.len(),
LIMIT
);
assert!(std::fs::metadata(&path).unwrap().len() < LIMIT);
assert!(append(dir.path(), &json!("x".repeat(LIMIT as usize))).is_err());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,391 @@
use super::*;
use canvas_pilot::reference_document::Document;
use std::{
collections::VecDeque,
sync::mpsc::{self, Receiver},
};
type Job<T> = Option<Receiver<Result<T, String>>>;
#[derive(Default)]
pub(super) struct DocumentReferenceUi {
queue: VecDeque<egui::DroppedFile>,
file: Option<egui::DroppedFile>,
loading: Job<Document>,
rendering: Job<super::super::reference::Reference>,
document: Option<Document>,
preview: Option<super::super::reference::Reference>,
page: usize,
resolution: u32,
layout_only: bool,
error: String,
}
fn poll<T>(job: &mut Job<T>) -> Option<Result<T, String>> {
match job.as_ref()?.try_recv() {
Ok(result) => {
*job = None;
Some(result)
}
Err(mpsc::TryRecvError::Empty) => None,
Err(mpsc::TryRecvError::Disconnected) => {
*job = None;
Some(Err("Document reader stopped. Please try again.".into()))
}
}
}
impl DocumentReferenceUi {
pub(super) fn enqueue(&mut self, file: egui::DroppedFile) -> Result<(), String> {
if self.queue.len() >= 32 {
return Err("Up to 32 reference documents can be queued.".into());
}
self.queue.push_back(file);
Ok(())
}
fn load(&mut self, ctx: &egui::Context) {
let Some(file) = self.file.clone() else {
return;
};
let layout_only = self.layout_only;
self.preview = None;
self.document = None;
self.rendering = None;
self.error.clear();
let (tx, rx) = mpsc::channel();
self.loading = Some(rx);
let ctx = ctx.clone();
std::thread::spawn(move || {
let result = (|| {
let name = file
.path
.as_deref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or(file.name);
let bytes = if let Some(bytes) = file.bytes {
bytes.to_vec()
} else {
canvas_pilot::reference_document::read(
file.path.as_deref().ok_or("Missing document path")?,
)?
};
Document::open(bytes, &name, layout_only)
})();
let _ = tx.send(result);
ctx.request_repaint();
});
}
fn render(&mut self, ctx: &egui::Context) {
let Some(document) = self.document.clone() else {
return;
};
self.preview = None;
self.error.clear();
let page = self.page;
let resolution = self.resolution;
let (tx, rx) = mpsc::channel();
self.rendering = Some(rx);
let ctx = ctx.clone();
std::thread::spawn(move || {
let result = document.render(page, resolution).and_then(|bytes| {
let mut reference = super::super::reference::Reference::load(
&ctx,
&egui::DroppedFile {
name: format!("{} · {}", document.name, document.pages[page]),
bytes: Some(bytes.into()),
..Default::default()
},
)?;
reference.preserve_ratio = true;
Ok(reference)
});
let _ = tx.send(result);
ctx.request_repaint();
});
}
fn close(&mut self) {
self.file = None;
self.document = None;
self.preview = None;
self.loading = None;
self.rendering = None;
self.error.clear();
}
pub(super) fn show(
&mut self,
ctx: &egui::Context,
) -> Option<super::super::reference::Reference> {
if self.file.is_none()
&& let Some(file) = self.queue.pop_front()
{
let path = file
.path
.as_deref()
.unwrap_or_else(|| std::path::Path::new(&file.name));
self.layout_only = !canvas_pilot::software::artwork_available(path);
self.file = Some(file);
self.page = 0;
self.resolution = 1920;
self.load(ctx);
}
if let Some(result) = poll(&mut self.loading) {
match result {
Ok(document) => {
self.document = Some(document);
self.page = 0;
self.render(ctx);
}
Err(error) => self.error = error,
}
}
if let Some(result) = poll(&mut self.rendering) {
match result {
Ok(reference) => self.preview = Some(reference),
Err(error) => self.error = error,
}
}
let file = self.file.as_ref()?;
let path = file
.path
.as_deref()
.unwrap_or_else(|| std::path::Path::new(&file.name));
let artwork_available = canvas_pilot::software::artwork_available(path);
let mut open = true;
let mut add = false;
let mut cancel = false;
let mut reload = false;
let mut render = false;
egui::Window::new("Import document as reference")
.id(egui::Id::new("document-reference-import"))
.open(&mut open)
.default_width(600.0)
.show(ctx, |ui| {
ui.label("Choose a page and check its appearance before adding it.");
ui.add_enabled_ui(self.loading.is_none() && self.rendering.is_none(), |ui| {
ui.horizontal(|ui| {
ui.label("Render:");
if artwork_available {
reload |= ui
.selectable_value(&mut self.layout_only, false, "Artwork")
.changed();
}
reload |= ui
.selectable_value(&mut self.layout_only, true, "Layout boxes")
.changed();
});
});
if let Some(document) = &self.document {
ui.label(&document.name);
ui.label(&document.note);
ui.add_enabled_ui(self.rendering.is_none(), |ui| {
ui.horizontal(|ui| {
egui::ComboBox::from_id_salt("reference-document-page")
.selected_text(&document.pages[self.page])
.show_ui(ui, |ui| {
for (i, name) in document.pages.iter().enumerate() {
render |=
ui.selectable_value(&mut self.page, i, name).changed();
}
});
egui::ComboBox::from_id_salt("reference-document-resolution")
.selected_text(format!("{} px longest edge", self.resolution))
.show_ui(ui, |ui| {
for size in [1280, 1920, 2560, 3840, 4096] {
render |= ui
.selectable_value(
&mut self.resolution,
size,
format!("{size} px"),
)
.changed();
}
});
});
});
}
if let Some(preview) = &self.preview {
ui.add(
egui::Image::new((preview.texture.id(), preview.texture.size_vec2()))
.max_size(egui::vec2(560.0, 330.0)),
);
ui.small(format!(
"{} × {} px · proportions preserved",
preview.size[0], preview.size[1]
));
}
if self.loading.is_some() || self.rendering.is_some() {
ui.spinner();
ui.label("Preparing reference…");
}
if !self.error.is_empty() {
ui.colored_label(theme::palette(ctx).amber, &self.error);
}
add = ui
.add_enabled(
self.preview.is_some() && !reload && !render,
egui::Button::new("Add reference"),
)
.clicked();
cancel = ui.button("Cancel").clicked();
});
if !open || cancel {
self.close();
return None;
}
if reload {
self.load(ctx);
} else if render {
self.render(ctx);
}
if add {
let reference = self.preview.take();
self.close();
return reference;
}
None
}
}
#[cfg(test)]
mod tests {
use super::super::tests::{frame, mouse};
use super::*;
fn wait_preview(app: &mut Editor, ctx: &egui::Context) {
let until = std::time::Instant::now() + std::time::Duration::from_secs(15);
while app.document_reference.preview.is_none()
&& app.document_reference.error.is_empty()
&& std::time::Instant::now() < until
{
frame(app, ctx, vec![]);
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(
app.document_reference.error.is_empty(),
"{}",
app.document_reference.error
);
assert!(app.document_reference.preview.is_some());
}
#[test]
fn pdf_review_adds_selected_page_as_portable_reference_without_changing_layers() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let before = app.project();
app.load_reference(
&ctx,
&egui::DroppedFile {
name: "client.pdf".into(),
bytes: Some(
include_bytes!("../tests/fixtures/reference-pages.pdf")
.to_vec()
.into(),
),
..Default::default()
},
);
wait_preview(&mut app, &ctx);
assert_eq!(
app.project(),
before,
"preview must not change the document"
);
app.document_reference.page = 1;
app.document_reference.resolution = 200;
app.document_reference.render(&ctx);
wait_preview(&mut app, &ctx);
let output = frame(&mut app, &ctx, vec![]);
let pos = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == "Add reference" => {
Some(t.pos + t.galley.size() / 2.0)
}
_ => None,
})
.unwrap();
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(pos), mouse(pos, true)],
);
frame(&mut app, &ctx, vec![mouse(pos, false)]);
assert_eq!(app.references.len(), 1);
let reference = &app.references[0];
assert_eq!(reference.name, "client.pdf · Page 2");
assert!(reference.preserve_ratio);
assert_eq!(reference.size, [200, 200]);
assert_eq!(app.project().layers, before.layers);
let saved =
canvas_pilot::project::Project::from_json(&app.project().to_json().unwrap()).unwrap();
let mut restored = Editor::default();
restored.install_project(&ctx, saved).unwrap();
assert_eq!(restored.references[0].bytes, reference.bytes);
assert!(restored.references[0].preserve_ratio);
assert!(app.document_reference.file.is_none());
}
#[test]
fn layout_only_documents_start_without_an_artwork_option() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let csv = "midra_geometry_version,canvas_width,canvas_height,id,name,role,x,y,width,height\n1,1920,1080,speaker,Speaker,layer,10,20,300,400\n";
app.load_reference(
&ctx,
&egui::DroppedFile {
name: "layout.csv".into(),
bytes: Some(csv.as_bytes().to_vec().into()),
..Default::default()
},
);
wait_preview(&mut app, &ctx);
assert!(app.document_reference.layout_only);
let output = frame(&mut app, &ctx, vec![]);
assert!(
!output
.shapes
.iter()
.any(|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text() == "Artwork"))
);
assert!(output.shapes.iter().any(
|s| matches!(&s.shape, egui::Shape::Text(t) if t.galley.text() == "Layout boxes")
));
}
#[test]
fn cancellation_and_failed_documents_keep_existing_project_and_ignore_late_results() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let before = app.project();
app.document_reference.file = Some(egui::DroppedFile {
name: "bad.pdf".into(),
bytes: Some(b"broken".to_vec().into()),
..Default::default()
});
app.document_reference.load(&ctx);
let until = std::time::Instant::now() + std::time::Duration::from_secs(5);
while app.document_reference.error.is_empty() && std::time::Instant::now() < until {
frame(&mut app, &ctx, vec![]);
std::thread::sleep(std::time::Duration::from_millis(5));
}
assert!(app.document_reference.error.contains("Cannot open PDF"));
assert_eq!(app.project(), before);
let (tx, rx) = mpsc::channel();
app.document_reference.loading = Some(rx);
app.document_reference.close();
assert!(tx.send(Err("late result".into())).is_err());
frame(&mut app, &ctx, vec![]);
assert_eq!(app.project(), before);
assert!(app.document_reference.error.is_empty());
let (tx, rx) = mpsc::channel::<Result<Document, String>>();
drop(tx);
assert!(poll(&mut Some(rx)).unwrap().is_err());
}
}

View File

@ -97,7 +97,7 @@ fn placeholder(project: &Project, layer: &Layer) -> Result<String, String> {
source.native_resolution.width as f64,
source.native_resolution.height as f64,
];
let input = source.input_crop.remaining(native)?;
let input = native;
let remaining = layer.advanced_crop.remaining(input)?;
let fitted = if let Some(mode) = layer.layer_fit {
mode.image(remaining, layer.bounds)?
@ -126,12 +126,8 @@ fn placeholder(project: &Project, layer: &Layer) -> Result<String, String> {
return Rgba([0, 0, 0, 0]);
}
let sx = source.input_crop.left
+ layer.advanced_crop.left
+ (ox - fitted.x) / fitted.width * remaining[0];
let sy = source.input_crop.top
+ layer.advanced_crop.top
+ (oy - fitted.y) / fitted.height * remaining[1];
let sx = layer.advanced_crop.left + (ox - fitted.x) / fitted.width * remaining[0];
let sy = layer.advanced_crop.top + (oy - fitted.y) / fitted.height * remaining[1];
let gx = sx / native[0] * 10.0;
let gy = sy / native[1] * 6.0;
if gx.fract() < 0.025 || gy.fract() < 0.025 {

View File

@ -16,7 +16,6 @@ pub fn snapshot(project: &Project, ids: &[usize]) -> Result<Project, String> {
project.layout()?;
let mut p = project.clone();
p.layers.retain(|l| ids.contains(&l.id));
p.input_proposals.retain(|p| ids.contains(&p.layer_id));
p.editor.selected_layer_ids.retain(|id| ids.contains(id));
p.folders
.retain(|f| p.layers.iter().any(|l| &l.folder == f));

View File

@ -236,53 +236,7 @@ fn dimensions(ui: &mut egui::Ui, size: &mut [f64; 2], prefix: &str) {
}
});
}
fn resolution(ui: &mut egui::Ui, size: &mut [u32; 2], prefix: &str, ratio: Option<f64>) {
ui.horizontal_wrapped(|ui| {
ui.label(prefix);
if ui
.add(
egui::DragValue::new(&mut size[0])
.speed(1)
.prefix(tr(ui.ctx(), "ui.w")),
)
.changed()
&& let Some(r) = ratio
{
size[1] = (size[0] as f64 / r).round() as u32;
}
if ui
.add(
egui::DragValue::new(&mut size[1])
.speed(1)
.prefix(tr(ui.ctx(), "ui.h")),
)
.changed()
&& let Some(r) = ratio
{
size[0] = (size[1] as f64 * r).round() as u32;
}
if size[0] > 0 && size[1] > 0 {
ui.label(format!(
"Ratio {}",
ratio_ui::label(size[0] as f64 / size[1] as f64)
));
}
});
}
fn presets(ui: &mut egui::Ui, size: &mut [u32; 2], aspect: &mut Aspect) {
ui.horizontal_wrapped(|ui| {
for (name, value) in [
("HD", [1280, 720]),
("Full HD", [1920, 1080]),
("UHD 4K", [3840, 2160]),
] {
if ui.button(name).clicked() {
*size = value;
*aspect = Aspect::SixteenNine;
}
}
});
}
impl Editor {
pub(super) fn output_window(&mut self, ctx: &egui::Context) {
let Some(mut d) = self.output_draft.take() else {
@ -330,6 +284,38 @@ impl Editor {
self.output_draft = Some(d);
}
}
fn request_formats_close(&mut self) {
if let Some(draft) = self
.format_draft
.as_mut()
.filter(|d| d.pending(&self.layout))
{
draft.closing = true;
} else {
self.format_draft = None;
}
}
pub(super) fn toggle_layer_properties(&mut self, layer: usize) {
if self
.format_draft
.as_ref()
.is_some_and(|draft| draft.is_for(layer))
{
self.request_formats_close();
} else {
self.property_tab = PropertyTab::Layer;
self.format_draft = Some(FormatDraft::new(&self.layout, layer));
}
}
pub(super) fn finish_crop_edit(&mut self) {
self.request_formats_close();
self.edit_content = false;
self.edit_mask = false;
self.alt_mask = false;
}
pub(super) fn sync_crop_tab_mode(&mut self) {
let mask = self.property_tab == PropertyTab::Mask;
let active = (self.property_tab == PropertyTab::Crop || mask)
@ -376,62 +362,19 @@ impl Editor {
ui.separator();
}
if self.property_tab == PropertyTab::Source {
ui.heading(tr(ui.ctx(), "ui.advanced-source-input-settings"));
self.advanced_input_controls(ui, i);
self.source_input_controls(ui,i);
self.preview_warning(ui,i);
ui.separator();
ui.label(tr(ui.ctx(), "ui.editor-source-model-local-geometry"));
ui.small(tr(ui.ctx(), "ui.these-dimensions-describe-the-editor-source-not-a-device-timing-command-local-input-c"));
ui.add_enabled_ui(self.device.input_edits.enabled, |ui| {
ui.horizontal(|ui| {
ui.label(tr(ui.ctx(), "ui.editor-input"));
egui::ComboBox::from_id_salt("source-id").selected_text(format!("Input {}",d.source_id+1)).show_ui(ui,|ui| {
let count = self.layout.formats().sources.len().max(8).max(d.source_id + 1);
for id in 0..count { if ui.stable_selectable_value(&mut d.source_id,id,format!("Input {}",id+1)).changed() { d.source=self.layout.formats().sources.get(id).copied().unwrap_or_default();d.input_size=d.source.input().unwrap(); } }
ui.separator();
if ui.add_enabled(count < 1024, egui::Button::new(tr(ui.ctx(), "ui.new-editor-input"))).clicked() {
d.source_id = count;
d.source = Default::default();
d.input_size = d.source.input().unwrap();
ui.close();
}
});
});
ui.small(tr(ui.ctx(), "ui.editor-inputs-share-source-format-and-input-crop-between-editor-layers-inputs-1-8-are"));
let affected:Vec<_>=(0..self.layout.layers().len()).filter(|j| *j==i || self.layout.formats().source_for[*j]==d.source_id).map(|j|self.layout.layer_label(j)).collect();
ui.label(format!("Input edits affect: {}",affected.join(", ")));
let old_native=d.source.native;
ui.horizontal(|ui| {
ui.label(tr(ui.ctx(), "ui.source-format"));
if aspect_combo(ui,"source-aspect",&mut d.source.aspect) && let Some(r)=d.source.aspect.ratio() { d.source.native[1]=(d.source.native[0] as f64/r).round() as u32; }
});
presets(ui,&mut d.source.native,&mut d.source.aspect);
resolution(ui,&mut d.source.native,"Native pixels",d.source.aspect.ratio());
if old_native!=d.source.native { d.source.input_crop=Crop::default();d.input_size=d.source.native.map(f64::from); }
ui.label(tr(ui.ctx(), "ui.custom-input-resolution-retains-the-source-format-above"));
let old_input_size=d.input_size;
dimensions(ui,&mut d.input_size,"Input resolution");
if old_input_size!=d.input_size {
match Crop::centered(d.source.native.map(f64::from),d.input_size) {
Ok(c)=>{d.source.input_crop=c;d.error.clear();},Err(e)=>d.error=e
}
ui.heading(tr(ui.ctx(), "ui.advanced-source-input-settings"));
if ui.button("Open shared input settings…").clicked() {
self.inputs.open = true;
self.inputs.selected = self.selected_physical_input(i);
}
ui.horizontal(|ui| {
if ui.button(tr(ui.ctx(), "ui.center-input-crop-to-this-size")).clicked() {
match Crop::centered(d.source.native.map(f64::from),d.input_size) { Ok(c)=>{d.source.input_crop=c;d.error.clear();},Err(e)=>d.error=e }
}
if ui.button(tr(ui.ctx(), "ui.use-full-input")).clicked() { d.source.input_crop=Crop::default();d.input_size=d.source.native.map(f64::from); }
});
let old_crop=d.source.input_crop;
ui.horizontal_wrapped(|ui| {
for (title,value) in [("L ",&mut d.source.input_crop.left),("R ",&mut d.source.input_crop.right),("T ",&mut d.source.input_crop.top),("B ",&mut d.source.input_crop.bottom)] { ui.add(egui::DragValue::new(value).range(0.0..=f64::MAX).custom_parser(nonnegative_number).speed(1.0).custom_formatter(|v,_|number(v)).prefix(title)); }
});
if old_crop!=d.source.input_crop && let Ok(size)=d.source.input() { d.input_size=size; }
ui.label(tr(ui.ctx(), "ui.input-crop-edges-native-source-pixels-native-size-changes-reset-the-draft-input-crop"));
});
ui.small("Shared input settings apply to every layer using that physical input. Load the layout again after changing device preprocessing.");
}
if self.property_tab == PropertyTab::Layer {
let before_size = d.size;
self.keep_aspect_ratio = self.layout.layer_info(i).keep_aspect_ratio;
ui.heading(tr(ui.ctx(), "ui.layer-resolution-final-visible-box"));
ui.label(tr(ui.ctx(), "ui.resizing-automatically-adjusts-the-layer-crop-to-fit-the-new-dimensions"));
ui.horizontal(|ui| {
@ -448,7 +391,11 @@ impl Editor {
match d.commit_ratio(self.keep_aspect_ratio) {Ok(())=>d.error.clear(),Err(error)=>d.error=error}
}
if !self.keep_aspect_ratio && d.ratio_edit.target.is_some() {ui.small(tr(ui.ctx(), "ui.ratio-ready-enable-the-lock-to-resize"));}
if lock_changed {self.settings.save(&self.application_settings(ui.ctx()));}
if lock_changed
&& let Err(error) = self.layout.set_keep_aspect_ratio(i, self.keep_aspect_ratio)
{
d.error = error;
}
let old=d.size;
dimensions(ui,&mut d.size,"Visible pixels");
if self.keep_aspect_ratio {
@ -464,24 +411,6 @@ impl Editor {
ui.small(tr(ui.ctx(), "ui.layer-size-changes-apply-as-you-edit-undo-restores-earlier-values"));
}
if !ui.input(|input| input.pointer.primary_down()) { d.layer_before = None; }
if self.property_tab == PropertyTab::Source {
let g=self.layout.layers()[i];
let [x,y]=self.position_reference().offsets_on(g,self.layout.formats().output);
let geometry=self.position_reference().geometry_on(x,y,d.size[0],d.size[1],self.layout.formats().output);
let mut preview=self.layout.clone();
let input_matches=d.source.input().is_ok_and(|size| (size[0]-d.input_size[0]).abs()<1e-7 && (size[1]-d.input_size[1]).abs()<1e-7);
let reviewed=if input_matches {geometry.and_then(|geometry|preview.configure(i,d.source_id,d.source,geometry,true))} else {Err("Input resolution is invalid or does not match the crop edges.".into())};
match &reviewed {
Ok(message) if !message.is_empty()=>{ ui.label(message); },
Err(e)=>{ ui.colored_label(theme::palette(ui.ctx()).amber,e); },
_=>{}
}
let pending = d.pending(&self.layout);
if apply_button(ui,&tr(ui.ctx(), "action.apply-source"), pending && self.device.input_edits.enabled).clicked() {
match d.apply(&mut self.layout, position_reference, self.keep_aspect_ratio) { Ok(())=>{self.sync();d=FormatDraft::new(&self.layout,i);},Err(e)=>d.error=e }
}
ui.small(tr(ui.ctx(), "ui.source-changes-require-apply-switching-tabs-keeps-pending-source-edits"));
}
if self.property_tab == PropertyTab::Mask {
ui.heading(tr(ui.ctx(), "ui.layer-mask-blanking"));
ui.label(tr(ui.ctx(), "ui.the-magenta-box-reveals-pixels-everything-outside-it-is-blanked-image-scale-crop-and"));
@ -524,6 +453,11 @@ impl Editor {
}
if self.property_tab == PropertyTab::Crop {
ui.heading(tr(ui.ctx(), "ui.layer-crop-zoom-position"));
ui.add_enabled_ui(!d.pending(&self.layout), |ui| {
ui.group(|ui| {
if self.crop_preset_buttons(ui) { d = FormatDraft::new(&self.layout, i); }
});
});
let mut advanced_fit = self.layout.formats().layer_fit[i].is_some();
if ui.checkbox(&mut advanced_fit, tr(ui.ctx(), "ui.advanced-layer-fit")).changed() {
let mode = advanced_fit.then_some(canvas_pilot::formats::LayerFit::Centered);
@ -557,14 +491,16 @@ impl Editor {
let current = self.layout.layers()[i];
let (_, area) = ui.allocate_space(Vec2::new(ui.available_width(),170.0));
paint_layer_source(ui.painter(),fit_rect(area,[current.width,current.height]), &self.layout, i, self.layer_preview(i));
if current_fit == canvas_pilot::formats::LayerFit::OneToOne {
ui.small(tr(ui.ctx(), "ui.drag-helper-edges-to-trim-without-zooming-drag-anywhere-inside-the-layer-including-em"));
} else if matches!(current_fit, canvas_pilot::formats::LayerFit::Centered | canvas_pilot::formats::LayerFit::Cropped) {
ui.small(tr(ui.ctx(), "ui.this-mode-fits-automatically-the-canvas-crop-helper-is-disabled-numeric-crop-edges-re"));
} else {
ui.small(tr(ui.ctx(), "ui.edit-crop-edges-here-visual-zoom-drag-controls-are-for-normal-crop-mode"));
ui.small("Drag green edge handles on the canvas to trim each side. The image stays still until release, then refits. Double-click or Enter opens/closes this helper.");
if ui.button("Convert to Smart crop")
.on_hover_text("Keep an exact matching crop; otherwise reset to centered cover framing. Undo restores the advanced fit.")
.clicked() {
match self.layout.convert_to_smart_crop(i) {
Ok(()) => { self.sync(); d.refresh_fit(&self.layout); self.edit_mask = false; self.edit_content = true; }
Err(e) => d.error = e,
}
}
ui.small(tr(ui.ctx(), "ui.disabling-advanced-fit-restores-normal-cover-framing-device-subpixel-rendering-is-app"));
} else {
ui.label(tr(ui.ctx(), "ui.zoom-and-position-change-the-crop-values-inside-this-layer-keeping-its-visible-box-fi"));
@ -597,6 +533,19 @@ impl Editor {
});
if !ui.input(|input| input.pointer.primary_down()) { d.crop_before = None; }
ui.small(tr(ui.ctx(), "ui.crop-zoom-and-offsets-apply-as-you-edit-offsets-stop-at-the-content-edges-and-adjust"));
if ui.button("Convert to Edge crop")
.on_hover_text("Keep the current picture and crop, then edit its source edges independently. Undo returns to Smart crop.")
.clicked() {
match self.layout.convert_to_edge_crop(i) {
Ok(()) => {
self.sync();
d.refresh_fit(&self.layout);
self.edit_mask = false;
self.edit_content = true;
}
Err(e) => d.error = e,
}
}
}
}
if self.property_tab == PropertyTab::Preview {
@ -606,6 +555,7 @@ impl Editor {
let (_,rect)=ui.allocate_space(Vec2::new(ui.available_width(),170.0));
let preview_rect=fit_rect(rect,[current.width,current.height]);
paint_layer_source(ui.painter(),preview_rect,&self.layout,i,self.layer_preview(i));
self.paint_preview_warning(ui.painter(), preview_rect, i);
ui.label(tr(ui.ctx(), "ui.captured-stills-follow-this-layer-s-input-and-dynamic-crops-guides-are-drawn-above-th"));
}
if !d.error.is_empty() {ui.colored_label(theme::palette(ui.ctx()).amber,&d.error);}
@ -616,12 +566,25 @@ impl Editor {
}
});
});
// Input selection can reframe the live layer while this window owns its
// draft. Refresh only source-dependent fields, preserving pending size edits.
let source_id = self.layout.formats().source_for[i];
let source = self.layout.formats().sources[source_id];
if d.baseline.0 != source_id || d.baseline.1 != source {
d.source_id = source_id;
d.source = source;
d.input_size = source.input().unwrap();
d.baseline.0 = source_id;
d.baseline.1 = source;
d.baseline.2 = d.input_size;
d.refresh_fit(&self.layout);
}
if !open && d.pending(&self.layout) {
d.closing = true;
}
if d.closing {
match pending_close(ctx, "formats-close", &d.error) {
Some(true) => {
Some(CloseChoice::Apply) => {
match d.apply(&mut self.layout, position_reference, self.keep_aspect_ratio) {
Ok(()) => {
self.sync();
@ -634,7 +597,11 @@ impl Editor {
}
}
}
Some(false) => return,
Some(CloseChoice::Discard) => return,
Some(CloseChoice::Cancel) => {
d.closing = false;
open = true;
}
None => {}
}
}
@ -652,9 +619,10 @@ pub(super) fn content_bounds(rect: Rect, source: Source, crop: Crop) -> Option<R
let input = source.input().ok()?;
let retained = crop.remaining(input).ok()?;
let k = rect.width() as f64 / retained[0];
let ky = rect.height() as f64 / retained[1];
Some(Rect::from_min_size(
rect.min - Vec2::new((crop.left * k) as f32, (crop.top * k) as f32),
Vec2::new((input[0] * k) as f32, (input[1] * k) as f32),
rect.min - Vec2::new((crop.left * k) as f32, (crop.top * ky) as f32),
Vec2::new((input[0] * k) as f32, (input[1] * ky) as f32),
))
}
@ -862,16 +830,36 @@ fn paint_source_clipped(
};
let k = rect.width() as f64 / retained[0];
let ky = rect.height() as f64 / retained[1];
// A Midra still already contains the input crop. Fit its actual aspect
// into source space before applying the layer transform; stretching it
// to source.native here distorts even Centered and ordinary crop modes.
// Reduced-resolution captures and local pictures use the same rule.
let picture = painter
.ctx()
.tex_manager()
.read()
.meta(texture)
.map(|meta| meta.size.map(|n| n as f64))
.unwrap_or(input);
let fitted = canvas_pilot::formats::LayerFit::Centered.image(
picture,
canvas_pilot::Geometry {
x: 0.,
y: 0.,
width: input[0],
height: input[1],
},
);
let Ok(fitted) = fitted else {
return;
};
let native = Rect::from_min_size(
rect.min
- Vec2::new(
((source.input_crop.left + crop.left) * k) as f32,
((source.input_crop.top + crop.top) * ky) as f32,
+ Vec2::new(
((fitted.x - crop.left) * k) as f32,
((fitted.y - crop.top) * ky) as f32,
),
Vec2::new(
(source.native[0] as f64 * k) as f32,
(source.native[1] as f64 * ky) as f32,
),
Vec2::new((fitted.width * k) as f32, (fitted.height * ky) as f32),
);
painter
.with_clip_rect(painter.clip_rect().intersect(clip))
@ -889,7 +877,7 @@ fn paint_source_clipped(
paint_pattern_clipped(&guides, rect, source, crop, clip);
}
fn paint_pattern_clipped(
pub(super) fn paint_pattern_clipped(
painter: &egui::Painter,
rect: Rect,
source: Source,
@ -907,11 +895,7 @@ fn paint_pattern_clipped(
let ky = rect.height() as f64 / retained[1];
let p = painter.with_clip_rect(painter.clip_rect().intersect(clip));
let point = |x: f64, y: f64| {
rect.min
+ Vec2::new(
((x - source.input_crop.left - crop.left) * k) as f32,
((y - source.input_crop.top - crop.top) * ky) as f32,
)
rect.min + Vec2::new(((x - crop.left) * k) as f32, ((y - crop.top) * ky) as f32)
};
for row in 0..6 {
for col in 0..10 {
@ -927,15 +911,14 @@ fn paint_pattern_clipped(
if !cell.intersects(clip) {
continue;
}
p.rect_filled(
cell,
0.0,
if (row + col) % 2 == 0 {
palette.pattern[0]
} else {
palette.pattern[1]
},
);
let tile = (row + col) % 2;
let label_color = if theme::Theme::current(painter.ctx()) == theme::Theme::HighContrast
{
palette.pattern[1 - tile]
} else {
palette.text
};
p.rect_filled(cell, 0.0, palette.pattern[tile]);
p.rect_stroke(
cell,
0.0,
@ -948,7 +931,7 @@ fn paint_pattern_clipped(
Align2::CENTER_CENTER,
format!("{},{}", col, row),
FontId::proportional(11.0),
palette.text,
label_color,
);
}
}
@ -966,6 +949,74 @@ fn paint_pattern_clipped(
mod tests {
use super::super::tests::{click_text, frame, mouse};
use super::*;
#[test]
fn crop_properties_presets_resize_and_crop_together_and_respect_pending_edits() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.select(Some(0));
app.sync();
app.property_tab = PropertyTab::Crop;
app.format_draft = Some(FormatDraft::new(&app.layout, 0));
let before = canvas_pilot::project::Project::from_layout(&app.layout);
click_text(&mut app, &ctx, "4:3");
let g = app.layout.layers()[0];
assert!((g.width / g.height - 4.0 / 3.0).abs() < 1e-9);
assert!(app.layout.formats().advanced[0].left > 0.0);
let after = canvas_pilot::project::Project::from_layout(&app.layout);
click_text(&mut app, &ctx, "4:3");
assert_eq!(
canvas_pilot::project::Project::from_layout(&app.layout),
after
);
app.layout.undo();
assert_eq!(
canvas_pilot::project::Project::from_layout(&app.layout),
before
);
let mut draft = FormatDraft::new(&app.layout, 0);
draft.source.native = [1280, 720];
app.format_draft = Some(draft);
click_text(&mut app, &ctx, "4:3");
assert_eq!(
canvas_pilot::project::Project::from_layout(&app.layout),
before
);
assert_eq!(
app.format_draft.as_ref().unwrap().source.native,
[1280, 720]
);
}
#[test]
fn enter_from_crop_or_mask_reviews_pending_properties_without_discarding() {
for tab in [PropertyTab::Crop, PropertyTab::Mask] {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.select(Some(1));
app.property_tab = tab;
let mut draft = FormatDraft::new(&app.layout, 1);
draft.size = [800.0, 450.0];
app.format_draft = Some(draft);
frame(&mut app, &ctx, vec![]);
let applied = app.project();
frame(
&mut app,
&ctx,
vec![egui::Event::Key {
key: egui::Key::Enter,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}],
);
assert!(app.format_draft.as_ref().unwrap().closing);
assert_eq!(app.project(), applied);
click_text(&mut app, &ctx, "Discard");
assert!(app.format_draft.is_none());
assert_eq!(app.project(), applied);
}
}
fn enter_value(app: &mut Editor, ctx: &egui::Context, label: &str, text: &str) {
// DragValue renders prefix, number and suffix as separate atoms in egui 0.35.
frame(app, ctx, vec![]);
@ -1144,75 +1195,6 @@ mod tests {
assert_eq!(layout.layers(), &before);
}
#[test]
fn input_crop_controls_reject_negative_paste_and_keep_fractional_values() {
let ctx = egui::Context::default();
let mut app = Editor {
property_tab: PropertyTab::Source,
..Default::default()
};
app.device.input_edits.enabled = true;
let crop = Crop {
left: 20.0,
right: 20.0,
top: 20.0,
bottom: 20.0,
};
let source = Source {
input_crop: crop,
..Source::default()
};
app.layout
.configure(1, 1, source, app.layout.layers()[1], true)
.unwrap();
app.sync();
app.format_draft = Some(FormatDraft::new(&app.layout, 1));
for label in ["L 20.0", "R 20.0", "T 20.0", "B 20.0"] {
enter_value(&mut app, &ctx, label, "-12.5");
assert_eq!(app.format_draft.as_ref().unwrap().source.input_crop, crop);
}
enter_value(&mut app, &ctx, "L 20.0", "NaN");
assert_eq!(app.format_draft.as_ref().unwrap().source.input_crop, crop);
enter_value(&mut app, &ctx, "L 20.0", "12.5");
assert_eq!(
app.format_draft.as_ref().unwrap().source.input_crop.left,
12.5
);
enter_value(&mut app, &ctx, "L 12.5", "0");
assert_eq!(
app.format_draft.as_ref().unwrap().source.input_crop.left,
0.0
);
let output = frame(&mut app, &ctx, vec![]);
let texts: Vec<_> = output
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
egui::Shape::Text(t) => Some(t),
_ => None,
})
.collect();
let start = texts
.windows(2)
.find_map(|pair| {
(pair[0].galley.text() == "R " && pair[1].galley.text() == "20.0")
.then(|| pair[1].pos + pair[1].galley.size() / 2.0)
})
.unwrap();
let end = start - Vec2::new(100.0, 0.0);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
frame(&mut app, &ctx, vec![mouse(end, false)]);
assert_eq!(
app.format_draft.as_ref().unwrap().source.input_crop.right,
0.0
);
}
#[test]
fn crop_zoom_rejects_negative_entry_but_content_offsets_allow_negative_values() {
let ctx = egui::Context::default();
@ -1408,6 +1390,12 @@ mod tests {
draft.size = [800.0, 450.0];
draft.closing = true;
app.format_draft = Some(draft);
click_text(&mut app, &ctx, "Cancel");
let draft = app.format_draft.as_mut().unwrap();
assert!(!draft.closing);
assert_eq!(draft.size, [800.0, 450.0]);
assert_eq!(*app.layout.layers(), before);
draft.closing = true;
click_text(&mut app, &ctx, "Discard");
assert!(app.format_draft.is_none());
assert_eq!(*app.layout.layers(), before);
@ -1581,63 +1569,89 @@ mod tests {
app.layout.undo();
assert_eq!(app.layout.formats().output, [1920, 1080]);
}
#[test]
fn advanced_source_edits_require_explicit_checkbox() {
let mut app = Editor {
property_tab: PropertyTab::Source,
..Default::default()
};
let ctx = egui::Context::default();
let before = app.layout.formats().clone();
let mut draft = FormatDraft::new(&app.layout, 1);
draft.input_size = [1920.0, 1000.0];
draft.source.input_crop = Crop::centered([1920.0, 1080.0], draft.input_size).unwrap();
app.format_draft = Some(draft);
click_text(&mut app, &ctx, "Apply source changes");
assert_eq!(app.layout.formats(), &before);
assert!(!app.device.input_edits.enabled);
click_text(
&mut app,
&ctx,
"Edit advanced input settings and include my edits when sending",
);
assert!(app.device.input_edits.enabled);
click_text(&mut app, &ctx, "Apply source changes");
assert_eq!(app.layout.formats().input(1).unwrap(), [1920.0, 1000.0]);
assert!(!app.device.sending);
}
#[test]
fn source_and_layer_dialog_applies_worked_example_with_one_undo() {
let mut app = Editor {
property_tab: PropertyTab::Source,
keep_aspect_ratio: false,
..Default::default()
};
app.device.input_edits.enabled = true;
let ctx = egui::Context::default();
let before = app.layout.layers().clone();
let formats = app.layout.formats().clone();
let mut d = FormatDraft::new(&app.layout, 1);
d.input_size = [1920.0, 1000.0];
d.source.input_crop = Crop::centered([1920.0, 1080.0], d.input_size).unwrap();
d.size = [300.0, 250.0];
app.format_draft = Some(d);
click_text(&mut app, &ctx, "Apply source changes");
assert_eq!(app.layout.formats().input(1).unwrap(), [1920.0, 1000.0]);
let g = app.layout.layers()[1];
assert_eq!([g.width, g.height], [300.0, 250.0]);
assert_eq!(app.layout.formats().advanced[1].left, 360.0);
assert_eq!(app.layout.layers()[0], before[0]);
app.layout.undo();
assert_eq!(*app.layout.layers(), before);
assert_eq!(*app.layout.formats(), formats);
}
}
#[cfg(test)]
mod preview_paint_tests {
use super::*;
#[test]
fn cropped_capture_aspect_survives_layer_fit_and_helpers() {
use canvas_pilot::formats::LayerFit;
for size in [[361, 512], [512, 231], [512, 288]] {
for fit in std::iter::once(None).chain(LayerFit::ALL.into_iter().map(Some)) {
let ctx = egui::Context::default();
let texture = ctx.load_texture(
"cropped-input",
egui::ColorImage::filled(size, Color32::RED),
Default::default(),
);
let mut app = Editor::default();
if fit.is_some() {
app.layout
.set_layer_fit(
1,
fit,
Crop {
left: 120.,
right: 80.,
top: 30.,
bottom: 60.,
},
)
.unwrap();
}
let g = app.layout.layers()[1];
let rect = Rect::from_min_size(
Pos2::new(100., 100.),
Vec2::new(g.width as f32, g.height as f32) * 0.25,
);
let before = app.project();
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
paint_layer_source(
ui.painter(),
rect,
&app.layout,
1,
Some((texture.id(), 0.0)),
);
paint_mask_helper(
ui.painter(),
rect,
&app.layout,
1,
Some((texture.id(), 0.0)),
);
});
let meshes: Vec<_> = output
.shapes
.iter()
.filter_map(|shape| match &shape.shape {
egui::Shape::Mesh(mesh) if mesh.texture_id == texture.id() => Some(mesh),
_ => None,
})
.collect();
assert!(!meshes.is_empty());
let retained = app.layout.formats().advanced[1]
.remaining(app.layout.formats().input(1).unwrap())
.unwrap();
let stretch = if fit == Some(LayerFit::Fullscreen) {
(g.width / retained[0]) / (g.height / retained[1])
} else {
1.
};
for mesh in meshes {
let bounds = mesh.calc_bounds();
let expected = size[0] as f64 / size[1] as f64 * stretch;
assert!(
(bounds.aspect_ratio() as f64 - expected).abs() < 0.00001,
"{size:?} {fit:?}: {bounds:?}"
);
}
assert_eq!(app.project(), before);
}
}
}
#[test]
fn masked_helper_is_translucent_hatched_and_confined_to_hidden_regions() {
use canvas_pilot::formats::{LayerFit, Mask, MaskOrigin};
@ -1746,7 +1760,6 @@ mod preview_paint_tests {
let source = Source {
aspect: canvas_pilot::formats::Aspect::Square,
native: [1000, 1000],
..Source::default()
};
let crop = Crop {
left: 100.0,
@ -1808,6 +1821,37 @@ mod preview_paint_tests {
}
}
#[test]
fn high_contrast_coordinate_labels_contrast_with_both_tile_colors() {
let ctx = egui::Context::default();
theme::Theme::HighContrast.apply(&ctx);
let rect = Rect::from_min_size(Pos2::new(20.0, 20.0), Vec2::new(1000.0, 600.0));
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
paint_pattern_clipped(ui.painter(), rect, Source::default(), Crop::default(), rect);
});
let mut labels = 0;
for shape in &output.shapes {
if let egui::Shape::Text(text) = &shape.shape {
let (col, row) = text.galley.text().split_once(',').unwrap();
let tile = (col.parse::<usize>().unwrap() + row.parse::<usize>().unwrap()) % 2;
let expected = if tile == 0 {
egui::Color32::WHITE
} else {
egui::Color32::BLACK
};
assert!(
text.galley
.job
.sections
.iter()
.all(|section| section.format.color == expected)
);
labels += 1;
}
}
assert_eq!(labels, 60);
}
#[test]
fn actual_layer_stays_clipped_with_layer_and_source_masks() {
use canvas_pilot::formats::{Mask, MaskOrigin};
@ -1862,18 +1906,10 @@ mod preview_paint_tests {
}
#[test]
fn captured_texture_follows_both_crops_with_guides_above_and_opaque_fallback() {
fn captured_texture_follows_layer_crop_with_guides_above_and_opaque_fallback() {
let ctx = egui::Context::default();
let rect = Rect::from_min_size(Pos2::new(100., 100.), Vec2::new(132., 88.));
let source = Source {
input_crop: Crop {
left: 100.,
right: 100.,
top: 0.,
bottom: 0.,
},
..Source::default()
};
let source = Source::default();
let crop = Crop {
left: 200.,
right: 200.,
@ -1919,8 +1955,13 @@ mod preview_paint_tests {
.fold(Pos2::new(f32::NEG_INFINITY, f32::NEG_INFINITY), |a, b| {
a.max(b)
});
assert_eq!(min, Pos2::new(70., 90.));
assert_eq!(max, Pos2::new(262., 198.));
let kx = rect.width() / (1920.0 - crop.left - crop.right) as f32;
let ky = rect.height() / (1080.0 - crop.top - crop.bottom) as f32;
assert_eq!(
min,
rect.min - Vec2::new(crop.left as f32 * kx, crop.top as f32 * ky)
);
assert_eq!(max, min + Vec2::new(1920.0 * kx, 1080.0 * ky));
assert!(
guides
.iter()

View File

@ -252,14 +252,12 @@ impl Mask {
pub struct Source {
pub aspect: Aspect,
pub native: [u32; 2],
pub input_crop: Crop,
}
impl Default for Source {
fn default() -> Self {
Self {
aspect: Aspect::SixteenNine,
native: [1920, 1080],
input_crop: Crop::default(),
}
}
}
@ -271,7 +269,7 @@ impl Source {
{
return Err("Native dimensions do not match Source format. Choose Custom or correct the native dimensions.".into());
}
self.input_crop.remaining(self.native.map(f64::from))
Ok(self.native.map(f64::from))
}
}
#[derive(Clone, Copy, Debug, PartialEq)]

View File

@ -581,3 +581,71 @@ pub(crate) fn looks_like_dxf(text: &str) -> bool {
|| (start.starts_with("0\r\nSECTION") && text.contains("LWPOLYLINE"))
|| (start.starts_with("0\nSECTION") && text.contains("LWPOLYLINE"))
}
/// Render the supported HTML/JSON exchange schema, retaining embedded pictures.
pub(crate) fn reference_svg(text: &str, html: bool) -> Result<String, String> {
let (size, shapes) = if html {
let parsed = parse_html(text)?;
let xml = roxmltree::Document::parse_with_options(
text,
roxmltree::ParsingOptions {
allow_dtd: true,
nodes_limit: 200_000,
},
)
.map_err(|e| e.to_string())?;
let canvas = xml
.descendants()
.find(|n| n.attribute("id") == Some("midra-canvas"))
.ok_or("Missing canvas")?;
let nodes = canvas
.descendants()
.filter(|n| n.is_element() && n.attribute("data-midra-role").is_some());
let shapes = parsed
.shapes
.into_iter()
.zip(nodes)
.map(|(s, node)| {
let image = node
.attribute("src")
.and_then(|s| s.strip_prefix("data:image/png;base64,"))
.map(str::to_owned);
ExportShape {
id: crate::exchange::escape(node.attribute("id").unwrap_or("")),
name: s.name.unwrap_or_default(),
geometry: s.geometry,
background: s.background,
image_png_base64: image,
}
})
.collect::<Vec<_>>();
(
[
xml_number(canvas, "data-width")? as u32,
xml_number(canvas, "data-height")? as u32,
],
shapes,
)
} else {
parse_json(text)?;
let json: JsonDocument = serde_json::from_str(text).map_err(|e| e.to_string())?;
let shapes = json
.layers
.into_iter()
.map(|s| ExportShape {
id: crate::exchange::escape(&s.id),
name: s.name,
geometry: Geometry {
x: s.x as f64,
y: s.y as f64,
width: s.width as f64,
height: s.height as f64,
},
background: s.role == "background",
image_png_base64: s.image_png_base64,
})
.collect::<Vec<_>>();
([json.canvas.width, json.canvas.height], shapes)
};
crate::exchange::encode_shapes(Format::Svg, size, &shapes)
}

File diff suppressed because it is too large Load Diff

View File

@ -82,18 +82,98 @@ pub fn parse_values(text: &str) -> Result<ImportDocument, String> {
if crate::geometry_formats::looks_like_dxf(text) {
return crate::geometry_formats::parse_dxf(text);
}
if text.trim_start().starts_with('<')
&& roxmltree::Document::parse_with_options(text, xml_options())
.is_ok_and(|d| d.root_element().has_tag_name("svg"))
let decoded;
let xml = if text.trim_start().to_ascii_lowercase().starts_with("%3c") {
decoded = crate::decode_percent(text.trim())?;
decoded.as_str()
} else {
text
};
if let Ok(document) = roxmltree::Document::parse_with_options(xml, xml_options()) {
let root = document.root_element();
match root.tag_name().name() {
"svg" => return parse_svg(xml),
"mxGraphModel" | "mxfile" => return parse_drawio_values(xml),
"html" => {
// Explicit Canvas Pilot documents remain strict: do not hide invalid
// versions or lost settings by falling back to incidental artwork.
if root.attribute("data-midra-layout-geometry").is_some() {
return crate::geometry_formats::parse_html(xml);
}
let mut failures = Vec::new();
for (label, tags) in [
("draw.io", &["mxGraphModel", "mxfile"][..]),
("SVG", &["svg"][..]),
] {
let nodes: Vec<_> = root
.descendants()
.filter(|node| {
node.is_element()
&& tags.contains(&node.tag_name().name())
&& !node.ancestors().skip(1).any(|parent| {
parent.is_element() && tags.contains(&parent.tag_name().name())
})
})
.collect();
if nodes.is_empty() {
continue;
}
if nodes.len() != 1 {
failures.push(format!(
"{label}: multiple embedded documents; export a single file instead."
));
continue;
}
let fragment = &xml[nodes[0].range()];
let result = if label == "SVG" {
parse_svg(fragment)
} else {
parse_drawio_values(fragment)
};
match result {
Ok(mut imported)
if imported.shapes.iter().any(|shape| !shape.background_only) =>
{
imported.note = format!(
"Clipboard: used embedded {label}; HTML layout/CSS is not imported. {}{}",
imported.note,
if failures.is_empty() {
String::new()
} else {
format!(
" Earlier candidates were rejected: {}",
failures.join(" | ")
)
}
);
return Ok(imported);
}
Ok(_) => failures.push(format!("{label}: no usable layer geometry.")),
Err(error) => failures.push(format!("{label}: {error}")),
}
}
if !failures.is_empty() {
return Err(format!(
"No supported clipboard representation could be imported. {}",
failures.join(" | ")
));
}
}
_ => {}
}
} else if xml.trim_start().starts_with("<svg")
|| xml.trim_start().starts_with("<?xml") && xml.contains("<svg")
{
return parse_svg(text);
}
if text.trim_start().starts_with('<')
&& roxmltree::Document::parse_with_options(text, xml_options())
.is_ok_and(|d| d.root_element().has_tag_name("html"))
return parse_svg(xml);
} else if xml.trim_start().starts_with("<mxGraphModel")
|| xml.trim_start().starts_with("<mxfile")
{
return crate::geometry_formats::parse_html(text);
return parse_drawio_values(xml);
}
Err("No supported layer geometry found in clipboard text. Copy SVG, draw.io XML or Canvas Pilot values, or import a supported file. For PowerPoint, use Import geometry with the .pptx file; native PowerPoint clipboard objects are not supported.".into())
}
fn parse_drawio_values(text: &str) -> Result<ImportDocument, String> {
Ok(ImportDocument {
shapes: parse_drawio(text)?
.into_iter()

View File

@ -1,82 +0,0 @@
//! Inert, explicitly saved input corrections. These are never device commands.
use crate::{DeviceLink, device::Family};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::BTreeMap;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InputProposal {
pub layer_id: usize,
pub device_link: DeviceLink,
pub input: String,
pub plug: String,
/// Only the documented Midra setting suffixes are permitted; never arbitrary paths.
pub settings: BTreeMap<String, Value>,
}
impl InputProposal {
pub fn validate(&self) -> Result<(), String> {
self.device_link.validate()?;
let decimal = |s: &str| {
!s.is_empty()
&& s.len() <= 16
&& s.bytes().all(|b| b.is_ascii_digit())
&& !s.starts_with('0')
};
if self.layer_id == 0
|| self.device_link.family != Family::Midra4k
|| !self.input.strip_prefix("INPUT_").is_some_and(decimal)
|| !decimal(&self.plug)
|| self.settings.is_empty()
|| self.settings.len() > 9
{
return Err("Invalid input proposal identity or settings count.".into());
}
for (key, value) in &self.settings {
let options: &[&str] = match key.as_str() {
"aspect/pp/signal" => &[
"NATIVE", "5_4", "4_3", "16_10", "15_9", "16_9", "21_9", "256_135", "64_27",
],
"aspect/pp/transformTo" => &[
"SIGNAL", "5_4", "4_3", "16_10", "15_9", "16_9", "21_9", "CUSTOM",
],
"aspect/pp/layerFill" => {
&["LAYER_SETTING", "1_1", "CENTERED", "FULLSCREEN", "CROPPED"]
}
"cropping/control/pp/predefined" => &[
"NONE",
"LETTERBOX_1_78",
"LETTERBOX_1_85",
"LETTERBOX_2_35",
"PILLARBOX_1_33",
],
"aspect/pp/customRatio" => {
if !value.as_i64().is_some_and(|v| (250..=10000).contains(&v)) {
return Err("Invalid proposal custom ratio.".into());
}
continue;
}
"cropping/control/pp/left"
| "cropping/control/pp/right"
| "cropping/control/pp/top"
| "cropping/control/pp/bottom" => {
if !value.as_i64().is_some_and(|v| (0..=8191).contains(&v)) {
return Err("Invalid proposal input crop.".into());
}
continue;
}
_ => return Err("Unsupported input proposal setting.".into()),
};
if !value.as_str().is_some_and(|v| options.contains(&v)) {
return Err(format!("Invalid input proposal value for {key}."));
}
}
Ok(())
}
pub fn base(&self) -> String {
format!(
"/device/inputList/items/{}/plugList/items/{}/settings",
self.input, self.plug
)
}
}

View File

@ -1,626 +0,0 @@
//! Explicit device edits and separately saved, inactive input-setting proposals.
use super::*;
use canvas_pilot::{
device::Snapshot,
device_send::{Change, Plan},
};
use serde_json::{Value, json};
use std::collections::{BTreeMap, BTreeSet};
#[derive(Default)]
pub(super) struct InputEdits {
pub enabled: bool,
pub saved: Vec<canvas_pilot::input_proposal::InputProposal>,
message: Option<String>,
// Only fields actually edited are staged; opening the tab never stages defaults.
values: BTreeMap<String, Value>,
}
fn input_path(snapshot: &Snapshot, screen: &str, bank: &str, layer: &str) -> Option<String> {
let input = snapshot.raw.pointer(&format!("/device/screenList/items/{screen}/presetList/items/{bank}/liveLayerList/items/{layer}/source/pp/input"))?.as_str()?;
let base = format!("/device/inputList/items/{input}");
let plug = snapshot
.raw
.pointer(&format!("{base}/status/pp/plug"))?
.as_str()?;
Some(format!("{base}/plugList/items/{plug}/settings"))
}
fn setting_label(value: &str) -> String {
match value {
"NATIVE" => "Native".into(),
"SIGNAL" => "Signal".into(),
"CUSTOM" => "Custom".into(),
"LAYER_SETTING" => "Layer setting".into(),
"CENTERED" => "Centered".into(),
"FULLSCREEN" => "Full screen".into(),
"CROPPED" => "Cropped".into(),
"NONE" => "None".into(),
"LETTERBOX_1_78" => "Letterbox 1.78:1".into(),
"LETTERBOX_1_85" => "Letterbox 1.85:1".into(),
"LETTERBOX_2_35" => "Letterbox 2.35:1".into(),
"PILLARBOX_1_33" => "Pillarbox 1.33:1".into(),
_ => value.replace('_', ":"),
}
}
impl InputEdits {
pub fn clear(&mut self) {
self.enabled = false;
self.values.clear();
self.message = None;
}
pub fn show(
&mut self,
ui: &mut egui::Ui,
snapshot: Option<&Snapshot>,
link: Option<&canvas_pilot::DeviceLink>,
layer_id: usize,
) {
if let Some(saved) = self.saved.iter().find(|p| p.layer_id == layer_id).cloned() {
ui.label(format!(
"Saved proposal: {} · plug {} (inactive until staged)",
saved.input, saved.plug
));
for (key, value) in &saved.settings {
ui.small(format!("{key}: {value}"));
}
let can_stage =
self.enabled && snapshot.is_some_and(|s| Self::proposal_matches(&saved, s, link));
if ui
.add_enabled(
can_stage,
egui::Button::new(tr(ui.ctx(), "ui.stage-saved-input-proposal")),
)
.clicked()
&& let Some(snapshot) = snapshot
{
self.message = Some(match self.stage_proposal(&saved, snapshot, link) {
Ok(()) => "Proposal staged. Review mappings before sending.".into(),
Err(error) => error,
});
}
ui.small(tr(ui.ctx(), "ui.to-stage-connect-match-this-layer-s-saved-mapping-and-routed-input-plug-then-enable-a"));
if ui
.button(tr(ui.ctx(), "ui.remove-saved-input-proposal"))
.clicked()
{
self.saved.retain(|p| p.layer_id != layer_id);
}
}
if let Some(message) = &self.message {
ui.label(message);
}
if snapshot.is_some_and(|s| !s.profile.advanced_inputs()) {
ui.label(tr(ui.ctx(), "ui.shared-input-corrections-for-this-adapter-are-managed-in-webrcs-layer-crop-and-zoom-r"));
return;
}
ui.label(tr(
ui.ctx(),
"ui.advanced-use-only-when-you-need-to-correct-an-input-and-understand-the-effect",
));
ui.label(tr(ui.ctx(), "ui.these-device-controls-map-one-for-one-to-webrcs-advanced-input-settings-content-ratio"));
ui.label(tr(ui.ctx(), "ui.input-crop-removes-source-edges-before-dynamic-layer-crop-zoom-it-does-not-resize-the"));
if ui
.checkbox(
&mut self.enabled,
tr(
ui.ctx(),
"ui.edit-advanced-input-settings-and-include-my-edits-when-sending",
),
)
.changed()
&& !self.enabled
{
self.values.clear();
}
ui.small(tr(ui.ctx(), "ui.off-by-default-only-edited-device-fields-are-sent-and-only-with-layers-using-that-inp"));
let Some((snapshot, base)) = snapshot.and_then(|snapshot| {
let link = link?;
let screen = snapshot.screens.iter().find(|s| s.id == link.screen)?;
input_path(snapshot, &link.screen, &screen.preview_bank, &link.layer)
.map(|base| (snapshot, base))
}) else {
ui.small(tr(ui.ctx(), "ui.connect-and-map-this-layer-to-a-midra-input-source-to-inspect-its-advanced-settings-n"));
return;
};
ui.small(format!(
"Shared input: {} · plug {} (from linked Preview layer)",
base.split('/').nth(4).unwrap_or("?"),
base.split('/').nth(7).unwrap_or("?")
));
ui.add_enabled_ui(self.enabled, |ui| {
for (suffix, label, options) in [
(
"aspect/pp/signal",
"Content ratio",
&[
"NATIVE", "5_4", "4_3", "16_10", "15_9", "16_9", "21_9", "256_135", "64_27",
][..],
),
(
"aspect/pp/transformTo",
"Transform to",
&[
"SIGNAL", "5_4", "4_3", "16_10", "15_9", "16_9", "21_9", "CUSTOM",
][..],
),
(
"aspect/pp/layerFill",
"Layer fill option",
&["LAYER_SETTING", "1_1", "CENTERED", "FULLSCREEN", "CROPPED"][..],
),
(
"cropping/control/pp/predefined",
"Input crop preset",
&[
"NONE",
"LETTERBOX_1_78",
"LETTERBOX_1_85",
"LETTERBOX_2_35",
"PILLARBOX_1_33",
][..],
),
] {
let path = format!("{base}/{suffix}");
let Some(original) = snapshot.raw.pointer(&path) else {
continue;
};
let mut value = self
.values
.get(&path)
.unwrap_or(original)
.as_str()
.unwrap_or_default()
.to_owned();
let before = value.clone();
ui.horizontal(|ui| {
ui.label(label);
egui::ComboBox::from_id_salt(&path)
.selected_text(setting_label(&value))
.show_ui(ui, |ui| {
for option in options {
ui.stable_selectable_value(
&mut value,
(*option).into(),
setting_label(option),
);
}
});
});
if value != before {
self.stage(path, json!(value), original);
}
}
for (suffix, label, min, max, scale) in [
(
"aspect/pp/customRatio",
"Custom aspect ratio ",
250.,
10000.,
0.001,
),
(
"cropping/control/pp/left",
"Input crop left ",
0.,
8191.,
1.,
),
(
"cropping/control/pp/right",
"Input crop right ",
0.,
8191.,
1.,
),
("cropping/control/pp/top", "Input crop top ", 0., 8191., 1.),
(
"cropping/control/pp/bottom",
"Input crop bottom ",
0.,
8191.,
1.,
),
] {
let path = format!("{base}/{suffix}");
let Some(original) = snapshot.raw.pointer(&path) else {
continue;
};
let mut value = self
.values
.get(&path)
.unwrap_or(original)
.as_f64()
.unwrap_or_default()
* scale;
if ui
.add(
egui::DragValue::new(&mut value)
.range(min * scale..=max * scale)
.speed(scale)
.prefix(label)
.max_decimals(if scale == 1. { 0 } else { 3 }),
)
.changed()
{
self.stage(path, json!((value / scale).round() as i64), original);
}
}
});
let prefix = format!("{base}/");
let settings: BTreeMap<_, _> = self
.values
.iter()
.filter_map(|(path, value)| {
path.strip_prefix(&prefix)
.map(|key| (key.to_owned(), value.clone()))
})
.collect();
if ui
.add_enabled(
!settings.is_empty(),
egui::Button::new(tr(
ui.ctx(),
"ui.save-staged-input-edits-as-a-project-proposal",
)),
)
.clicked()
&& let Some(link) = link
{
let proposal = canvas_pilot::input_proposal::InputProposal {
layer_id,
device_link: link.clone(),
input: base.split('/').nth(4).unwrap_or_default().into(),
plug: base.split('/').nth(7).unwrap_or_default().into(),
settings,
};
if proposal.validate().is_ok() {
self.saved.retain(|p| p.layer_id != layer_id);
self.saved.push(proposal);
}
}
ui.small(tr(ui.ctx(), "ui.saving-a-proposal-is-opt-in-project-saves-and-extra-parameter-exports-retain-it-reope"));
ui.small(tr(ui.ctx(), "ui.edits-wait-for-send-opening-this-tab-or-enabling-the-checkbox-sends-nothing-refresh-l"));
}
fn proposal_matches(
proposal: &canvas_pilot::input_proposal::InputProposal,
snapshot: &Snapshot,
link: Option<&canvas_pilot::DeviceLink>,
) -> bool {
proposal.validate().is_ok()
&& snapshot.profile.advanced_inputs()
&& link == Some(&proposal.device_link)
&& snapshot
.screens
.iter()
.find(|s| s.id == proposal.device_link.screen)
.and_then(|s| {
input_path(
snapshot,
&s.id,
&s.preview_bank,
&proposal.device_link.layer,
)
})
.as_deref()
== Some(proposal.base().as_str())
}
fn stage_proposal(
&mut self,
proposal: &canvas_pilot::input_proposal::InputProposal,
snapshot: &Snapshot,
link: Option<&canvas_pilot::DeviceLink>,
) -> Result<(), String> {
if !self.enabled || !Self::proposal_matches(proposal, snapshot, link) {
return Err(
"Enable edits and verify the saved layer, input and plug mapping first.".into(),
);
}
let values: Vec<_> = proposal
.settings
.iter()
.map(|(key, value)| {
let path = format!("{}/{key}", proposal.base());
let original = snapshot
.raw
.pointer(&path)
.ok_or("Refresh device: proposal field unavailable.")?
.clone();
Ok((path, value.clone(), original))
})
.collect::<Result<_, String>>()?;
for (path, value, original) in values {
self.stage(path, value, &original);
}
Ok(())
}
fn stage(&mut self, path: String, value: Value, original: &Value) {
if &value == original {
self.values.remove(&path);
} else {
self.values.insert(path, value);
}
}
pub fn extend_plan(
&self,
snapshot: &Snapshot,
mappings: &[(usize, String)],
plan: &mut Plan,
) -> Result<(), String> {
if !self.enabled || !snapshot.profile.advanced_inputs() {
return Ok(());
}
let inputs: BTreeSet<_> = mappings
.iter()
.filter_map(|(_, layer)| input_path(snapshot, &plan.screen, &plan.bank, layer))
.collect();
let mut changes = Vec::new();
for (path, after) in &self.values {
if !inputs
.iter()
.any(|base| path.starts_with(&format!("{base}/")))
{
continue;
}
let before = snapshot
.raw
.pointer(path)
.ok_or("Refresh the device: a staged input setting is unavailable.")?;
if before != after {
changes.push(Change {
path: path
.trim_start_matches('/')
.split('/')
.map(str::to_owned)
.collect(),
before: before.clone(),
after: after.clone(),
});
}
}
changes.append(&mut plan.changes);
plan.changes = changes;
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use canvas_pilot::device_send::Target;
fn fixture() -> Snapshot {
Snapshot {
profile: Default::default(),
identity: "Test".into(),
screens: vec![],
raw: json!({"device": {"inputList": {"items": {"INPUT_4": {"status": {"pp": {"plug": "2"}}, "plugList": {"items": {"2": {"settings": {"aspect": {"pp": {"signal": "NATIVE", "transformTo": "SIGNAL", "customRatio": 1333, "layerFill": "LAYER_SETTING"}}, "cropping": {"control": {"pp": {"left": 0, "right": 0, "top": 0, "bottom": 0, "predefined": "NONE", "xUpdate": true}}}}}}}}}}, "screenList": {"items": {"1": {"presetList": {"items": {"UP": {"liveLayerList": {"items": {"1": {"source": {"pp": {"input": "INPUT_4"}}}, "2": {"source": {"pp": {"input": "INPUT_NONE"}}}}}}, "DOWN": {"liveLayerList": {"items": {"1": {"source": {"pp": {"input": "INPUT_NONE"}}}}}}}}}}}}}),
}
}
fn empty_plan() -> Plan {
Plan {
profile: Default::default(),
observed: vec![],
screen: "1".into(),
bank: "UP".into(),
target: Target::Preview,
changes: vec![],
}
}
#[test]
fn connected_source_controls_open_read_only_and_unchecking_discards_edits() {
let mut snapshot = fixture();
snapshot.screens.push(canvas_pilot::device::Screen {
id: "1".into(),
resolution: [1920, 1080],
preview_bank: "UP".into(),
program_bank: "DOWN".into(),
layers: vec![],
});
let link = canvas_pilot::DeviceLink {
family: Default::default(),
screen: "1".into(),
layer: "1".into(),
};
let ctx = egui::Context::default();
let mut edits = InputEdits::default();
let mut draw = |edits: &mut InputEdits, events| {
ctx.run_ui(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(900., 1000.),
)),
events,
..Default::default()
},
|root_ui| {
egui::CentralPanel::default().show(root_ui, |ui| {
edits.show(ui, Some(&snapshot), Some(&link), 1)
});
},
)
};
draw(&mut edits, vec![]);
let output = draw(&mut edits, vec![]);
assert!(!edits.enabled);
assert!(edits.values.is_empty());
assert!(output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(t) if t.galley.text() == "Content ratio")));
let pos = output
.shapes
.iter()
.find_map(|shape| match &shape.shape {
egui::Shape::Text(t)
if t.galley.text()
== "Edit advanced input settings and include my edits when sending" =>
{
Some(t.pos + egui::vec2(10., 5.))
}
_ => None,
})
.unwrap();
let click = |edits: &mut InputEdits,
draw: &mut dyn FnMut(
&mut InputEdits,
Vec<egui::Event>,
) -> egui::FullOutput| {
draw(
edits,
vec![
egui::Event::PointerMoved(pos),
super::super::tests::mouse(pos, true),
],
);
draw(edits, vec![super::super::tests::mouse(pos, false)]);
};
click(&mut edits, &mut draw);
assert!(edits.enabled);
assert!(edits.values.is_empty());
edits.stage("test".into(), json!(40), &json!(0));
click(&mut edits, &mut draw);
assert!(!edits.enabled);
assert!(edits.values.is_empty());
}
#[test]
fn default_enable_only_and_unrelated_layers_never_write_inputs() {
let snapshot = fixture();
let mappings = [(1, "1".into())];
let mut edits = InputEdits::default();
let mut plan = empty_plan();
edits.extend_plan(&snapshot, &mappings, &mut plan).unwrap();
assert!(plan.changes.is_empty());
edits.enabled = true;
edits.extend_plan(&snapshot, &mappings, &mut plan).unwrap();
assert!(plan.changes.is_empty());
let path = format!(
"{}/cropping/control/pp/left",
input_path(&snapshot, "1", "UP", "1").unwrap()
);
edits.stage(path.clone(), json!(40), &json!(0));
edits
.extend_plan(&snapshot, &[(2, "2".into())], &mut plan)
.unwrap();
assert!(plan.changes.is_empty());
edits.extend_plan(&snapshot, &mappings, &mut plan).unwrap();
assert_eq!(plan.changes.len(), 1);
assert_eq!(plan.changes[0].path.join("/"), path.trim_start_matches('/'));
assert_eq!(plan.changes[0].after, json!(40));
// Program has a different routed source and must not receive Preview input edits.
let mut program = empty_plan();
program.bank = "DOWN".into();
program.target = Target::Program;
edits
.extend_plan(&snapshot, &mappings, &mut program)
.unwrap();
assert!(program.changes.is_empty());
edits.enabled = false;
let mut disabled = empty_plan();
edits
.extend_plan(&snapshot, &mappings, &mut disabled)
.unwrap();
assert!(disabled.changes.is_empty());
edits.clear();
assert!(edits.values.is_empty());
assert!(!edits.enabled);
}
#[test]
fn reverted_values_are_not_staged_and_duplicate_routes_are_written_once() {
let snapshot = fixture();
let path = format!(
"{}/aspect/pp/transformTo",
input_path(&snapshot, "1", "UP", "1").unwrap()
);
let mut edits = InputEdits {
enabled: true,
..Default::default()
};
edits.stage(path.clone(), json!("16_9"), &json!("SIGNAL"));
let mut plan = empty_plan();
edits
.extend_plan(&snapshot, &[(1, "1".into()), (2, "1".into())], &mut plan)
.unwrap();
assert_eq!(plan.changes.len(), 1);
edits.stage(path, json!("SIGNAL"), &json!("SIGNAL"));
assert!(edits.values.is_empty());
}
#[test]
fn restored_proposals_are_inert_and_stage_only_after_route_and_field_review() {
let mut snapshot = fixture();
snapshot.screens.push(canvas_pilot::device::Screen {
id: "1".into(),
resolution: [1920, 1080],
preview_bank: "UP".into(),
program_bank: "DOWN".into(),
layers: vec![],
});
let proposal = canvas_pilot::input_proposal::InputProposal {
layer_id: 1,
device_link: canvas_pilot::DeviceLink {
family: Default::default(),
screen: "1".into(),
layer: "1".into(),
},
input: "INPUT_4".into(),
plug: "2".into(),
settings: [
("aspect/pp/transformTo".into(), json!("CUSTOM")),
("aspect/pp/customRatio".into(), json!(1778)),
]
.into(),
};
let mut edits = InputEdits {
saved: vec![proposal.clone()],
..Default::default()
};
let link = Some(&proposal.device_link);
let mut plan = empty_plan();
edits
.extend_plan(&snapshot, &[(1, "1".into())], &mut plan)
.unwrap();
assert!(plan.changes.is_empty());
assert!(edits.stage_proposal(&proposal, &snapshot, link).is_err());
edits.enabled = true;
edits
.extend_plan(&snapshot, &[(1, "1".into())], &mut plan)
.unwrap();
assert!(
plan.changes.is_empty(),
"Enabling alone must not stage saved data"
);
let mut wrong = proposal.clone();
wrong.input = "INPUT_9".into();
assert!(edits.stage_proposal(&wrong, &snapshot, link).is_err());
assert!(edits.stage_proposal(&proposal, &snapshot, None).is_err());
let mut missing = snapshot.clone();
missing
.raw
.pointer_mut("/device/inputList/items/INPUT_4/plugList/items/2/settings/aspect/pp")
.unwrap()
.as_object_mut()
.unwrap()
.remove("transformTo");
assert!(edits.stage_proposal(&proposal, &missing, link).is_err());
assert!(
edits.values.is_empty(),
"Missing fields reject staging atomically"
);
edits.stage_proposal(&proposal, &snapshot, link).unwrap();
edits
.extend_plan(&snapshot, &[(1, "1".into())], &mut plan)
.unwrap();
assert_eq!(plan.changes.len(), 2);
assert!(plan.changes.iter().all(|c| {
c.path
.join("/")
.starts_with("device/inputList/items/INPUT_4/plugList/items/2/settings/aspect/pp/")
}));
edits.clear();
assert!(!edits.enabled && edits.values.is_empty());
assert_eq!(edits.saved, vec![proposal]);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -251,3 +251,36 @@ pub fn read_project_or_parameters(path: &std::path::Path) -> Result<(Project, bo
}
read_embedded_project(path).map(|p| (p, false))
}
/// User-requested native-project opening is recoverable; embedded artwork remains strict.
pub fn read_project_for_open(
path: &std::path::Path,
) -> Result<(crate::project_recovery::LoadedProject, bool), String> {
use std::io::Read;
let mut bytes = Vec::new();
std::fs::File::open(path)
.map_err(|e| e.to_string())?
.take(crate::project::MAX_PROJECT_BYTES + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() as u64 > crate::project::MAX_PROJECT_BYTES {
return Err("Project exceeds 96 MiB.".into());
}
if let Ok(value) = serde_json::from_slice::<serde_json::Value>(&bytes)
&& value["format"] == crate::project::FORMAT
{
return crate::project_recovery::from_json(
std::str::from_utf8(&bytes).map_err(|e| e.to_string())?,
)
.map(|p| (p, true));
}
read_embedded_project(path).map(|project| {
(
crate::project_recovery::LoadedProject {
project,
warnings: Vec::new(),
},
false,
)
})
}

View File

@ -49,6 +49,7 @@ pub(super) struct LayerDrag(pub usize);
#[derive(Clone)]
pub(super) struct FolderDrag(pub String);
#[derive(Clone, PartialEq)]
pub(super) enum TreeRow {
Folder(String),
Layer(usize),
@ -60,6 +61,8 @@ pub(super) struct LayerUi {
pub(super) collapsed: std::collections::BTreeSet<String>,
pub(super) folder_rename: Option<(Option<String>, String, Vec<usize>)>,
folder_move: Option<(String, usize, bool)>,
reorder_requested: Option<(usize, usize)>,
pub(super) add_requested: bool,
last_folder_click: Option<String>,
assign: Option<(Vec<usize>, String)>,
pub context_layer: Option<usize>,
@ -108,6 +111,16 @@ impl Editor {
} else {
vec![id]
};
for (label, up) in [("Move up", true), ("Move down", false)] {
let target = self.tree_step_target(&TreeRow::Layer(i), up);
if ui
.add_enabled(target.is_some(), egui::Button::new(label))
.clicked()
{
self.layer_ui.reorder_requested = target.map(|to| (id, to));
ui.close();
}
}
ui.menu_button(tr(ui.ctx(), "ui.move-to-folder"), |ui| {
if ui.button(tr(ui.ctx(), "ui.no-folder")).clicked() {
self.layer_ui.assign = Some((ids.clone(), String::new()));
@ -263,14 +276,18 @@ impl Editor {
}
if self.layer_ui.rename_closing {
match pending_close(ctx, "rename-close", &self.error) {
Some(true) => {
Some(CloseChoice::Apply) => {
apply = true;
self.layer_ui.rename_closing = false;
}
Some(false) => {
Some(CloseChoice::Discard) => {
cancel = true;
self.layer_ui.rename_closing = false;
}
Some(CloseChoice::Cancel) => {
self.layer_ui.rename_closing = false;
open = true;
}
None => {}
}
}
@ -381,8 +398,11 @@ impl Editor {
refresh = false;
open = true;
let choice = pending_close(ctx, "names-close", &self.layer_ui.error);
if let Some(apply) = choice {
let result = if apply {
if choice == Some(CloseChoice::Cancel) {
self.layer_ui.closing = false;
self.layer_ui.deferred = 0;
} else if let Some(choice) = choice {
let result = if choice == CloseChoice::Apply {
self.layout.rename_layers(&self.layer_ui.drafts)
} else {
Ok(())
@ -450,31 +470,109 @@ impl Editor {
rows
}
pub(super) fn layer_tree_header(&mut self, ui: &mut egui::Ui, ink: &Ink, width: f32) {
if toolbar_icon(
ui,
Rect::from_min_size(ink.point(width - 92.0, -5.0), Vec2::new(28.0, 24.0)),
"Create folder",
ToolbarIcon::AddFolder,
)
.clicked()
{
self.layer_ui.folder_rename = Some((None, "New folder".into(), Vec::new()));
self.layer_ui.rename_focus = true;
// Step through visible siblings: folder contents stay in their folder,
// while root layers and nonempty folders move past one another as blocks.
fn tree_step_target(&self, row: &TreeRow, up: bool) -> Option<usize> {
if let TreeRow::Layer(i) = row {
let folder = &self.layout.layer_info(*i).folder;
if !folder.is_empty() {
let members = self.layout.folder_members(folder);
let position = members.iter().position(|j| j == i)?;
return members
.get(if up {
position + 1
} else {
position.checked_sub(1)?
})
.copied();
}
}
let root = ui.interact(
Rect::from_min_size(ink.point(0.0, -5.0), Vec2::new(60.0, 24.0)),
egui::Id::new("layer-root"),
egui::Sense::hover(),
);
if root.dnd_hover_payload::<LayerDrag>().is_some() {
let roots: Vec<_> = self
.layer_tree_rows()
.into_iter()
.filter(|row| match row {
TreeRow::Layer(i) => self.layout.layer_info(*i).folder.is_empty(),
TreeRow::Folder(name) => !self.layout.folder_members(name).is_empty(),
})
.collect();
let position = roots.iter().position(|candidate| candidate == row)?;
match roots.get(if up {
position.checked_sub(1)?
} else {
position + 1
})? {
TreeRow::Layer(i) => Some(*i),
TreeRow::Folder(name) => {
let members = self.layout.folder_members(name);
if up {
members.last().copied()
} else {
members.first().copied()
}
}
}
}
pub(super) fn add_layer_menu(&mut self, ui: &mut egui::Ui) {
if ui
.add_enabled(
self.layout.layers().len() < 256,
egui::Button::new(tr(ui.ctx(), "ui.add-layer")),
)
.clicked()
{
self.layer_ui.add_requested = true;
ui.close();
}
}
pub(super) fn root_drop_target(
&mut self,
ui: &mut egui::Ui,
rect: Rect,
id: egui::Id,
caption: bool,
) {
let palette = theme::palette(ui.ctx());
let root = ui.interact(rect, id, egui::Sense::hover());
let hovering = root.dnd_hover_payload::<LayerDrag>().is_some();
if hovering {
ui.painter()
.rect_filled(rect, 3.0, palette.cyan.gamma_multiply(0.18));
if !caption {
let c = rect.center();
ui.painter().arrow(
c + Vec2::new(8.0, 0.0),
Vec2::new(-16.0, 0.0),
Stroke::new(2.0, palette.cyan),
);
}
}
if caption || hovering {
ui.painter().rect_stroke(
root.rect,
rect,
3.0,
Stroke::new(1.0_f32, theme::palette(ui.ctx()).cyan),
Stroke::new(1.0, if hovering { palette.cyan } else { palette.line }),
StrokeKind::Inside,
);
}
if caption {
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
if hovering {
"Release to move out of folder"
} else {
"No folder — drop layer here"
},
egui::FontId::proportional(12.0),
if hovering {
palette.cyan
} else {
palette.muted
},
);
}
if let Some(payload) = root.dnd_release_payload::<LayerDrag>() {
self.layer_ui.assign = Some((vec![payload.0], String::new()));
}
@ -484,6 +582,42 @@ impl Editor {
));
}
pub(super) fn layer_tree_header(&mut self, ui: &mut egui::Ui, ink: &Ink, width: f32) {
if toolbar_icon(
ui,
Rect::from_min_size(ink.point(width - 92.0, 0.0), Vec2::new(28.0, 24.0)),
"Create folder",
ToolbarIcon::AddFolder,
)
.clicked()
{
self.layer_ui.folder_rename = Some((None, "New folder".into(), Vec::new()));
self.layer_ui.rename_focus = true;
}
self.root_drop_target(
ui,
Rect::from_min_size(
ink.point(0.0, -5.0),
Vec2::new((width - 132.0).max(60.0), 24.0),
),
egui::Id::new("layer-root"),
false,
);
let add = ui
.add_enabled_ui(self.layout.layers().len() < 256, |ui| {
toolbar_icon(
ui,
Rect::from_min_size(ink.point(width - 124.0, 0.0), Vec2::new(28.0, 24.0)),
"Add layer",
ToolbarIcon::AddLayer,
)
})
.inner;
if add.clicked() {
self.layer_ui.add_requested = true;
}
}
pub(super) fn folder_drop_on_layer(&mut self, row: &egui::Response, i: usize) {
if let Some(payload) = row.dnd_release_payload::<FolderDrag>() {
let above = row
@ -671,34 +805,14 @@ impl Editor {
ui.close();
}
}
let folders = self.layout.folders();
let position = folders.iter().position(|name| name == folder).unwrap();
for (label, target, above) in [
("Move folder up", position.checked_sub(1), true),
(
"Move folder down",
(position + 1 < folders.len()).then_some(position + 1),
false,
),
] {
for (label, up) in [("Move up", true), ("Move down", false)] {
let target = self.tree_step_target(&TreeRow::Folder(folder.into()), up);
if ui
.add_enabled(
!members.is_empty()
&& target.is_some_and(|i| {
!self.layout.folder_members(&folders[i]).is_empty()
}),
egui::Button::new(label),
)
.add_enabled(target.is_some(), egui::Button::new(label))
.clicked()
{
let target_members = self.layout.folder_members(&folders[target.unwrap()]);
let index = if above {
*target_members.last().unwrap()
} else {
target_members[0]
};
self.layer_ui.folder_move =
Some((folder.into(), self.layout.layer_info(index).id, above));
target.map(|i| (folder.into(), self.layout.layer_info(i).id, up));
ui.close();
}
}
@ -738,6 +852,20 @@ impl Editor {
}
fn folder_commands(&mut self, ctx: &egui::Context) {
if std::mem::take(&mut self.layer_ui.add_requested) {
match self.layout.add_layer() {
Ok(_) => {
self.sync();
if self.layer_ui.open {
self.manage_layers();
}
}
Err(error) => self.error = error,
}
}
if let Some((id, to)) = self.layer_ui.reorder_requested.take() {
self.reorder_layer(id, to);
}
let result = if let Some(folder) = self.layer_ui.folder_remove.take() {
self.layer_ui.collapsed.remove(&folder);
Some(self.layout.ungroup_folder(&folder))
@ -841,6 +969,186 @@ impl Editor {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quick_add_icon_selects_new_layer_without_opening_manager() {
use super::super::tests::{frame, mouse};
let mut app = Editor::default();
let ctx = egui::Context::default();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
let header = ctx.read_response(egui::Id::new("layer-root")).unwrap().rect;
let point = Pos2::new(header.right() + 22.0, header.center().y);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(point), mouse(point, true)],
);
frame(&mut app, &ctx, vec![mouse(point, false)]);
assert_eq!(app.layout.layers().len(), 3);
assert_eq!(app.layout.selected(), Some(2));
assert!(!app.layer_ui.open);
app.layout.undo();
assert_eq!(app.layout.layers().len(), 2);
}
#[test]
fn viewport_add_layer_is_available_without_selection() {
use super::super::tests::mouse;
let mut app = Editor::default();
app.layout.select(None);
let ctx = egui::Context::default();
let mut render = |events| {
ctx.run_ui(
egui::RawInput {
events,
..Default::default()
},
|root| {
egui::CentralPanel::default().show(root, |ui| app.layer_context_menu(ui));
},
)
};
render(vec![]);
let output = render(vec![]);
let point = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == "Add layer" => {
Some(t.pos + t.galley.size() * 0.5)
}
_ => None,
})
.unwrap();
render(vec![egui::Event::PointerMoved(point), mouse(point, true)]);
render(vec![mouse(point, false)]);
app.folder_commands(&ctx);
assert_eq!(app.layout.layers().len(), 3);
assert_eq!(app.layout.selected(), Some(2));
assert!(!app.layer_ui.open);
}
#[test]
fn stacking_steps_cross_whole_folders_and_keep_children_inside() {
let mut app = Editor::default();
app.layout.add_layer().unwrap();
app.layout.assign_folder(&[1, 2], "Video").unwrap();
assert_eq!(app.tree_step_target(&TreeRow::Layer(2), true), None);
assert_eq!(app.tree_step_target(&TreeRow::Layer(2), false), Some(0));
let target = app.tree_step_target(&TreeRow::Layer(2), false).unwrap();
app.reorder_layer(3, target);
assert_eq!(app.layout.layer_info(0).id, 3);
assert_eq!(app.layout.folder_members("Video"), [1, 2]);
assert_eq!(app.tree_step_target(&TreeRow::Layer(1), true), Some(2));
assert_eq!(app.tree_step_target(&TreeRow::Layer(2), true), None);
let target = app
.tree_step_target(&TreeRow::Folder("Video".into()), false)
.unwrap();
let id = app.layout.layer_info(target).id;
app.layout.move_folder("Video", id, false).unwrap();
assert_eq!(app.layout.folder_members("Video"), [0, 1]);
assert_eq!(app.layout.layer_info(2).id, 3);
app.layout.undo();
assert_eq!(app.layout.layer_info(0).id, 3);
}
#[test]
fn folder_gutter_accepts_edges_and_row_gaps_without_reordering_and_can_cancel() {
use super::super::tests::{frame, mouse};
for gap in [false, true] {
for cancel in [false, true] {
let mut app = Editor::default();
let ctx = egui::Context::default();
app.layout.assign_folder(&[1, 2], "Video").unwrap();
let before = app.project();
let geometry = app.layout.layers().clone();
let order: Vec<_> = (0..app.layout.layers().len())
.map(|i| app.layout.layer_info(i).id)
.collect();
frame(&mut app, &ctx, vec![]);
frame(&mut app, &ctx, vec![]);
let start = ctx
.read_response(egui::Id::new(("layer", 1_usize)))
.unwrap()
.rect
.center();
let gutter = ctx
.read_response(egui::Id::new(("layer-root-gutter", 2_usize)))
.unwrap()
.rect;
assert!(gutter.width() >= 32.0);
let end = if gap {
gutter.left_bottom() + Vec2::new(1.0, -1.0)
} else {
gutter.right_center() - Vec2::new(1.0, 0.0)
};
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start), mouse(start, true)],
);
frame(
&mut app,
&ctx,
vec![egui::Event::PointerMoved(start + Vec2::new(0.0, 12.0))],
);
frame(&mut app, &ctx, vec![egui::Event::PointerMoved(end)]);
if cancel {
frame(
&mut app,
&ctx,
vec![egui::Event::Key {
key: egui::Key::Escape,
physical_key: None,
pressed: true,
repeat: false,
modifiers: egui::Modifiers::NONE,
}],
);
}
frame(&mut app, &ctx, vec![mouse(end, false)]);
frame(&mut app, &ctx, vec![]);
assert_eq!(app.layout.layers(), &geometry);
assert_eq!(
(0..app.layout.layers().len())
.map(|i| app.layout.layer_info(i).id)
.collect::<Vec<_>>(),
order
);
if cancel {
assert_eq!(app.project(), before);
} else {
assert_eq!(app.layout.folder_members("Video").len(), 1);
app.layout.undo();
assert_eq!(app.project(), before);
}
}
}
}
#[test]
fn wide_root_drop_ungroups_and_undo_restores_membership() {
let mut app = Editor::default();
let ctx = egui::Context::default();
app.layout.assign_folder(&[1, 2], "Video").unwrap();
drag_tree(
&mut app,
&ctx,
egui::Id::new(("layer", 1_usize)),
egui::Id::new("layer-root-drop"),
false,
);
let members = app.layout.folder_members("Video");
assert_eq!(members.len(), 1);
assert_eq!(app.layout.layer_info(members[0]).id, 2);
let moved = (0..app.layout.layers().len())
.find(|&i| app.layout.layer_info(i).id == 1)
.unwrap();
assert!(app.layout.layer_info(moved).folder.is_empty());
app.layout.undo();
assert_eq!(app.layout.folder_members("Video"), [0, 1]);
}
#[test]
fn empty_layer_list_space_clears_selection() {
use super::super::tests::{frame, mouse};
@ -1205,6 +1513,19 @@ mod tests {
assert_eq!(app.layout.layer_info(1), &before);
}
}
#[test]
fn cancelling_rename_close_keeps_the_name_draft() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let id = app.layout.layer_info(1).id;
app.layer_ui.rename = Some((id, "Camera".into()));
app.layer_ui.rename_closing = true;
super::super::tests::cancel_pending_close(&mut app, &ctx);
assert!(!app.layer_ui.rename_closing);
assert_eq!(app.layer_ui.rename, Some((id, "Camera".into())));
assert_eq!(app.layout.layer_info(1).name, "Presenter");
}
#[test]
fn closing_batch_names_applies_or_discards_without_losing_identity() {
let ctx = egui::Context::default();
@ -1213,6 +1534,16 @@ mod tests {
let id = app.layout.layer_info(1).id;
app.layer_ui.drafts[1].1 = "Camera".into();
app.layer_ui.closing = true;
app.layer_ui.deferred = 1;
let count = app.layout.layers().len();
super::super::tests::click_text(&mut app, &ctx, "Cancel");
assert!(app.layer_ui.open);
assert!(!app.layer_ui.closing);
assert_eq!(app.layer_ui.deferred, 0);
assert_eq!(app.layer_ui.drafts[1].1, "Camera");
assert_eq!(app.layout.layers().len(), count);
assert_eq!(app.layout.layer_info(1).name, "Presenter");
app.layer_ui.closing = true;
super::super::tests::click_text(&mut app, &ctx, "Apply");
assert!(!app.layer_ui.open);
assert_eq!(app.layout.layer_info(1).name, "Camera");

View File

@ -1,8 +1,12 @@
//! Layer geometry, reversible edits and bounded imports.
mod device_mapping;
pub use device_mapping::{ConnectionTarget, SendDestination, SendMapping};
pub mod clipboard;
pub mod device;
pub mod device_capture;
pub mod device_inputs;
pub mod device_send;
mod device_send_log;
use std::collections::HashMap;
pub mod exchange;
pub mod exchange_metadata;
@ -10,10 +14,13 @@ mod folders;
pub mod formats;
mod geometry_formats;
pub mod import;
pub mod input_proposal;
pub mod interchange;
pub mod project;
pub mod project_recovery;
pub mod reference_document;
pub mod size_presets;
pub mod snapping;
pub mod software;
#[cfg(all(feature = "vendor_formats", not(feature = "no_proprietary")))]
mod vendor_formats;
use formats::{Formats, Framing, Source};
@ -470,7 +477,9 @@ impl DeviceLink {
#[serde(deny_unknown_fields)]
pub struct LayerInfo {
pub pivot: [f64; 2],
pub device_link: Option<DeviceLink>,
pub keep_aspect_ratio: bool,
pub load_mapping: Option<DeviceLink>,
pub send_mapping: SendMapping,
pub id: usize,
pub name: String,
pub folder: String,
@ -499,6 +508,7 @@ pub struct Layout {
drag: Option<(Vec<bool>, Snapshot, [f64; 2])>,
content_drag: Option<(usize, Snapshot, [f64; 2])>,
content_resize: Option<Resize>,
pending_edge_crop: Option<formats::Crop>,
mask_drag: Option<(usize, Snapshot, [f64; 2], Option<ResizeHandle>)>,
pub gesture_error: Option<String>,
resize: Option<Resize>,
@ -565,14 +575,18 @@ impl Default for Layout {
info: vec![
LayerInfo {
pivot: [0.5; 2],
device_link: None,
keep_aspect_ratio: true,
load_mapping: None,
send_mapping: Default::default(),
id: 2,
name: "Slides".into(),
folder: String::new(),
},
LayerInfo {
pivot: [0.5; 2],
device_link: None,
keep_aspect_ratio: true,
load_mapping: None,
send_mapping: Default::default(),
id: 1,
name: "Presenter".into(),
folder: String::new(),
@ -599,6 +613,7 @@ impl Default for Layout {
formats: Formats::default(),
content_drag: None,
content_resize: None,
pending_edge_crop: None,
mask_drag: None,
gesture_error: None,
undo: Vec::new(),
@ -640,19 +655,33 @@ impl Layout {
self.layers = s.layers;
self.formats = s.formats;
}
/// Current UI contract: change both directions together, with one send target.
pub fn set_device_link(&mut self, i: usize, link: Option<DeviceLink>) -> Result<(), String> {
let send = SendMapping::linked(link.clone());
self.set_device_mappings(i, link, send)
}
/// Independent routing model; the current UI only uses `set_device_link`.
pub fn set_device_mappings(
&mut self,
i: usize,
load: Option<DeviceLink>,
send: SendMapping,
) -> Result<(), String> {
if i >= self.info.len() {
return Err("Layer no longer exists.".into());
}
if let Some(link) = &link {
if let Some(link) = &load {
link.validate()?;
}
if self.info[i].device_link == link {
send.validate()?;
if self.info[i].load_mapping == load && self.info[i].send_mapping == send {
return Ok(());
}
self.finish_drag();
let before = self.snapshot();
self.info[i].device_link = link;
self.info[i].load_mapping = load;
self.info[i].send_mapping = send;
self.remember(before);
Ok(())
}
@ -735,7 +764,9 @@ impl Layout {
self.layers.push(g);
self.info.push(LayerInfo {
pivot: [0.5; 2],
device_link: None,
keep_aspect_ratio: true,
load_mapping: None,
send_mapping: Default::default(),
id: self.next_id,
name: format!("Layer {}", self.next_id),
folder: String::new(),
@ -812,6 +843,55 @@ impl Layout {
pub fn formats(&self) -> &Formats {
&self.formats
}
/// Reframe only this layer for a replacement signal, preserving its output box.
pub fn set_layer_source_resolution(
&mut self,
i: usize,
native: [u32; 2],
) -> Result<(), String> {
formats::validate_resolution(native)?;
let g = *self.layers.get(i).ok_or("Layer unavailable")?;
let old = self.formats.input(i)?;
if old == native.map(f64::from) {
return Ok(());
}
let input = native.map(f64::from);
let crop = self.formats.advanced[i];
let next_crop = if self.formats.layer_fit[i].is_some() {
formats::Crop {
left: crop.left * input[0] / old[0],
right: crop.right * input[0] / old[0],
top: crop.top * input[1] / old[1],
bottom: crop.bottom * input[1] / old[1],
}
} else {
formats::reframed(old, [g.width, g.height], crop, input, [g.width, g.height])?.0
};
next_crop.remaining(input)?;
self.finish_drag();
let before = self.snapshot();
let source = self.formats.source_for[i];
let replacement = Source {
native,
aspect: formats::Aspect::Custom,
};
if self
.formats
.source_for
.iter()
.filter(|&&id| id == source)
.count()
> 1
{
self.formats.source_for[i] = self.formats.sources.len();
self.formats.sources.push(replacement);
} else {
self.formats.sources[source] = replacement;
}
self.formats.advanced[i] = next_crop;
self.remember(before);
Ok(())
}
pub fn set_output(&mut self, output: [u32; 2]) -> Result<(), String> {
formats::validate_resolution(output)?;
self.finish_drag();
@ -954,15 +1034,81 @@ impl Layout {
}
/// Resize content in normal crop mode, or trim source pixels in centered 1:1 mode.
/// The layer container stays fixed; 1:1 ignores proportional scaling and pivots.
pub fn start_content_resize(&mut self, index: usize, handle: ResizeHandle, point: [f64; 2]) {
if self
.formats
.layer_fit
.get(index)
.is_some_and(|mode| mode.is_some_and(|fit| fit != formats::LayerFit::OneToOne))
{
return;
/// Pending retained-image bounds under the frozen source transform.
pub fn edge_crop_bounds(&self, i: usize) -> Result<Geometry, String> {
let crop = self.formats.advanced[i];
let input = self.formats.input(i)?;
let retained = crop.remaining(input)?;
let image = self.formats.layer_fit[i]
.ok_or("No advanced fit")?
.image(retained, self.layers[i])?;
let pending = self
.content_resize
.as_ref()
.filter(|r| r.index == i)
.and(self.pending_edge_crop)
.unwrap_or(crop);
let size = pending.remaining(input)?;
Ok(Geometry {
x: image.x + (pending.left - crop.left) * image.width / retained[0],
y: image.y + (pending.top - crop.top) * image.height / retained[1],
width: size[0] * image.width / retained[0],
height: size[1] * image.height / retained[1],
})
}
/// Switch to normal cover framing, retaining an exactly representable crop.
pub fn convert_to_smart_crop(&mut self, i: usize) -> Result<(), String> {
if !self.selectable(i) {
return Err("Unlock and show this layer first.".into());
}
self.finish_drag();
let g = self.layers[i];
let input = self.formats.input(i)?;
let crop = self.formats.advanced[i];
let exact = self.formats.layer_fit[i].is_none_or(|fit| {
fit.image(crop.remaining(input).unwrap_or(input), g)
.is_ok_and(|image| {
(image.width - g.width).abs() < 1e-7 && (image.height - g.height).abs() < 1e-7
})
}) && crop
.remaining(input)
.is_ok_and(|r| (g.width / r[0] - g.height / r[1]).abs() < 1e-10)
&& formats::mapping(input, [g.width, g.height], crop).is_ok();
let before = self.snapshot();
self.formats.advanced[i] = if exact {
crop
} else {
formats::crop_from_framing(input, [g.width, g.height], Framing::default())?
};
self.formats.layer_fit[i] = None;
self.remember(before);
Ok(())
}
/// Switch a normal crop to Centered edge crop without changing its picture.
pub fn convert_to_edge_crop(&mut self, i: usize) -> Result<(), String> {
if !self.selectable(i) {
return Err("Unlock and show this layer first.".into());
}
if self.formats.layer_fit[i].is_some() {
return Ok(());
}
self.finish_drag();
let geometry = self.layers[i];
let crop = self.formats.advanced[i];
formats::mapping(
self.formats.input(i)?,
[geometry.width, geometry.height],
crop,
)?;
let before = self.snapshot();
self.formats.layer_fit[i] = Some(formats::LayerFit::Centered);
self.remember(before);
Ok(())
}
pub fn start_content_resize(&mut self, index: usize, handle: ResizeHandle, point: [f64; 2]) {
self.finish_drag();
if !self.selectable(index)
|| self.selected() != Some(index)
@ -1080,7 +1226,6 @@ impl Layout {
let input = source.input()?;
let m = f.mapping(i, g)?;
let a = f.advanced[i];
let c = source.input_crop;
let projected = Geometry {
x: g.x - m.scale * a.left,
y: g.y - m.scale * a.top,
@ -1088,15 +1233,11 @@ impl Layout {
height: m.scale * input[1],
};
Ok(format!(
"PROVISIONAL GEOMETRY — not a verified device recipe\nSource {} / {} / {} x {}\nInput crop L/R/T/B (native px): {} / {} / {} / {}\nInput resolution: {} x {}\nLayer resolution: {} x {}; visible center: {}, {}\nAdvanced crop L/R/T/B (usable-input px): {} / {} / {} / {}\nCombined native retained region: x {}, y {}, w {}, h {}\nContent zoom: {}%; offsets (output px): {}, {}\nProjected full usable input: {} x {}; center {}, {}\nIntended aspect mode: Centered. Device container, crop units and quantization remain unverified.",
"PROVISIONAL GEOMETRY — not a verified device recipe\nSource {} / {} / {} x {}\nInput resolution: {} x {}\nLayer resolution: {} x {}; visible center: {}, {}\nAdvanced crop L/R/T/B (usable-input px): {} / {} / {} / {}\nRetained source region: x {}, y {}, w {}, h {}\nContent zoom: {}%; offsets (output px): {}, {}\nProjected full usable input: {} x {}; center {}, {}\nIntended aspect mode: Centered. Device container, crop units and quantization remain unverified.",
f.source_for[i] + 1,
source.aspect.label(),
source.native[0],
source.native[1],
p(c.left),
p(c.right),
p(c.top),
p(c.bottom),
p(input[0]),
p(input[1]),
p(g.width),
@ -1107,8 +1248,8 @@ impl Layout {
p(a.right),
p(a.top),
p(a.bottom),
p(c.left + a.left),
p(c.top + a.top),
p(a.left),
p(a.top),
p(m.retained[0]),
p(m.retained[1]),
view_pixels(m.framing.zoom * 100.0),
@ -1155,6 +1296,22 @@ impl Layout {
}
self.remember(before);
}
/// Change the resize lock for one layer as an undoable layer property.
pub fn set_keep_aspect_ratio(&mut self, index: usize, keep: bool) -> Result<(), String> {
let current = self
.info
.get(index)
.ok_or("Layer no longer exists.")?
.keep_aspect_ratio;
if current == keep {
return Ok(());
}
self.finish_drag();
let before = self.snapshot();
self.info[index].keep_aspect_ratio = keep;
self.remember(before);
Ok(())
}
/// A single selected layer, or None for zero/multiple selections.
pub fn selected(&self) -> Option<usize> {
let indices = self.selected_indices();
@ -1405,8 +1562,53 @@ impl Layout {
)?;
}
if let Some((source, crop)) = framing {
let mut imported_crop = *crop;
if let Some(mode) = fit {
mode.image(crop.remaining(source.input()?)?, *geometry)?;
let image = mode.image(crop.remaining(source.input()?)?, *geometry)?;
// Normalize only an identical, uniformly scaled visible rectangle.
if (image.width - geometry.width).abs() < 1e-7
&& (image.height - geometry.height).abs() < 1e-7
&& crop.remaining(source.input()?).is_ok_and(|r| {
(geometry.width / r[0] - geometry.height / r[1]).abs() < 1e-10
})
&& formats::mapping(
source.input()?,
[geometry.width, geometry.height],
*crop,
)
.is_ok()
{
draft.formats.layer_fit[i] = None;
} else if matches!(
mode,
formats::LayerFit::Centered | formats::LayerFit::Cropped
) && (image.width - geometry.width).abs() <= 1.0
&& (image.height - geometry.height).abs() <= 1.0
{
// Device crop fractions can round a uniform fit away from the
// exact box aspect. Trim symmetrically to cover, preserving
// the source-space center and never revealing new pixels.
let input = source.input()?;
let retained = crop.remaining(input)?;
let scale =
(geometry.width / retained[0]).max(geometry.height / retained[1]);
let trim = [
((retained[0] - geometry.width / scale) / 2.0).max(0.0),
((retained[1] - geometry.height / scale) / 2.0).max(0.0),
];
let normalized = formats::Crop {
left: crop.left + trim[0],
right: crop.right + trim[0],
top: crop.top + trim[1],
bottom: crop.bottom + trim[1],
};
if formats::mapping(input, [geometry.width, geometry.height], normalized)
.is_ok()
{
imported_crop = normalized;
draft.formats.layer_fit[i] = None;
}
}
} else {
formats::mapping(source.input()?, [geometry.width, geometry.height], *crop)?;
}
@ -1429,7 +1631,7 @@ impl Layout {
};
draft.formats.sources[source_id] = *source;
draft.formats.source_for[i] = source_id;
draft.formats.advanced[i] = *crop;
draft.formats.advanced[i] = imported_crop;
}
}
self.finish_drag();
@ -1499,7 +1701,8 @@ impl Layout {
draft.info[i].folder = new_folder.trim().into();
i
};
draft.info[i].device_link = Some(link.clone());
draft.info[i].load_mapping = Some(link.clone());
draft.info[i].send_mapping = SendMapping::linked(Some(link.clone()));
}
self.finish_drag();
let before = self.snapshot();
@ -1763,13 +1966,15 @@ impl Layout {
let i = r.index;
let g = r.before.layers[i];
let input = r.before.formats.input(i)?;
if r.before.formats.layer_fit[i] == Some(formats::LayerFit::OneToOne) {
if let Some(fit) = r.before.formats.layer_fit[i] {
let mut crop = r.before.formats.advanced[i];
let remaining = crop.remaining(input)?;
// The retained image stays centered: moving a displayed edge
// by d changes retained size by 2d. Only the chosen source
// crop edge changes; pixel scale and container never change.
let delta = [2.0 * (point[0] - r.start[0]), 2.0 * (point[1] - r.start[1])];
// Freeze the source transform until release; each edge follows the pointer.
let image = fit.image(remaining, g)?;
let delta = [
(point[0] - r.start[0]) * remaining[0] / image.width,
(point[1] - r.start[1]) * remaining[1] / image.height,
];
let left = matches!(
r.handle,
ResizeHandle::Left
@ -1892,7 +2097,11 @@ impl Layout {
})();
match result {
Ok(crop) => {
self.formats.advanced[r.index] = crop;
if r.before.formats.layer_fit[r.index].is_some() {
self.pending_edge_crop = Some(crop);
} else {
self.formats.advanced[r.index] = crop;
}
self.gesture_error = None;
}
Err(e) => self.gesture_error = Some(e),
@ -2076,6 +2285,9 @@ impl Layout {
self.remember(before);
}
if let Some(r) = self.content_resize.take() {
if let Some(crop) = self.pending_edge_crop.take() {
self.formats.advanced[r.index] = crop;
}
self.remember(r.before);
}
if let Some((_, before, _)) = self.content_drag.take() {
@ -2089,6 +2301,7 @@ impl Layout {
}
}
pub fn cancel_drag(&mut self) {
self.pending_edge_crop = None;
if let Some((_, before, _, _)) = self.mask_drag.take() {
self.restore(before);
}

View File

@ -504,7 +504,6 @@ mod tests {
include_str!("capture_ui.rs"),
include_str!("layers_ui.rs"),
include_str!("format_ui.rs"),
include_str!("input_ui.rs"),
include_str!("ratio_ui.rs"),
include_str!("reference_ui.rs"),
include_str!("recovery_ui.rs"),

View File

@ -12,6 +12,7 @@ const AMBER: Color32 = Color32::from_rgb(246, 197, 119);
const PURPLE: Color32 = Color32::from_rgb(102, 85, 217);
fn main() -> eframe::Result {
canvas_pilot::software::detected();
eframe::run_native(
"Canvas Pilot",
eframe::NativeOptions {
@ -52,6 +53,7 @@ mod gui;
mod reference;
mod settings;
mod theme;
mod theme_packs;
mod widgets;
use widgets::StableSelectableUi;
@ -62,6 +64,17 @@ struct Ink {
scale: f32,
}
// egui rasterizes text into one shared font texture. Camera-scaled decorative text
// must not request multi-thousand-pixel glyphs and evict/corrupt ordinary UI text.
const MAX_CANVAS_TEXT_RASTER_PIXELS: f32 = 128.0;
fn bounded_canvas_font_size(ctx: &egui::Context, size: f32) -> Option<f32> {
(size.is_finite()
&& size > 0.0
&& size * ctx.pixels_per_point() <= MAX_CANVAS_TEXT_RASTER_PIXELS)
.then_some(size)
}
impl Ink {
fn new(ui: &egui::Ui, rect: Rect) -> Self {
Self {
@ -94,11 +107,15 @@ impl Ink {
}
fn text(&self, x: f32, y: f32, text: &str, size: f32, color: Color32) {
let size = size * self.scale;
let Some(size) = bounded_canvas_font_size(self.painter.ctx(), size) else {
return;
};
self.painter.text(
self.point(x, y),
Align2::LEFT_TOP,
text,
FontId::proportional(size * self.scale),
FontId::proportional(size),
color,
);
}
@ -126,13 +143,6 @@ impl Ink {
);
self.text(x + 12.0, y + 9.0, label, 13.0, palette.text);
}
fn field(&self, x: f32, y: f32, w: f32, label: &str, value: &str) {
let palette = theme::palette(self.painter.ctx());
self.text(x, y, label, 12.0, palette.muted);
self.card(x, y + 23.0, w, 42.0, palette.field, palette.line);
self.text(x + 12.0, y + 34.0, value, 18.0, palette.text);
}
}
const SCREEN_LABEL_TOP: f32 = 24.0;
@ -152,13 +162,15 @@ fn screen_labels(ink: &Ink, output: [u32; 2]) {
12.0 * k,
palette.muted,
);
ink.painter.text(
ink.point(width, -SCREEN_LABEL_TOP * k),
Align2::RIGHT_TOP,
format!("{} × {} px", output[0], output[1]),
FontId::proportional(13.0 * k * ink.scale),
palette.muted,
);
if let Some(size) = bounded_canvas_font_size(ink.painter.ctx(), 13.0 * k * ink.scale) {
ink.painter.text(
ink.point(width, -SCREEN_LABEL_TOP * k),
Align2::RIGHT_TOP,
format!("{} × {} px", output[0], output[1]),
FontId::proportional(size),
palette.muted,
);
}
}
fn screen_artwork(ink: &Ink, title: &str, output: [u32; 2]) {
@ -201,10 +213,13 @@ fn screen_reference_hint(ink: &Ink, output: [u32; 2]) {
.painter
.with_clip_rect(ink.painter.clip_rect().intersect(rect));
let color = theme::palette(ink.painter.ctx()).muted;
let Some(font_size) = bounded_canvas_font_size(ink.painter.ctx(), 12.0 * ink.scale) else {
return;
};
let text = painter.layout(
"Illustrative reference artwork · Drag & drop an image or use Import > Reference image…"
.into(),
FontId::proportional(12.0 * ink.scale),
FontId::proportional(font_size),
color,
(size.x - 48.0).max(1.0) * ink.scale,
);

View File

@ -104,6 +104,14 @@ impl Editor {
);
ui.add_enabled_ui(self.snapping.enabled, |ui| {
ui.checkbox(&mut self.snapping.pixels, tr(ui.ctx(), "ui.pixel-edges"));
ui.checkbox(
&mut self.snapping.force_pixels,
tr(ui.ctx(), "ui.force-snapping-to-whole-pixels"),
)
.on_hover_text(tr(
ui.ctx(),
"ui.force-whole-pixels-help",
));
ui.checkbox(
&mut self.snapping.screen_edges,
tr(ui.ctx(), "ui.screen-edges-center-quarters"),
@ -112,16 +120,10 @@ impl Editor {
&mut self.snapping.layer_edges,
tr(ui.ctx(), "ui.visible-layer-edges"),
)
.on_hover_text(tr(
ui.ctx(),
"ui.includes-contact-between-mirrored-opposite-resizing-layers",
));
.on_hover_text("Snap moving outer borders and use other layers’ borders as targets. Independent of masks. Also controls mirrored/opposite resize contact; center and direct resize-handle snapping remain available.");
ui.checkbox(&mut self.snapping.mask_edges, tr(ui.ctx(), "ui.mask-edges"));
});
ui.weak(tr(
ui.ctx(),
"ui.alt-invert-snapping-shift-10-px-ctrl-shift-100-px",
));
ui.weak(tr(ui.ctx(), "ui.snapping-modifiers-help"));
}
pub(super) fn snapping_menu(&mut self, ui: &mut egui::Ui) {
ui.menu_button(tr(ui.ctx(), "ui.snapping"), |ui| {
@ -168,13 +170,13 @@ impl Editor {
});
let before = self.application_settings(ui.ctx());
let current = theme::Theme::current(ui.ctx());
ui.menu_button(format!("Theme: {}", current.name()), |ui| {
ui.menu_button(format!("Theme: {}", current.display_name(ui.ctx())), |ui| {
for choice in theme::Theme::recent(ui.ctx()) {
if ui
.stable_selectable_label(current == choice, choice.name())
.stable_selectable_label(current == choice, choice.display_name(ui.ctx()))
.clicked()
{
choice.apply(ui.ctx());
choice.select(ui.ctx());
ui.close();
}
}
@ -229,6 +231,8 @@ impl Editor {
.id(egui::Id::new("All themes"))
.open(&mut self.themes_open)
.default_width(540.0)
.max_height((ctx.content_rect().height() - 100.0).max(200.0))
.vscroll(true)
.resizable(false)
.collapsible(false)
.show(ctx, |ui| {
@ -236,19 +240,26 @@ impl Editor {
ui.ctx(),
"ui.choose-a-theme-your-three-most-recent-choices-stay-in-the-menu",
));
if ui.button(tr(ctx, "theme.packs")).clicked() {
self.preferences_open = true;
self.preferences_section = preferences_ui::Section::Themes;
}
ui.separator();
ui.columns(2, |columns| {
for (index, choice) in theme::Theme::ALL.into_iter().enumerate() {
for (index, choice) in theme::Theme::choices(ctx).into_iter().enumerate() {
columns[index % 2].horizontal(|ui| {
let palette = choice.palette();
let palette = choice.resolved_palette(ctx);
for color in [palette.bg, palette.layer, palette.cyan] {
let (rect, _) =
ui.allocate_exact_size(Vec2::splat(10.0), egui::Sense::hover());
ui.painter().rect_filled(rect, 2.0, color);
}
if ui
.stable_selectable_label(current == choice, choice.name())
.on_hover_text(if choice.is_light() {
.stable_selectable_label(
current == choice,
choice.display_name(ui.ctx()),
)
.on_hover_text(if choice.resolved_light(ctx) {
"Light theme"
} else {
"Dark theme"
@ -262,8 +273,7 @@ impl Editor {
});
});
if let Some(choice) = selected {
choice.apply(ctx);
self.themes_open = false;
choice.select(ctx);
self.settings.save(&self.application_settings(ctx));
}
}
@ -280,17 +290,55 @@ impl Editor {
self.pan = Vec2::new(sw / 2.0 - c[0] as f32, sh / 2.0 - c[1] as f32);
}
}
pub(super) fn software_integrations_window(&mut self, ctx: &egui::Context) {
if !self.software_integrations_open {
return;
}
egui::Window::new("Software integrations")
.id(egui::Id::new("software-integrations"))
.open(&mut self.software_integrations_open)
.default_width(560.0)
.max_height((ctx.content_rect().height() - 100.0).max(200.0))
.vscroll(true)
.show(ctx, |ui| {
ui.label("Optional local applications detected at startup. Restart Canvas Pilot after installing or changing a converter.");
for integration in canvas_pilot::software::detected() {
ui.separator();
ui.horizontal_wrapped(|ui| {
ui.strong(integration.software.name());
ui.label(integration.status());
});
ui.label(integration.software.functionality());
if let Some(path) = &integration.path { ui.small(path.display().to_string()); }
if integration.enabled && !integration.available() {
ui.small(format!("Install the application on PATH, beside Canvas Pilot, or in its bin folder; alternatively set {} to its executable.", integration.software.environment()));
}
}
ui.separator();
ui.label("PDF and SVG rendering are built in. Figma artwork rendering is also built in when vendor formats are enabled.");
ui.weak("Detection checks for an executable file; conversion errors are still reported if that application cannot run or read the document.");
});
}
pub(super) fn application_menu(&mut self, ui: &mut egui::Ui) {
ui.set_min_width(185.0);
if ui.button(tr(ui.ctx(), "ui.open-all-settings")).clicked() {
self.preferences_open = true;
ui.close();
}
if ui.button("Software integrations…").clicked() {
self.software_integrations_open = true;
ui.close();
}
ui.separator();
if ui.button(tr(ui.ctx(), "ui.device-connection")).clicked() {
self.device.connection_open = true;
ui.close();
}
if ui.button("Input settings…").clicked() {
self.inputs.open = true;
ui.close();
}
ui.menu_button(tr(ui.ctx(), "ui.project"), |ui| self.project_menu(ui));
ui.menu_button(tr(ui.ctx(), "ui.import"), |ui| self.import_menu(ui));
ui.menu_button(tr(ui.ctx(), "ui.export"), |ui| self.export_menu(ui));
@ -474,12 +522,20 @@ mod tests {
click_label(&mut app, &ctx, "Options");
click_label(&mut app, &ctx, "Snapping");
click_label(&mut app, &ctx, "Snap movement & resizing");
click_label(&mut app, &ctx, "Mask edges");
click_label(&mut app, &ctx, "Mask edges & centers");
assert!(app.snapping.mask_edges);
click_label(&mut app, &ctx, "Layer borders");
assert!(!app.snapping.layer_edges);
assert!(app.snapping.mask_edges);
click_label(&mut app, &ctx, "Mask edges & centers");
assert!(!app.snapping.mask_edges);
assert!(!app.snapping.layer_edges);
click_label(&mut app, &ctx, "Mask edges & centers");
assert_eq!(*app.layout.layers(), before);
let (store, saved) = settings::Store::at(path);
assert!(store.error.is_none());
assert!(saved.snapping.mask_edges);
assert!(!saved.snapping.layer_edges);
assert!(saved.snapping.enabled);
}
@ -502,13 +558,22 @@ mod tests {
click_label(&mut app, &ctx, "Theme: Midra Dark");
click_label(&mut app, &ctx, "More themes…");
click_label(&mut app, &ctx, "Corporate Light");
click_label(&mut app, &ctx, "High Contrast");
assert_eq!(theme::Theme::current(&ctx), theme::Theme::HighContrast);
click_label(&mut app, &ctx, "High Contrast");
assert_eq!(theme::Theme::current(&ctx), theme::Theme::CorporateLight);
assert!(app.themes_open);
let (store, saved) = settings::Store::at(path);
assert!(store.error.is_none());
let fresh_ctx = egui::Context::default();
let restored = Editor::with_settings(&fresh_ctx, store, saved);
assert_eq!(
theme::Theme::recent(&fresh_ctx),
vec![theme::Theme::CorporateLight, theme::Theme::Midra]
vec![
theme::Theme::CorporateLight,
theme::Theme::HighContrast,
theme::Theme::Midra
]
);
assert!(restored.show_toolbar_icon_names);
assert!(!restored.keep_aspect_ratio);
@ -524,13 +589,14 @@ mod tests {
let ctx = egui::Context::default();
let boxes = app.layout.layers().clone();
let formats = app.layout.formats().clone();
click_label(&mut app, &ctx, "Menu");
click_label(&mut app, &ctx, "Options");
let label = format!("Theme: {}", theme::Theme::current(&ctx).name());
click_label(&mut app, &ctx, &label);
click_label(&mut app, &ctx, "More themes…");
for choice in theme::Theme::ALL {
click_label(&mut app, &ctx, "Menu");
click_label(&mut app, &ctx, "Options");
let label = format!("Theme: {}", theme::Theme::current(&ctx).name());
click_label(&mut app, &ctx, &label);
click_label(&mut app, &ctx, "More themes…");
click_label(&mut app, &ctx, choice.name());
assert!(app.themes_open);
assert!(theme::Theme::current(&ctx) == choice);
assert_eq!(ctx.global_style().visuals.dark_mode, !choice.is_light());
let output = frame(&mut app, &ctx, vec![]);
@ -579,3 +645,36 @@ mod tests {
}
}
}
#[cfg(test)]
mod software_tests {
use super::super::tests::frame;
use super::*;
#[test]
fn integrations_window_lists_tools_status_and_enabled_functions_without_editing_project() {
let ctx = egui::Context::default();
let mut app = Editor {
software_integrations_open: true,
..Default::default()
};
let before = app.project();
frame(&mut app, &ctx, vec![]);
let output = frame(&mut app, &ctx, vec![]);
let labels: Vec<_> = output
.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Text(t) => Some(t.galley.text()),
_ => None,
})
.collect();
assert!(labels.contains(&"Software integrations"));
for integration in canvas_pilot::software::detected() {
assert!(labels.contains(&integration.software.name()));
assert!(labels.contains(&integration.status()));
assert!(labels.contains(&integration.software.functionality()));
}
assert_eq!(app.project(), before);
}
}

View File

@ -0,0 +1,347 @@
//! Compact, session-only browsing shared by installed language and theme packs.
use super::*;
#[derive(Clone, Default)]
struct Browser {
query: String,
selected: Option<String>,
reveal: bool,
}
pub(super) struct Row {
pub id: String,
pub summary: String,
pub search: String,
pub active: bool,
}
pub(super) fn focus(ctx: &egui::Context, kind: &str, pack: &str) {
ctx.data_mut(|data| {
data.insert_temp(
egui::Id::new(("pack-browser", kind)),
Browser {
query: String::new(),
selected: Some(pack.into()),
reveal: true,
},
)
});
}
pub(super) fn show(
ui: &mut egui::Ui,
kind: &str,
mut rows: Vec<Row>,
details: impl FnOnce(&mut egui::Ui, &str, f32),
) {
let id = egui::Id::new(("pack-browser", kind));
let mut state = ui
.data(|data| data.get_temp::<Browser>(id))
.unwrap_or_default();
let previous_query = state.query.clone();
let previous_selection = state.selected.clone();
rows.sort_by(|a, b| a.id.cmp(&b.id));
ui.horizontal(|ui| {
ui.add(
egui::TextEdit::singleline(&mut state.query)
.id(id.with("search"))
.hint_text("Search packs or contents…")
.desired_width((ui.available_width() - 60.0).max(80.0)),
);
if ui
.add_enabled(!state.query.is_empty(), egui::Button::new("Clear"))
.clicked()
{
state.query.clear();
}
});
let query = state.query.trim().to_lowercase();
let filtered: Vec<_> = rows
.iter()
.filter(|row| {
query.is_empty()
|| row.search.to_lowercase().contains(&query)
|| row.id.contains(&query)
})
.collect();
ui.weak(format!(
"{} of {} packs · select a pack to inspect its contents",
filtered.len(),
rows.len()
));
if !filtered
.iter()
.any(|row| state.selected.as_ref() == Some(&row.id))
{
state.selected = filtered
.iter()
.find(|row| row.active)
.or_else(|| filtered.first())
.map(|row| row.id.clone());
}
ui.spacing_mut().scroll = egui::style::ScrollStyle {
bar_width: 10.0,
foreground_color: true,
..egui::style::ScrollStyle::solid()
};
let wide = ui.available_width() >= 460.0;
let height = (ui.ctx().content_rect().height() - 330.0).clamp(180.0, 360.0);
let reveal =
state.reveal || previous_query != state.query || previous_selection != state.selected;
let list = |ui: &mut egui::Ui, height: f32, selected: &mut Option<String>| {
egui::ScrollArea::vertical()
.id_salt(id.with("list"))
.max_height(height)
.auto_shrink([false, false])
.show(ui, |ui| {
if filtered.is_empty() {
ui.weak(if rows.is_empty() {
"No packs installed. Install a ZIP to get started."
} else {
"No matches. Try a name, pack ID or language code."
});
}
ui.spacing_mut().item_spacing.y = 4.0;
for row in &filtered {
let title_size = egui::TextStyle::Body.resolve(ui.style()).size;
let summary_size = egui::TextStyle::Small.resolve(ui.style()).size;
let (_, rect) = ui.allocate_space(Vec2::new(
ui.available_width(),
(title_size + summary_size + 14.0).max(40.0),
));
let response = ui.interact(rect, id.with(&row.id), egui::Sense::click());
response.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
true,
format!("{} · {}", row.id, row.summary),
)
});
let chosen = selected.as_ref() == Some(&row.id);
let visuals = ui.style().interact_selectable(&response, chosen);
ui.painter().rect_filled(rect, 3.0, visuals.bg_fill);
ui.painter()
.rect_stroke(rect, 3.0, visuals.bg_stroke, StrokeKind::Inside);
let title = format!("{}{}", if row.active { "● " } else { "" }, row.id);
for (text, y, size, color) in [
(title, 4.0, title_size, visuals.text_color()),
(
row.summary.clone(),
title_size + 9.0,
summary_size,
visuals.text_color(),
),
] {
let galley = egui::WidgetText::from(egui::RichText::new(text).size(size))
.into_galley(
ui,
Some(egui::TextWrapMode::Truncate),
rect.width() - 12.0,
egui::TextStyle::Body,
);
ui.painter()
.galley(rect.min + Vec2::new(6.0, y), galley, color);
}
if chosen && reveal {
response.scroll_to_me(Some(egui::Align::Center));
}
if response
.on_hover_text(format!(
"{}\n{}{}",
row.id,
row.summary,
if row.active { "\nIn use" } else { "" }
))
.clicked()
{
*selected = Some(row.id.clone());
}
}
});
};
if wide {
let width = (ui.available_width() * 0.38).clamp(160.0, 240.0);
ui.horizontal_top(|ui| {
ui.set_height(height);
ui.allocate_ui_with_layout(
Vec2::new(width, height),
egui::Layout::top_down(egui::Align::Min),
|ui| list(ui, height, &mut state.selected),
);
ui.separator();
ui.vertical(|ui| {
ui.set_width(ui.available_width());
if let Some(selected) = &state.selected {
details(ui, selected, height);
}
});
});
} else {
list(ui, 110.0, &mut state.selected);
ui.separator();
if let Some(selected) = &state.selected {
details(ui, selected, height.min(220.0));
}
}
state.reveal = false;
ui.data_mut(|data| data.insert_temp(id, state));
}
#[cfg(test)]
mod tests {
use super::*;
fn rows(count: usize) -> Vec<Row> {
(0..count)
.map(|i| Row {
id: format!("pack-{i:03}"),
summary: "16 themes · r2".into(),
search: format!("Palette {i:03} 日本語"),
active: i == 1,
})
.collect()
}
#[test]
fn row_selection_search_and_clear_work_with_pointer_and_keyboard() {
let ctx = egui::Context::default();
ctx.global_style_mut(|s| s.animation_time = 0.0);
let id = egui::Id::new(("pack-browser", "themes"));
let run = |events| {
let mut selected = None;
let output = ctx.run_ui(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(700.0, 720.0))),
events,
..Default::default()
},
|ui| {
show(ui, "themes", rows(20), |_, pack, _| {
selected = Some(pack.to_owned())
})
},
);
(selected, output)
};
run(vec![]);
run(vec![]);
let pos = ctx
.read_response(id.with("pack-005"))
.unwrap()
.rect
.center();
run(vec![
egui::Event::PointerMoved(pos),
super::super::tests::mouse(pos, true),
]);
assert_eq!(
run(vec![super::super::tests::mouse(pos, false)])
.0
.as_deref(),
Some("pack-005")
);
ctx.memory_mut(|m| m.request_focus(id.with("search")));
assert_eq!(
run(vec![egui::Event::Text("Palette 019".into())])
.0
.as_deref(),
Some("pack-019")
);
let output = run(vec![]).1;
let clear = output
.shapes
.iter()
.find_map(|s| match &s.shape {
egui::Shape::Text(t) if t.galley.text() == "Clear" => {
Some(t.pos + t.galley.size() / 2.0)
}
_ => None,
})
.unwrap();
run(vec![
egui::Event::PointerMoved(clear),
super::super::tests::mouse(clear, true),
]);
run(vec![super::super::tests::mouse(clear, false)]);
assert!(
ctx.data(|d| d.get_temp::<Browser>(id))
.unwrap()
.query
.is_empty()
);
focus(&ctx, "themes", "pack-007");
assert_eq!(run(vec![]).0.as_deref(), Some("pack-007"));
}
#[test]
fn collections_stay_bounded_and_search_selects_contents_without_crossing_sections() {
for width in [340.0, 700.0] {
let ctx = egui::Context::default();
ctx.global_style_mut(|s| s.animation_time = 0.0);
let run = |kind, count| {
let mut bounds = Rect::NOTHING;
let mut selected = None;
let _ = ctx.run_ui(
egui::RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 720.0))),
..Default::default()
},
|ui| {
ui.set_width(width - 20.0);
show(ui, kind, rows(count), |ui, id, _| {
selected = Some(id.to_owned());
ui.label("Contents");
});
bounds = ui.min_rect();
},
);
(bounds, selected)
};
let (small, selected) = run("themes", 2);
assert_eq!(selected.as_deref(), Some("pack-001"));
let (large, _) = run("themes", 200);
assert!((small.height() - large.height()).abs() < 2.0);
assert!(large.width() <= width);
assert!(
large.height() < 500.0,
"width={width} small={small:?} large={large:?}"
);
let id = egui::Id::new(("pack-browser", "themes"));
ctx.data_mut(|d| {
d.insert_temp(
id,
Browser {
query: "Palette 199".into(),
selected: Some("pack-001".into()),
..Default::default()
},
)
});
assert_eq!(run("themes", 200).1.as_deref(), Some("pack-199"));
assert_eq!(run("languages", 2).1.as_deref(), Some("pack-001"));
ctx.data_mut(|d| {
d.insert_temp(
id,
Browser {
query: "missing".into(),
selected: None,
..Default::default()
},
)
});
assert!(run("themes", 200).1.is_none());
ctx.data_mut(|d| {
d.insert_temp(
id,
Browser {
query: "日本語".into(),
selected: Some("pack-199".into()),
..Default::default()
},
)
});
assert_eq!(run("themes", 200).1.as_deref(), Some("pack-199"));
// Removal or update cannot leave details attached to a stale pack.
assert_eq!(run("themes", 2).1.as_deref(), Some("pack-001"));
assert!(run("themes", 0).1.is_none());
}
}
}

View File

@ -42,15 +42,17 @@ pub(super) enum Section {
#[default]
Appearance,
Languages,
Themes,
Editing,
Reference,
Storage,
Device,
}
impl Section {
const ALL: [(Self, &'static str); 6] = [
const ALL: [(Self, &'static str); 7] = [
(Self::Appearance, "ui.appearance"),
(Self::Languages, "language.packs"),
(Self::Themes, "theme.packs"),
(Self::Editing, "ui.editing"),
(Self::Reference, "ui.reference-images"),
(Self::Storage, "ui.files-settings"),
@ -66,6 +68,8 @@ pub(super) struct LanguagePreview {
pub(super) enum PackAction {
Install(crate::language_packs::Prepared),
Remove(crate::language_packs::Installed),
InstallTheme(crate::theme_packs::Prepared),
RemoveTheme(crate::theme_packs::Installed),
}
impl Editor {
@ -185,10 +189,16 @@ impl Editor {
Ok(pending) if pending.needs_confirmation() => {
self.language_pack_action = Some(PackAction::Install(pending))
}
Ok(pending) => match crate::language_packs::commit(ctx, pending, false) {
Ok(()) => self.refresh_pack_language(ctx, &previous),
Err(error) => self.error = error,
},
Ok(pending) => {
let id = pending.id().to_owned();
match crate::language_packs::commit(ctx, pending, false) {
Ok(()) => {
super::pack_browser_ui::focus(ctx, "languages", &id);
self.refresh_pack_language(ctx, &previous);
}
Err(error) => self.error = error,
}
}
Err(error) => self.error = error,
}
}
@ -203,24 +213,177 @@ impl Editor {
{
self.prepare_language_pack(&ctx, &path);
}
ui.weak("Choose a ZIP to install or update. Newer revisions update immediately; equal or older revisions ask before replacing.");
let packs = crate::language_packs::installed(&ctx);
if packs.is_empty() {
ui.label("No language packs installed.");
}
for pack in packs {
ui.separator();
ui.label(format!("{} · revision {}", pack.id, pack.revision));
for language in &pack.languages {
ui.label(format!("{} — {}", language.native_name, language.name));
let rows = packs
.iter()
.map(|pack| super::pack_browser_ui::Row {
id: pack.id.clone(),
summary: format!("Languages: {} · r{}", pack.languages.len(), pack.revision),
search: pack
.languages
.iter()
.map(|l| format!("{} {} {}", l.locale, l.name, l.native_name))
.collect::<Vec<_>>()
.join(" "),
active: pack
.languages
.iter()
.any(|l| self.language == localization::Language::Pack(l.locale.clone())),
})
.collect();
super::pack_browser_ui::show(ui, "languages", rows, |ui, id, height| {
let pack = packs.iter().find(|p| p.id == id).unwrap();
ui.label(egui::RichText::new(&pack.id).strong());
ui.weak(format!(
"Revision {} · Languages: {}",
pack.revision,
pack.languages.len()
));
if ui.button(tr(&ctx, "language.remove-pack")).clicked() {
self.finish_language_preview(&ctx, false);
self.language_pack_action = Some(PackAction::Remove(pack.clone()));
}
ui.push_id(&pack.id, |ui| {
if ui.button(tr(&ctx, "language.remove-pack")).clicked() {
self.finish_language_preview(&ctx, false);
self.language_pack_action = Some(PackAction::Remove(pack.clone()));
}
});
ui.separator();
egui::ScrollArea::vertical()
.id_salt(("pack-languages", id))
.max_height((height - 90.0).max(80.0))
.show(ui, |ui| {
for language in &pack.languages {
let choice = localization::Language::Pack(language.locale.clone());
let label = format!("{} — {}", language.native_name, language.name);
if ui
.add(
egui::Button::new(&label)
.selected(self.language == choice)
.wrap(),
)
.clicked()
{
self.preview_language(&ctx, choice);
}
}
});
});
}
fn refresh_pack_theme(&mut self, ctx: &egui::Context, was_available: bool) {
let current = theme::Theme::current(ctx);
if current.available(ctx) || !was_available {
current.apply(ctx);
} else {
theme::Theme::Midra.apply(ctx);
}
let current = theme::Theme::current(ctx);
let recent = theme::Theme::recent(ctx)
.into_iter()
.filter(|t| t.available(ctx) || *t == current)
.collect();
theme::Theme::restore_recent(ctx, recent);
self.settings.save(&self.application_settings(ctx));
}
fn prepare_theme_pack(&mut self, ctx: &egui::Context, path: &std::path::Path) {
let result = self
.settings
.path
.as_ref()
.and_then(|p| p.parent())
.ok_or_else(|| "Settings directory unavailable".to_owned())
.and_then(|directory| {
crate::theme_packs::prepare(ctx, &directory.join("theme-packs"), path)
});
match result {
Ok(pending) if pending.needs_confirmation() => {
self.language_pack_action = Some(PackAction::InstallTheme(pending))
}
Ok(pending) => {
let was_available = theme::Theme::current(ctx).available(ctx);
let id = pending.id().to_owned();
match crate::theme_packs::commit(ctx, pending, false) {
Ok(()) => {
super::pack_browser_ui::focus(ctx, "themes", &id);
self.refresh_pack_theme(ctx, was_available);
}
Err(error) => self.error = error,
}
}
Err(error) => self.error = error,
}
}
fn theme_pack_settings(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
ui.heading(tr(&ctx, "theme.packs"));
if ui.button(tr(&ctx, "theme.install-pack")).clicked()
&& let Some(path) = rfd::FileDialog::new()
.add_filter("Theme pack", &["zip"])
.pick_file()
{
self.prepare_theme_pack(&ctx, &path);
}
let packs = crate::theme_packs::installed(&ctx);
let current = theme::Theme::current(&ctx);
let rows = packs
.iter()
.map(|pack| super::pack_browser_ui::Row {
id: pack.id.clone(),
summary: format!("Themes: {} · r{}", pack.themes.len(), pack.revision),
search: pack
.themes
.iter()
.map(|t| format!("{} {}", t.id, t.name))
.collect::<Vec<_>>()
.join(" "),
active: pack
.themes
.iter()
.any(|t| current == theme::Theme::Pack(format!("{}/{}", pack.id, t.id))),
})
.collect();
super::pack_browser_ui::show(ui, "themes", rows, |ui, id, height| {
let pack = packs.iter().find(|p| p.id == id).unwrap();
ui.label(egui::RichText::new(&pack.id).strong());
ui.weak(format!(
"Revision {} · Themes: {}",
pack.revision,
pack.themes.len()
));
if ui.button(tr(&ctx, "language.remove-pack")).clicked() {
self.language_pack_action = Some(PackAction::RemoveTheme(pack.clone()));
}
ui.separator();
egui::ScrollArea::vertical()
.id_salt(("pack-themes", id))
.max_height((height - 90.0).max(80.0))
.show(ui, |ui| {
for entry in &pack.themes {
let choice = theme::Theme::Pack(format!("{}/{}", pack.id, entry.id));
let palette = choice.resolved_palette(&ctx);
ui.horizontal(|ui| {
for color in [palette.bg, palette.layer, palette.cyan] {
let (rect, _) =
ui.allocate_exact_size(Vec2::splat(12.0), egui::Sense::hover());
ui.painter().rect_filled(rect, 2.0, color);
}
if ui
.add(
egui::Button::new(&entry.name)
.selected(choice == theme::Theme::current(&ctx))
.wrap(),
)
.clicked()
{
choice.select(&ctx);
}
});
}
if !pack.notices.is_empty() {
egui::CollapsingHeader::new("Attribution and licenses")
.id_salt(("theme-notices", id))
.show(ui, |ui| {
ui.label(&pack.notices);
});
}
});
});
}
pub(super) fn language_pack_confirmation(&mut self, ctx: &egui::Context) {
@ -236,6 +399,19 @@ impl Editor {
ui.label("This is not a newer revision. Replacing it overwrites the installed translations.");
"language.overwrite-pack"
},
PackAction::InstallTheme(pack) => {
ui.heading(tr(ctx, "language.overwrite-pack"));
ui.label(format!("{}: installed revision {} → revision {}", pack.id(), pack.previous_revision.map_or_else(|| "unknown".into(), |v| v.to_string()), pack.revision()));
ui.label("This is not a newer revision. Replacing it overwrites the installed themes.");
"language.overwrite-pack"
},
PackAction::RemoveTheme(pack) => {
ui.heading(tr(ctx, "language.remove-pack"));
ui.label(&pack.id);
ui.label(pack.themes.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", "));
ui.label("All themes in this pack will be removed. If the current theme is removed, the interface switches to Midra Dark. You can reinstall the ZIP later.");
"language.remove-pack"
},
PackAction::Remove(pack) => {
ui.heading(tr(ctx, "language.remove-pack"));
ui.label(&pack.id);
@ -250,11 +426,29 @@ impl Editor {
self.language_pack_action = None;
} else if response.inner.0 {
let previous = crate::language_packs::available(ctx);
let theme_was_available = theme::Theme::current(ctx).available(ctx);
let theme_action = matches!(
self.language_pack_action,
Some(PackAction::InstallTheme(_) | PackAction::RemoveTheme(_))
);
let focus = match self.language_pack_action.as_ref() {
Some(PackAction::Install(pack)) => Some(("languages", pack.id().to_owned())),
Some(PackAction::InstallTheme(pack)) => Some(("themes", pack.id().to_owned())),
_ => None,
};
let result = match self.language_pack_action.take().unwrap() {
PackAction::Install(pack) => crate::language_packs::commit(ctx, pack, true),
PackAction::Remove(pack) => crate::language_packs::remove(ctx, &pack),
PackAction::InstallTheme(pack) => crate::theme_packs::commit(ctx, pack, true),
PackAction::RemoveTheme(pack) => crate::theme_packs::remove(ctx, &pack),
};
if result.is_ok()
&& let Some((kind, id)) = focus
{
super::pack_browser_ui::focus(ctx, kind, &id);
}
match result {
Ok(()) if theme_action => self.refresh_pack_theme(ctx, theme_was_available),
Ok(()) => self.refresh_pack_language(ctx, &previous),
Err(error) => self.error = error,
}
@ -325,14 +519,14 @@ impl Editor {
ui.weak(tr(ctx, "access.text-help"));
}
if scaling_before != (self.ui_scale, self.text_scale) { apply_scaling(ctx, self.ui_scale, self.text_scale); }
if ui.button(tr(ctx, "access.contrast")).clicked() { theme::Theme::HighContrast.apply(ctx); }
if ui.button(tr(ctx, "access.contrast")).clicked() { theme::Theme::HighContrast.select(ctx); }
ui.separator();
ui.label(rust_i18n::t!("theme.current", locale = &localization::locale(ctx), name = theme::Theme::current(ctx).name()).into_owned());
ui.label(rust_i18n::t!("theme.current", locale = &localization::locale(ctx), name = theme::Theme::current(ctx).display_name(ctx)).into_owned());
if ui.button(tr(ui.ctx(), "ui.browse-all-themes")).clicked() { self.themes_open = true; }
ui.label(tr(ui.ctx(), "ui.recently-used"));
for choice in theme::Theme::recent(ctx) {
if ui.stable_selectable_label(choice == theme::Theme::current(ctx), choice.name()).clicked() {
choice.apply(ctx);
if ui.stable_selectable_label(choice == theme::Theme::current(ctx), choice.display_name(ctx)).clicked() {
choice.select(ctx);
}
}
ui.separator();
@ -341,6 +535,7 @@ impl Editor {
ui.weak(tr(ui.ctx(), "ui.themes-also-apply-to-the-viewport-imported-pictures-retain-their-colors"));
}
Section::Languages => self.language_pack_settings(ui),
Section::Themes => self.theme_pack_settings(ui),
Section::Editing => {
ui.heading(tr(ui.ctx(), "ui.editing"));
self.resize_ratio_option(ui);
@ -470,6 +665,72 @@ mod tests {
writer.finish().unwrap().into_inner()
}
#[test]
fn theme_pack_manager_selects_updates_restarts_and_removes_with_confirmation() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("settings.json");
let source = dir.path().join("theme.zip");
let (store, saved) = settings::Store::at(path.clone());
let ctx = egui::Context::default();
let mut app = Editor::with_settings(&ctx, store, saved);
let project = app.project();
std::fs::write(
&source,
include_bytes!("../../../docs/theme-packs/tokyo-night.zip"),
)
.unwrap();
app.prepare_theme_pack(&ctx, &source);
app.preferences_open = true;
app.preferences_section = Section::Themes;
click_label(&mut app, &ctx, "Tokyo Night");
let choice = theme::Theme::Pack("tokyo-night/night".into());
assert_eq!(theme::Theme::current(&ctx), choice);
assert_eq!(settings::Store::at(path.clone()).1.theme, choice);
let restarted = egui::Context::default();
let (store, saved) = settings::Store::at(path.clone());
let _restored = Editor::with_settings(&restarted, store, saved);
assert_eq!(theme::palette(&restarted).bg, theme::palette(&ctx).bg);
theme::Theme::HighContrast.select(&ctx);
theme::Theme::HighContrast.select(&ctx);
assert_eq!(theme::Theme::current(&ctx), choice);
let mut manifest: serde_json::Value = serde_json::from_str(include_str!(
"../../../docs/theme-packs/tokyo-night/manifest.json"
))
.unwrap();
manifest["revision"] = 2.into();
manifest["themes"][0]["colors"]["bg"] = "#223344".into();
manifest["themes"][0]["light"] = true.into();
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
use std::io::Write;
zip.start_file("manifest.json", zip::write::SimpleFileOptions::default())
.unwrap();
zip.write_all(&serde_json::to_vec(&manifest).unwrap())
.unwrap();
std::fs::write(&source, zip.finish().unwrap().into_inner()).unwrap();
app.prepare_theme_pack(&ctx, &source);
assert_eq!(theme::palette(&ctx).bg, Color32::from_rgb(0x22, 0x33, 0x44));
assert!(!ctx.global_style().visuals.dark_mode);
app.prepare_theme_pack(&ctx, &source);
assert!(matches!(
app.language_pack_action,
Some(PackAction::InstallTheme(_))
));
click_label(&mut app, &ctx, "Cancel");
app.prepare_theme_pack(&ctx, &source);
click_label(&mut app, &ctx, "Overwrite pack");
assert!(app.language_pack_action.is_none());
click_label(&mut app, &ctx, "Remove pack…");
click_label(&mut app, &ctx, "Cancel");
assert_eq!(theme::Theme::current(&ctx), choice);
click_label(&mut app, &ctx, "Remove pack…");
click_label(&mut app, &ctx, "Remove pack…");
assert!(crate::theme_packs::installed(&ctx).is_empty());
assert_eq!(theme::Theme::current(&ctx), theme::Theme::Midra);
assert_eq!(settings::Store::at(path).1.theme, theme::Theme::Midra);
assert_eq!(app.project(), project);
assert!(source.exists());
}
#[test]
fn pack_manager_updates_confirms_overwrites_and_removes_active_language_live() {
let dir = tempfile::tempdir().unwrap();
@ -488,7 +749,8 @@ mod tests {
std::fs::write(&source, manager_pack(1, "test-manager")).unwrap();
app.prepare_language_pack(&ctx, &source);
assert!(app.language_pack_action.is_none());
app.preview_language(&ctx, localization::Language::Pack("test-manager".into()));
click_label(&mut app, &ctx, "Manager test — Manager test");
assert!(app.language_preview.is_some());
app.finish_language_preview(&ctx, true);
std::fs::write(&source, manager_pack(2, "test-manager")).unwrap();
app.prepare_language_pack(&ctx, &source);

View File

@ -30,14 +30,15 @@ pub struct Input {
pub id: usize,
pub source_format: Aspect,
pub native_resolution: Resolution,
pub input_crop: Crop,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Layer {
pub pivot: [f64; 2],
pub keep_aspect_ratio: bool,
#[serde(deserialize_with = "deserialize_link")]
pub device_link: Option<crate::DeviceLink>,
pub load_mapping: Option<crate::DeviceLink>,
pub send_mapping: crate::SendMapping,
pub name: String,
pub folder: String,
pub id: usize,
@ -103,7 +104,6 @@ pub struct EditorSettings {
pub position_point: PositionPoint,
#[serde(deserialize_with = "deserialize_layer_point")]
pub position_layer_point: Option<PositionPoint>,
pub keep_aspect_ratio: bool,
pub viewport_zoom: f32,
pub viewport_pan: [f32; 2],
pub show_source_pattern: bool,
@ -163,7 +163,6 @@ impl Preview {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Project {
pub input_proposals: Vec<crate::input_proposal::InputProposal>,
pub folders: Vec<String>,
pub workspace: Workspace,
pub format: String,
@ -181,8 +180,7 @@ impl Project {
folders: layout.folders.clone(),
workspace: Workspace::default(),
format: FORMAT.into(),
version: 18,
input_proposals: Vec::new(),
version: 22,
next_layer_id: layout.next_id,
output_resolution: layout.formats.output.into(),
inputs: (0..layout.formats.sources.len())
@ -192,14 +190,15 @@ impl Project {
id: i + 1,
source_format: source.aspect,
native_resolution: source.native.into(),
input_crop: source.input_crop,
}
})
.collect(),
layers: (0..layout.layers.len())
.map(|i| Layer {
pivot: layout.info[i].pivot,
device_link: layout.info[i].device_link.clone(),
keep_aspect_ratio: layout.info[i].keep_aspect_ratio,
load_mapping: layout.info[i].load_mapping.clone(),
send_mapping: layout.info[i].send_mapping.clone(),
name: layout.info[i].name.clone(),
folder: layout.info[i].folder.clone(),
id: layout.info[i].id,
@ -222,7 +221,6 @@ impl Project {
.collect(),
position_point: PositionPoint::TopLeft,
position_layer_point: None,
keep_aspect_ratio: true,
viewport_zoom: 1.0,
viewport_pan: [0.0; 2],
show_source_pattern: false,
@ -233,30 +231,12 @@ impl Project {
}
/// Build a fresh document only after validating the entire file. No history is restored.
pub fn layout(&self) -> Result<Layout, String> {
if self.format != FORMAT || self.version != 18 {
if self.format != FORMAT || self.version != 22 {
return Err(
"Unsupported project format/version; expected beffroi.midra-layout version 18."
"Unsupported project format/version; expected beffroi.midra-layout version 22."
.into(),
);
}
if self.input_proposals.len() > 256 {
return Err("Too many input proposals.".into());
}
let mut proposal_layers = std::collections::BTreeSet::new();
for proposal in &self.input_proposals {
proposal.validate()?;
if !proposal_layers.insert(proposal.layer_id)
|| !self.layers.iter().any(|l| {
l.id == proposal.layer_id
&& l.device_link.as_ref() == Some(&proposal.device_link)
})
{
return Err(
"Input proposal must refer to a distinct layer with its matching device link."
.into(),
);
}
}
if self.editor.backdrop_title.chars().count() > 128
|| self.editor.backdrop_title.chars().any(char::is_control)
{
@ -321,7 +301,6 @@ impl Project {
input.native_resolution.width,
input.native_resolution.height,
],
input_crop: input.input_crop,
};
source.input()?;
layout.formats.sources[i] = source;
@ -337,13 +316,16 @@ impl Project {
{
return Err("Invalid layer identity, name, folder or source ID.".into());
}
if let Some(link) = &layer.device_link {
layer.send_mapping.validate()?;
if let Some(link) = &layer.load_mapping {
link.validate()?;
}
crate::validate_pivot(layer.pivot)?;
layout.info.push(crate::LayerInfo {
pivot: layer.pivot,
device_link: layer.device_link.clone(),
keep_aspect_ratio: layer.keep_aspect_ratio,
load_mapping: layer.load_mapping.clone(),
send_mapping: layer.send_mapping.clone(),
id: layer.id,
name: layer.name.clone(),
folder: layer.folder.clone(),
@ -447,8 +429,8 @@ impl Project {
}
let header: Header =
serde_json::from_str(text).map_err(|e| format!("Invalid project JSON: {e}"))?;
if !(1..=18).contains(&header.version) {
return Err("Unsupported project version; expected versions 1–18.".into());
if !(1..=22).contains(&header.version) {
return Err("Unsupported project version; expected versions 1–22.".into());
}
let mut migrated: serde_json::Value = if header.version == 1 || header.version == 2 {
let mut value: serde_json::Value =
@ -699,6 +681,81 @@ impl Project {
snapping.insert("mask_edges".into(), false.into());
migrated["version"] = 18.into();
}
if header.version <= 18 {
for layer in migrated["layers"].as_array_mut().ok_or("Missing layers")? {
let layer = layer.as_object_mut().ok_or("Invalid project layer")?;
if layer.contains_key("load_mapping") || layer.contains_key("send_mapping") {
return Err("Unexpected directional mapping in legacy project.".into());
}
let link = layer.remove("device_link").ok_or("Missing device_link")?;
let destinations = if link.is_null() {
serde_json::json!([])
} else {
serde_json::json!([{ "connection": "current", "layer": link.clone() }])
};
layer.insert("load_mapping".into(), link);
layer.insert(
"send_mapping".into(),
serde_json::json!({ "destinations": destinations }),
);
}
migrated["version"] = 19.into();
}
if header.version <= 19 {
if migrated["input_proposals"] != serde_json::json!([]) {
return Err(
"Retired input proposals: open the project with best-effort recovery.".into(),
);
}
migrated
.as_object_mut()
.ok_or("Invalid project")?
.remove("input_proposals");
for input in migrated["inputs"].as_array_mut().ok_or("Missing inputs")? {
if let Some(crop) = input.get("input_crop") {
let crop: Crop =
serde_json::from_value(crop.clone()).map_err(|e| e.to_string())?;
if crop != Crop::default() {
return Err(
"Retired local input crop: open the project with best-effort recovery."
.into(),
);
}
}
input
.as_object_mut()
.ok_or("Invalid input")?
.remove("input_crop");
}
migrated["version"] = 20.into();
}
if header.version <= 20 {
let keep = migrated["editor"]
.as_object_mut()
.ok_or("Missing editor settings")?
.remove("keep_aspect_ratio")
.ok_or("Missing aspect-ratio setting")?;
let keep: bool = serde_json::from_value(keep)
.map_err(|_| "Invalid aspect-ratio setting".to_string())?;
for layer in migrated["layers"].as_array_mut().ok_or("Missing layers")? {
let layer = layer.as_object_mut().ok_or("Invalid project layer")?;
if layer.contains_key("keep_aspect_ratio") {
return Err("Unexpected per-layer aspect-ratio setting in old project.".into());
}
layer.insert("keep_aspect_ratio".into(), keep.into());
}
migrated["version"] = 21.into();
}
if header.version <= 21 {
let snapping = migrated["workspace"]["snapping"]
.as_object_mut()
.ok_or("Missing snapping")?;
if header.version >= 11 && snapping.contains_key("force_pixels") {
return Err("Unexpected force_pixels in old project.".into());
}
snapping.insert("force_pixels".into(), false.into());
migrated["version"] = 22.into();
}
let p: Self =
serde_json::from_value(migrated).map_err(|e| format!("Invalid project JSON: {e}"))?;
p.layout()?;

View File

@ -0,0 +1,306 @@
//! Explicit, reported recovery for opening native projects. Writers and exchange
//! metadata continue to use strict Project validation.
use crate::{
Layout,
formats::{Crop, Source},
project::{FORMAT, MAX_PROJECT_BYTES, Project},
};
use serde_json::Value;
pub struct LoadedProject {
pub project: Project,
pub warnings: Vec<String>,
}
pub fn from_json(text: &str) -> Result<LoadedProject, String> {
if text.len() as u64 > MAX_PROJECT_BYTES {
return Err("Project exceeds 96 MiB.".into());
}
let mut raw: Value =
serde_json::from_str(text).map_err(|e| format!("Invalid project JSON: {e}"))?;
if raw["format"] != FORMAT {
return Err("Not a Canvas Pilot project.".into());
}
let version = raw["version"]
.as_u64()
.filter(|v| (1..=22).contains(v))
.ok_or("Unsupported project version; expected versions 1–22.")?;
let mut warnings = Vec::new();
if let Some(proposals) = raw.as_object_mut().unwrap().remove("input_proposals") {
if proposals != serde_json::json!([]) {
warnings.push(
"Discarded retired device-input proposals; use shared Input settings.".into(),
);
}
// The strict historical migration expects this field from version 16.
if (16..20).contains(&version) {
raw["input_proposals"] = serde_json::json!([]);
}
}
if let Some(inputs) = raw["inputs"].as_array_mut() {
for (i, input) in inputs.iter_mut().enumerate() {
if let Some(obj) = input.as_object_mut() {
if let Some(crop) = obj.remove("input_crop")
&& crop != serde_json::to_value(Crop::default()).unwrap()
{
warnings.push(format!("Input {}: removed retired local pre-crop; appearance may change. Reload from the device to use its processed dimensions.", i + 1));
}
if version < 20 {
obj.insert(
"input_crop".into(),
serde_json::to_value(Crop::default()).unwrap(),
);
}
}
}
}
if let Ok(project) = Project::from_json(&raw.to_string()) {
return Ok(LoadedProject { project, warnings });
}
warnings.push(
"Recovered supported fields; missing, invalid or unknown settings were not restored."
.into(),
);
let defaults = Project::from_layout(&Layout::default());
let mut p = defaults.clone();
p.editor.selected_layer_ids.clear();
p.inputs.clear();
p.layers.clear();
// Dimensions are safe to default; geometry and identity must be present.
if let Ok(output) =
serde_json::from_value::<crate::project::Resolution>(raw["output_resolution"].clone())
&& crate::formats::validate_resolution([output.width, output.height]).is_ok()
{
p.output_resolution = output;
} else {
warnings.push("Output resolution reset to 1920 × 1080.".into());
}
let inputs = raw["inputs"]
.as_array()
.ok_or("No recoverable input definitions.")?;
let mut source_ids = std::collections::BTreeMap::new();
if inputs.len() > 1024 {
warnings.push("Inputs beyond the 1024-slot limit were skipped.".into());
}
for (i, input) in inputs.iter().take(1024).enumerate() {
let mut value = input.clone();
if let Some(obj) = value.as_object_mut() {
obj.retain(|key, _| {
["id", "source_format", "native_resolution"].contains(&key.as_str())
});
obj.entry("source_format")
.or_insert(serde_json::to_value(crate::formats::Aspect::Custom).unwrap());
}
let parsed = serde_json::from_value::<crate::project::Input>(value);
if let Ok(mut input) = parsed
&& input.id > 0
&& !source_ids.contains_key(&input.id)
&& (Source {
aspect: input.source_format,
native: [
input.native_resolution.width,
input.native_resolution.height,
],
})
.input()
.is_ok()
{
source_ids.insert(input.id, p.inputs.len() + 1);
input.id = p.inputs.len() + 1;
p.inputs.push(input);
} else {
warnings.push(format!(
"Input row {} skipped: invalid or duplicate definition.",
i + 1
));
}
}
if p.inputs.is_empty() {
return Err("No usable input definitions; current project kept.".into());
}
let layers = raw["layers"].as_array().ok_or("No recoverable layers.")?;
let mut ids = std::collections::BTreeSet::new();
if layers.len() > 256 {
warnings.push("Layers beyond the 256-layer limit were skipped.".into());
}
for (i, layer) in layers.iter().take(256).enumerate() {
let id = layer["id"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
.filter(|v| *v > 0 && *v < usize::MAX);
let source = layer["source_id"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
.and_then(|v| source_ids.get(&v).copied());
let bounds = serde_json::from_value::<crate::Geometry>(layer["bounds"].clone())
.ok()
.and_then(|v| v.validate().ok());
let (Some(id), Some(source_id), Some(bounds)) = (id, source, bounds) else {
warnings.push(format!(
"Layer row {} skipped: missing/invalid identity, source or geometry.",
i + 1
));
continue;
};
if !ids.insert(id) {
warnings.push(format!("Layer {id} skipped: duplicate identity."));
continue;
}
let mut recovered = defaults.layers[0].clone();
recovered.id = id;
recovered.source_id = source_id;
recovered.bounds = bounds;
recovered.name = format!("Layer {id}");
recovered.load_mapping = None;
recovered.send_mapping = Default::default();
let input = &p.inputs[source_id - 1];
let size = [
input.native_resolution.width as f64,
input.native_resolution.height as f64,
];
let Ok(crop) = crate::formats::crop_from_framing(
size,
[bounds.width, bounds.height],
Default::default(),
) else {
warnings.push(format!(
"Layer {id} skipped: unsupported geometry/source scale."
));
continue;
};
recovered.advanced_crop = crop;
p.next_layer_id = p.next_layer_id.max(id + 1);
p.layers.push(recovered);
if let Err(error) = p.layout() {
p.layers.pop();
warnings.push(format!("Layer {id} skipped: {error}"));
continue;
}
let index = p.layers.len() - 1;
// Apply dependent fit/crop before masks; validate each change against the
// complete recovered document so a bad optional field cannot lose geometry.
for key in [
"name",
"folder",
"pivot",
"keep_aspect_ratio",
"visible",
"locked",
"load_mapping",
"send_mapping",
"layer_fit",
"advanced_crop",
"mask",
] {
let Some(value) = layer.get(key) else {
warnings.push(format!("Layer {id}: {key} defaulted."));
continue;
};
let mut candidate = p.clone();
let mut data = serde_json::to_value(&candidate.layers[index]).unwrap();
data[key] = value.clone();
let result = serde_json::from_value(data)
.map_err(|e| e.to_string())
.and_then(|l| {
candidate.layers[index] = l;
candidate.layout().map(|_| ())
});
if result.is_ok() {
p = candidate;
} else {
warnings.push(format!("Layer {id}: invalid {key} reset."));
}
}
}
if p.layers.is_empty() {
return Err("No usable layers; current project kept.".into());
}
if let Some(next) = raw["next_layer_id"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
{
p.next_layer_id = p.next_layer_id.max(next);
}
// Recover independent document settings individually, including selection,
// references and previews only when their references and bounds remain valid.
let baseline = serde_json::to_value(&p).unwrap();
for section in ["editor", "workspace"] {
if let Some(fields) = raw[section].as_object() {
for (key, value) in fields {
if ["previews", "collapsed_folders", "selected_layer_ids"].contains(&key.as_str()) {
continue;
}
let mut candidate = serde_json::to_value(&p).unwrap();
candidate[section][key] = value.clone();
match serde_json::from_value::<Project>(candidate)
.ok()
.filter(|p| p.layout().is_ok())
{
Some(recovered) => p = recovered,
None => warnings.push(format!("{section}.{key} reset or skipped.")),
}
}
} else if raw[section] != baseline[section] {
warnings.push(format!("{section} reset to defaults."));
}
}
for (section, limit) in [("folders", 256), ("references", 32)] {
if let Some(items) = raw[section].as_array() {
if items.len() > limit {
warnings.push(format!("{section}: entries beyond {limit} skipped."));
}
for (i, item) in items.iter().take(limit).enumerate() {
let mut candidate = serde_json::to_value(&p).unwrap();
candidate[section]
.as_array_mut()
.unwrap()
.push(item.clone());
match serde_json::from_value::<Project>(candidate)
.ok()
.filter(|p| p.layout().is_ok())
{
Some(recovered) => p = recovered,
None => warnings.push(format!("{section} row {} skipped.", i + 1)),
}
}
}
}
for (section, key, limit) in [
("editor", "selected_layer_ids", 256),
("workspace", "collapsed_folders", 256),
("workspace", "previews", 256),
] {
if let Some(items) = raw[section][key].as_array() {
if items.len() > limit {
warnings.push(format!("{section}.{key}: entries beyond {limit} skipped."));
}
for (i, item) in items.iter().take(limit).enumerate() {
let mut candidate = serde_json::to_value(&p).unwrap();
let mut item = item.clone();
if key == "previews"
&& let Some(id) = item["source_id"]
.as_u64()
.and_then(|v| usize::try_from(v).ok())
&& let Some(mapped) = source_ids.get(&id)
{
item["source_id"] = (*mapped).into();
}
candidate[section][key].as_array_mut().unwrap().push(item);
match serde_json::from_value::<Project>(candidate)
.ok()
.filter(|p| p.layout().is_ok())
{
Some(recovered) => p = recovered,
None => warnings.push(format!("{section}.{key} row {} skipped.", i + 1)),
}
}
} else if !raw[section][key].is_null() {
warnings.push(format!("{section}.{key} reset."));
}
}
p.layout()?;
Ok(LoadedProject {
project: p,
warnings,
})
}

View File

@ -7,6 +7,7 @@ pub(super) struct PreparedProject {
capture: capture_ui::CaptureUi,
layout: Layout,
references: Vec<super::super::reference::Reference>,
warnings: Vec<String>,
}
type LoadedProject = (PreparedProject, Option<PathBuf>, Option<u64>);
type ProjectJob = std::sync::mpsc::Receiver<Result<Option<LoadedProject>, String>>;
@ -51,6 +52,49 @@ pub(super) struct FileUi {
export_job: Option<ExportJob>,
}
impl PreparedProject {
fn prepare_recovered(
ctx: &egui::Context,
loaded: canvas_pilot::project_recovery::LoadedProject,
) -> Result<Self, String> {
let canvas_pilot::project_recovery::LoadedProject {
mut project,
mut warnings,
} = loaded;
project.references.retain(|r| {
let valid = r.bytes().and_then(|bytes| {
let file = egui::DroppedFile {
name: r.name.clone(),
bytes: Some(bytes.into()),
..Default::default()
};
super::super::reference::Reference::load(ctx, &file).map(|_| ())
});
if let Err(error) = valid {
warnings.push(format!("Reference {} skipped: {error}", r.name));
false
} else {
true
}
});
let mut workspace = project.workspace.clone();
workspace.previews.clear();
project.workspace.previews.retain(|preview| {
workspace.previews = vec![preview.clone()];
if let Err(error) = capture_ui::CaptureUi::from_workspace(ctx, &workspace) {
warnings.push(format!(
"Layer {} preview skipped: {error}",
preview.layer_id
));
false
} else {
true
}
});
let mut prepared = Self::prepare(ctx, project)?;
prepared.warnings = warnings;
Ok(prepared)
}
fn prepare(ctx: &egui::Context, project: Project) -> Result<Self, String> {
let layout = project.layout()?;
let references = project
@ -77,29 +121,16 @@ impl PreparedProject {
project,
layout,
references,
warnings: Vec::new(),
})
}
}
impl Editor {
pub(super) fn project(&self) -> Project {
let mut p = Project::from_layout(&self.layout);
p.input_proposals = self
.device
.input_edits
.saved
.iter()
.filter(|proposal| {
p.layers.iter().any(|l| {
l.id == proposal.layer_id
&& l.device_link.as_ref() == Some(&proposal.device_link)
})
})
.cloned()
.collect();
p.editor.position_point = self.corner;
p.editor.position_layer_point = self.position_layer_point;
p.editor.backdrop_title = self.backdrop_title.clone();
p.editor.keep_aspect_ratio = self.keep_aspect_ratio;
p.editor.viewport_zoom = self.zoom;
p.editor.viewport_pan = [self.pan.x, self.pan.y];
p.editor.show_source_pattern = self.show_pattern;
@ -157,11 +188,10 @@ impl Editor {
project,
layout,
references,
warnings: _,
} = prepared;
let e = project.editor;
self.device.reset_mappings();
self.device.input_edits.clear();
self.device.input_edits.saved = project.input_proposals;
self.capture.clear_preview();
let mut layer_ui = layers_ui::LayerUi::default();
layer_ui.collapsed = project.workspace.collapsed_folders.into_iter().collect();
@ -187,7 +217,7 @@ impl Editor {
corner: e.position_point,
position_layer_point: e.position_layer_point,
backdrop_title: e.backdrop_title,
keep_aspect_ratio: e.keep_aspect_ratio,
keep_aspect_ratio: true,
zoom: e.viewport_zoom,
pan: Vec2::from(e.viewport_pan),
show_pattern: e.show_source_pattern,
@ -222,6 +252,21 @@ impl Editor {
ctx.request_repaint();
});
}
fn start_project_open(&mut self, ctx: &egui::Context, path: PathBuf) {
let (tx, rx) = std::sync::mpsc::channel();
self.files.loading = Some(rx);
self.files.loading_recovery = false;
let ctx = ctx.clone();
std::thread::spawn(move || {
let result = (|| {
let (loaded, native) = canvas_pilot::interchange::read_project_for_open(&path)?;
let prepared = PreparedProject::prepare_recovered(&ctx, loaded)?;
Ok(Some((prepared, native.then_some(path), None)))
})();
let _ = tx.send(result);
ctx.request_repaint();
});
}
pub(super) fn poll_project_job(&mut self) {
let Some(rx) = &self.files.loading else {
return;
@ -234,9 +279,13 @@ impl Editor {
let recovery = self.files.loading_recovery;
self.files.loading = None;
let result = result.and_then(|loaded| {
if let Some((prepared, path, time)) = loaded {
if let Some((prepared, mut path, mut time)) = loaded {
let warnings = prepared.warnings.clone();
if !warnings.is_empty() { path = None; time = None; }
self.install_prepared(prepared)?;
self.files.message = if recovery {
self.files.message = if !warnings.is_empty() {
Some(format!("Opened a recovered, unsaved copy. Review it before saving. The original file has not been changed.\n\n{}", warnings.join("\n")))
} else if recovery {
None
} else {
Some(
@ -608,7 +657,7 @@ impl Editor {
egui::ComboBox::new("Format", tr(ui.ctx(), "ui.format"))
.selected_text(self.files.export_codec.label())
.show_ui(ui, |ui| {
for codec in canvas_pilot::interchange::Codec::available() {
for codec in canvas_pilot::software::codecs() {
ui.stable_selectable_value(
&mut self.files.export_codec,
codec,
@ -633,12 +682,7 @@ impl Editor {
ui.horizontal(|ui| {load=ui.button(tr(ui.ctx(), "ui.open-project-5e5eba")).clicked();cancel=ui.button(tr(ui.ctx(), "ui.cancel")).clicked();});
});
if load {
self.start_project_job(ctx, false, move || {
let (project, native) =
canvas_pilot::interchange::read_project_or_parameters(&path)?;
// Never autosave JSON over the source artwork.
Ok(Some((project, native.then_some(path), None)))
});
self.start_project_open(ctx, path);
} else if open && !cancel {
self.files.opening = Some(path);
}
@ -674,7 +718,11 @@ impl Editor {
.collapsible(false)
.open(&mut open)
.show(ctx, |ui| {
ui.label(&message);
egui::ScrollArea::vertical()
.max_height(360.0)
.show(ui, |ui| {
ui.label(&message);
});
done = ui.button(tr(ui.ctx(), "ui.ok")).clicked();
});
if open && !done {
@ -687,6 +735,59 @@ impl Editor {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn partial_open_keeps_original_bytes_and_requires_save_as() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let mut raw = serde_json::to_value(app.project()).unwrap();
raw["layers"][0]["bounds"]["width"] = serde_json::json!(-1);
let bytes = raw.to_string();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("damaged.pilot.json");
std::fs::write(&path, &bytes).unwrap();
app.start_project_open(&ctx, path.clone());
app.wait_project_job();
assert_eq!(app.layout.layers().len(), 1);
assert!(app.files.project_path.is_none());
assert!(app.files.manual_saved_at.is_none());
assert!(
app.files
.message
.as_ref()
.unwrap()
.contains("recovered, unsaved copy")
);
app.autosave_position_points();
assert_eq!(std::fs::read_to_string(path).unwrap(), bytes);
}
#[test]
fn undecodable_reference_is_skipped_only_during_explicit_open() {
let ctx = egui::Context::default();
let mut project = Project::from_layout(&Layout::default());
project.references.push(SavedReference {
name: "broken.png".into(),
image_base64: STANDARD.encode(b"not an image"),
visible: true,
opacity: 1.0,
preserve_ratio: true,
native_size: false,
offset: [0.0; 2],
});
assert!(PreparedProject::prepare(&ctx, project.clone()).is_err());
let recovered = PreparedProject::prepare_recovered(
&ctx,
canvas_pilot::project_recovery::LoadedProject {
project,
warnings: vec![],
},
)
.unwrap();
assert!(recovered.references.is_empty());
assert_eq!(recovered.layout.layers().len(), 2);
assert_eq!(recovered.warnings.len(), 1);
}
#[test]
fn export_scope_is_explicit_and_unavailable_options_are_cleared() {
let ctx = egui::Context::default();
@ -775,25 +876,6 @@ mod tests {
assert_eq!(app.files.manual_saved_at, time);
}
#[test]
fn saved_input_proposals_reopen_inactive_and_follow_layer_identity() {
let ctx = egui::Context::default();
let mut app = Editor::default();
let project = Project::from_json(include_str!(
"../../../docs/interfaces/canvas-pilot-v16.example.json"
))
.unwrap();
app.device.input_edits.enabled = true;
app.install_project(&ctx, project.clone()).unwrap();
assert!(!app.device.input_edits.enabled);
assert_eq!(app.project().input_proposals, project.input_proposals);
app.layout.set_device_link(0, None).unwrap();
assert!(app.project().input_proposals.is_empty());
app.install_project(&ctx, Project::from_layout(&Layout::default()))
.unwrap();
assert!(app.device.input_edits.saved.is_empty());
}
#[test]
fn measurement_clicks_autosave_only_points_and_exports_keep_project_target() {
use super::super::tests::click_text;
@ -946,7 +1028,8 @@ mod tests {
app.corner = PositionPoint::TopLeft;
app.position_layer_point = Some(PositionPoint::Center);
app.backdrop_title = "Conference 2027 · Main stage".into();
app.keep_aspect_ratio = false;
app.layout.set_keep_aspect_ratio(1, false).unwrap();
app.sync();
app.show_pattern = true;
app.show_toolbar_icon_names = true;
app.layout

View File

@ -231,6 +231,18 @@ mod tests {
},
)
.unwrap();
let load = canvas_pilot::DeviceLink {
family: Default::default(),
screen: "1".into(),
layer: "1".into(),
};
let mut target = load.clone();
target.layer = "2".into();
let mut send = canvas_pilot::SendMapping::linked(Some(target.clone()));
target.screen = "2".into();
send.destinations
.extend(canvas_pilot::SendMapping::linked(Some(target)).destinations);
app.layout.set_device_mappings(0, Some(load), send).unwrap();
app.layout.set_layer_pivots(&[(1, [0.2, 0.7])]).unwrap();
app.corner = PositionPoint::BottomRight;
app.position_layer_point = Some(PositionPoint::Center);

View File

@ -3,6 +3,7 @@ use std::io::{Cursor, Read};
// Keep large concurrent imports from multiplying decoder peak memory.
static DECODE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Clone)]
pub(super) struct Reference {
pub texture: egui::TextureHandle,
pub name: String,

View File

@ -0,0 +1,466 @@
//! Local document-to-picture imports. Sources are never modified or saved over.
use hayro::hayro_syntax::Pdf;
use std::{io::Read, path::Path, sync::Arc};
pub const MAX_BYTES: usize = 64 * 1024 * 1024;
const MAX_PAGES: usize = 256;
static RENDER_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Clone)]
enum Source {
Pdf(Arc<Vec<u8>>),
Svg(Vec<String>),
}
#[derive(Clone)]
pub struct Document {
pub name: String,
pub pages: Vec<String>,
pub note: String,
source: Source,
}
/// Pictures plus every geometry format compiled into this build.
pub fn extensions() -> Vec<&'static str> {
let mut extensions = crate::software::geometry_extensions();
extensions.extend(["pdf", "png", "jpg", "jpeg", "bmp"]);
extensions
}
pub fn is_document(name: &Path) -> bool {
name.extension()
.and_then(|v| v.to_str())
.is_some_and(|ext| {
let ext = ext.to_ascii_lowercase();
!matches!(ext.as_str(), "png" | "jpg" | "jpeg" | "bmp")
&& extensions().contains(&ext.as_str())
})
}
pub fn read(path: &Path) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
std::fs::File::open(path)
.and_then(|f| f.take(MAX_BYTES as u64 + 1).read_to_end(&mut bytes))
.map_err(|e| format!("Cannot read reference document: {e}"))?;
check_size(&bytes)?;
Ok(bytes)
}
fn check_size(bytes: &[u8]) -> Result<(), String> {
if bytes.len() > MAX_BYTES {
Err("Reference document exceeds 64 MiB.".into())
} else {
Ok(())
}
}
impl Document {
/// `layout_only` explicitly requests the existing geometry codec's bounds view.
pub fn open(bytes: Vec<u8>, name: &str, layout_only: bool) -> Result<Self, String> {
check_size(&bytes)?;
let ext = Path::new(name)
.extension()
.and_then(|v| v.to_str())
.unwrap_or("")
.to_ascii_lowercase();
if matches!(ext.as_str(), "pptx" | "fig" | "figcraft" | "ai" | "dwg")
&& !crate::interchange::extensions().contains(&ext.as_str())
{
return Err("Vendor format support is disabled in this build.".into());
}
if ext == "pdf" || bytes.starts_with(b"%PDF-") {
return Self::pdf(
bytes,
name,
"PDF page rendered locally. Check the preview before adding it.",
);
}
if !layout_only && ext == "svg" {
return Ok(Self { name: name.into(), pages: vec!["Artwork".into()],
note: "SVG artwork. Embedded images and installed fonts are rendered; linked external images are omitted.".into(),
source: Source::Svg(vec![String::from_utf8(bytes).map_err(|e| e.to_string())?]) });
}
if !layout_only && matches!(ext.as_str(), "json" | "html") {
let text = std::str::from_utf8(&bytes).map_err(|e| e.to_string())?;
let svg = crate::geometry_formats::reference_svg(text, ext == "html")?;
return Ok(Self { name: name.into(), pages: vec!["Layout artwork".into()],
note: "Canvas Pilot exchange artwork, including embedded PNG pictures. HTML is rendered from its geometry data; custom CSS and scripts are not executed.".into(), source: Source::Svg(vec![svg]) });
}
if !layout_only && ext == "pptx" {
let pdf = office_pdf(&bytes)?;
return Self::pdf(
pdf,
name,
"Slides rendered by LibreOffice. Fonts and effects may differ from PowerPoint; check the preview.",
);
}
if !layout_only && matches!(ext.as_str(), "drawio" | "xml") {
let pdf = drawio_pdf(&bytes)?;
return Self::pdf(
pdf,
name,
"Diagram pages rendered by draw.io Desktop. Check the preview.",
);
}
#[cfg(all(feature = "vendor_formats", not(feature = "no_proprietary")))]
if !layout_only && ext == "ai" {
let pages = crate::vendor_formats::reference_ai(&bytes)?;
return Ok(Self { name: name.into(), pages: pages.iter().map(|p| p.0.clone()).collect(),
note: "Illustrator artwork converted by VectorCraft. Check the preview for conversion differences.".into(),
source: Source::Svg(pages.into_iter().map(|p| p.1).collect()) });
}
#[cfg(all(feature = "vendor_formats", not(feature = "no_proprietary")))]
if !layout_only && matches!(ext.as_str(), "fig" | "figcraft") {
let (pages, warnings) =
crate::vendor_formats::reference_fig(&bytes, name, ext == "figcraft")?;
return Ok(Self {
name: name.into(),
pages: pages.iter().map(|p| p.0.clone()).collect(),
note: format!(
"Figma artwork rendered through FigCraft (best effort). Check the preview. {warnings}"
),
source: Source::Svg(pages.into_iter().map(|p| p.1).collect()),
});
}
if !layout_only && !matches!(ext.as_str(), "json" | "csv" | "dxf" | "dwg") {
return Err("This format currently provides a layout preview only. Select ‘Layout boxes’ to render its supported geometry, or export PDF/SVG from the source application for the complete artwork.".into());
}
let pages = crate::interchange::import(&bytes, name)?;
let mut pictures = Vec::new();
for page in &pages {
pictures.push(layout_svg(&page.document)?);
}
Ok(Self { name: name.into(), pages: pages.iter().map(|p| p.name.clone()).collect(),
note: "Layout boxes only: labels and bounds from the geometry importer. Original artwork, fonts, pictures and decorative shapes are not reproduced. The preview fits the detected bounds.".into(),
source: Source::Svg(pictures) })
}
fn pdf(bytes: Vec<u8>, name: &str, note: &str) -> Result<Self, String> {
let pdf = parse_pdf(bytes.clone())?;
let count = pdf.pages().len();
if count == 0 || count > MAX_PAGES {
return Err("Choose a PDF with 1–256 pages.".into());
}
Ok(Self {
name: name.into(),
pages: (1..=count).map(|n| format!("Page {n}")).collect(),
note: note.into(),
source: Source::Pdf(Arc::new(bytes)),
})
}
/// Render only the chosen page, at a bounded size, and encode portable PNG bytes.
pub fn render(&self, page: usize, longest_side: u32) -> Result<Vec<u8>, String> {
if page >= self.pages.len() {
return Err("Reference page is out of range.".into());
}
if !(64..=4096).contains(&longest_side) {
return Err("Reference resolution must be 64–4096 pixels.".into());
}
let _guard = RENDER_LOCK
.lock()
.map_err(|_| "Document renderer stopped; please restart the app.")?;
let bytes = match &self.source {
Source::Pdf(bytes) => {
let pdf = parse_pdf(bytes.as_ref().clone())?;
let page = &pdf.pages()[page];
let (w, h) = page.render_dimensions();
let scale = render_scale(w, h, longest_side)?;
let pixmap = hayro::render(
page,
&hayro::RenderCache::new(),
&Default::default(),
&Default::default(),
&hayro::PixmapSettings {
x_scale: scale,
y_scale: scale,
bg_color: hayro::vello_cpu::color::palette::css::WHITE,
},
);
pixmap
.into_png()
.map_err(|e| format!("Cannot encode rendered PDF: {e}"))?
}
Source::Svg(pages) => render_svg(pages[page].as_bytes(), longest_side)?,
};
check_size(&bytes)?;
Ok(bytes)
}
}
fn parse_pdf(bytes: Vec<u8>) -> Result<Pdf, String> {
Pdf::new(bytes).map_err(|e| format!("Cannot open PDF ({e:?}). For a password-protected document, export an unlocked copy first."))
}
fn render_scale(width: f32, height: f32, longest: u32) -> Result<f32, String> {
if !width.is_finite() || !height.is_finite() || width <= 0.0 || height <= 0.0 {
return Err("Invalid document page dimensions.".into());
}
let scale = longest as f32 / width.max(height);
if width.min(height) * scale < 1.0 {
return Err("Document page is too narrow to render.".into());
}
Ok(scale)
}
fn render_svg(bytes: &[u8], longest: u32) -> Result<Vec<u8>, String> {
let mut options = resvg::usvg::Options::default();
options.image_href_resolver.resolve_string = Box::new(|_, _| None);
options.fontdb_mut().load_system_fonts();
let tree = resvg::usvg::Tree::from_data(bytes, &options)
.map_err(|e| format!("Cannot render SVG: {e}"))?;
let scale = render_scale(tree.size().width(), tree.size().height(), longest)?;
let width = (tree.size().width() * scale).ceil() as u32;
let height = (tree.size().height() * scale).ceil() as u32;
let mut pixmap =
resvg::tiny_skia::Pixmap::new(width, height).ok_or("Cannot allocate reference image.")?;
resvg::render(
&tree,
resvg::tiny_skia::Transform::from_scale(scale, scale),
&mut pixmap.as_mut(),
);
pixmap.encode_png().map_err(|e| e.to_string())
}
fn layout_svg(document: &crate::import::ImportDocument) -> Result<String, String> {
if document.shapes.is_empty() {
return Err("No supported layout shapes found.".into());
}
let mut bounds = [0.0_f64, 0.0_f64, 1.0_f64, 1.0_f64];
for s in &document.shapes {
let g = s.geometry.validate()?;
bounds[0] = bounds[0].min(g.x);
bounds[1] = bounds[1].min(g.y);
bounds[2] = bounds[2].max(g.x + g.width);
bounds[3] = bounds[3].max(g.y + g.height);
}
let [x, y, right, bottom] = bounds;
let width = right - x;
let height = bottom - y;
let mut svg = format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"{x} {y} {width} {height}\"><rect x=\"{x}\" y=\"{y}\" width=\"{width}\" height=\"{height}\" fill=\"#111720\"/>"
);
for s in &document.shapes {
let g = s.geometry;
let name = crate::exchange::escape(s.name.as_deref().unwrap_or(&s.id));
let fill = if s.background { "#1b2330" } else { "#315066" };
svg.push_str(&format!("<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" fill=\"{fill}\" stroke=\"#66dbef\" stroke-width=\"{}\"/><text x=\"{}\" y=\"{}\" font-family=\"sans-serif\" font-size=\"{}\" fill=\"white\">{name}</text>", g.x, g.y, g.width, g.height, width / 800.0, g.x + width / 200.0, g.y + height / 35.0, height / 45.0));
}
svg.push_str("</svg>");
Ok(svg)
}
fn office_pdf(bytes: &[u8]) -> Result<Vec<u8>, String> {
let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
let input = dir.path().join("source.pptx");
std::fs::write(&input, bytes).map_err(|e| e.to_string())?;
// A separate profile prevents handing the document to an already running user session.
let profile = url::Url::from_directory_path(dir.path().join("profile"))
.map_err(|_| "Invalid converter profile path")?;
let mut cmd = std::process::Command::new(crate::software::Software::LibreOffice.executable()?);
cmd.arg(format!("-env:UserInstallation={profile}"))
.args([
"--headless",
"--convert-to",
"pdf:impress_pdf_Export",
"--outdir",
])
.arg(dir.path())
.arg(input);
run_converter(&mut cmd, "LibreOffice", "CANVAS_PILOT_LIBREOFFICE")?;
read(&dir.path().join("source.pdf"))
}
fn drawio_pdf(bytes: &[u8]) -> Result<Vec<u8>, String> {
let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
let input = dir.path().join("source.drawio");
let output = dir.path().join("source.pdf");
std::fs::write(&input, bytes).map_err(|e| e.to_string())?;
let mut cmd = std::process::Command::new(crate::software::Software::Drawio.executable()?);
cmd.args(["--export", "--format", "pdf", "--all-pages", "--output"])
.arg(&output)
.arg(input);
run_converter(&mut cmd, "draw.io Desktop", "CANVAS_PILOT_DRAWIO")?;
read(&output)
}
fn run_converter(cmd: &mut std::process::Command, label: &str, env: &str) -> Result<(), String> {
use std::{
process::Stdio,
time::{Duration, Instant},
};
let mut child = cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()
.map_err(|e| format!("Cannot start {label}: {e}. Install it or set {env} to its executable. You can also select Layout boxes or import an exported PDF/SVG."))?;
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => return Ok(()),
Ok(Some(status)) => {
return Err(format!(
"{label} conversion failed ({status}). Export PDF/SVG in the source application, or use Layout boxes."
));
}
Ok(None) if start.elapsed() < Duration::from_secs(60) => {
std::thread::sleep(Duration::from_millis(50))
}
result => {
let _ = child.kill();
let _ = child.wait();
return Err(format!(
"{label} did not finish within 60 seconds: {result:?}"
));
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const PDF: &[u8] = include_bytes!("../tests/fixtures/reference-pages.pdf");
#[test]
fn pdf_page_selection_crop_and_rotation_render_distinct_images() {
let document = Document::open(PDF.to_vec(), "client.PDF", false).unwrap();
assert_eq!(document.pages, ["Page 1", "Page 2"]);
let red = image::load_from_memory(&document.render(0, 200).unwrap())
.unwrap()
.into_rgba8();
assert_eq!(red.dimensions(), (200, 100));
assert_eq!(red.get_pixel(50, 50).0, [255, 0, 0, 255]);
let green = image::load_from_memory(&document.render(1, 200).unwrap())
.unwrap()
.into_rgba8();
assert_eq!(green.dimensions(), (200, 200));
assert_eq!(green.get_pixel(50, 50).0, [0, 255, 0, 255]);
assert!(document.render(2, 200).is_err());
assert!(document.render(0, 8192).is_err());
}
#[test]
fn svg_artwork_keeps_color_transparency_and_does_not_fetch_linked_images() {
let svg = br#"<svg xmlns="http://www.w3.org/2000/svg" width="200" height="100"><rect width="100" height="100" fill="red"/><image href="file:///not-a-reference.png" x="100" width="100" height="100"/></svg>"#;
let doc = Document::open(svg.to_vec(), "art.svg", false).unwrap();
let image = image::load_from_memory(&doc.render(0, 200).unwrap())
.unwrap()
.into_rgba8();
assert_eq!(image.dimensions(), (200, 100));
assert_eq!(image.get_pixel(10, 10).0, [255, 0, 0, 255]);
assert_eq!(image.get_pixel(150, 50).0[3], 0);
assert!(Document::open(b"broken".to_vec(), "bad.pdf", false).is_err());
assert!(
Document::open(b"broken".to_vec(), "bad.svg", false)
.unwrap()
.render(0, 200)
.is_err()
);
assert!(render_scale(f32::INFINITY, 1.0, 200).is_err());
assert!(render_scale(0.0, 1.0, 200).is_err());
assert!(render_scale(1e20, 1.0, 200).is_err());
}
#[test]
fn supported_exchange_documents_offer_explicit_layout_pictures() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../docs/templates/canvas-pilot");
for codec in crate::interchange::Codec::available() {
if codec == crate::interchange::Codec::Illustrator {
continue;
}
let path = root.join(format!("canvas-pilot-template.{}", codec.extension()));
// The catalog owns the canonical starter basename.
let path = if path.exists() {
path
} else {
std::fs::read_dir(&root)
.unwrap()
.filter_map(Result::ok)
.map(|e| e.path())
.find(|p| p.extension().and_then(|e| e.to_str()) == Some(codec.extension()))
.unwrap()
};
let doc = Document::open(
read(&path).unwrap(),
path.file_name().unwrap().to_str().unwrap(),
true,
)
.unwrap();
assert!(doc.note.contains("Layout boxes only"), "{}", codec.label());
assert!(!doc.render(0, 320).unwrap().is_empty(), "{}", codec.label());
}
assert!(is_document(Path::new("drawing.PDF")));
assert!(!is_document(Path::new("picture.PNG")));
assert!(!is_document(Path::new("unknown.xyz")));
}
#[test]
fn json_and_html_artwork_preserve_embedded_images_and_canvas() {
use crate::exchange::{ExportShape, Format, encode_shapes};
use base64::Engine;
let mut png = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255]))
.write_to(&mut png, image::ImageFormat::Png)
.unwrap();
let shapes = [ExportShape {
id: "red".into(),
name: "Picture".into(),
geometry: crate::Geometry {
x: 0.,
y: 0.,
width: 200.,
height: 100.,
},
image_png_base64: Some(
base64::engine::general_purpose::STANDARD.encode(png.into_inner()),
),
background: true,
}];
for format in [Format::Json, Format::Html] {
let bytes = encode_shapes(format, [200, 100], &shapes)
.unwrap()
.into_bytes();
let doc =
Document::open(bytes, &format!("client.{}", format.extension()), false).unwrap();
let image = image::load_from_memory(&doc.render(0, 200).unwrap())
.unwrap()
.into_rgba8();
assert_eq!(image.dimensions(), (200, 100));
assert_eq!(image.get_pixel(50, 50).0, [255, 0, 0, 255]);
}
}
#[cfg(all(feature = "vendor_formats", not(feature = "no_proprietary")))]
#[test]
fn figma_artwork_is_rendered_with_embedded_pictures() {
use crate::exchange::ExportShape;
use base64::Engine;
let mut png = std::io::Cursor::new(Vec::new());
image::RgbaImage::from_pixel(2, 2, image::Rgba([255, 0, 0, 255]))
.write_to(&mut png, image::ImageFormat::Png)
.unwrap();
let shapes = [ExportShape {
id: "red".into(),
name: "Picture".into(),
geometry: crate::Geometry {
x: 0.,
y: 0.,
width: 200.,
height: 100.,
},
image_png_base64: Some(
base64::engine::general_purpose::STANDARD.encode(png.into_inner()),
),
background: false,
}];
for codec in [
crate::interchange::Codec::Figma,
crate::interchange::Codec::Figcraft,
] {
let bytes = crate::vendor_formats::export(codec, [200, 100], &shapes).unwrap();
let doc = Document::open(bytes, &format!("art.{}", codec.extension()), false).unwrap();
let image = image::load_from_memory(&doc.render(0, 200).unwrap())
.unwrap()
.into_rgba8();
assert_eq!(image.get_pixel(50, 50).0, [255, 0, 0, 255]);
}
}
}

View File

@ -0,0 +1,250 @@
//! Selection guides stay above layer artwork; covered edge segments are dashed.
use super::*;
/// Visible picture bounds of higher layers, excluding hidden and blanked regions.
pub(super) fn covers(layout: &Layout, index: usize, origin: Pos2, scale: f32) -> Vec<Rect> {
let to_rect = |g: Geometry| {
Rect::from_min_size(
origin + Vec2::new(g.x as f32, g.y as f32) * scale,
Vec2::new(g.width as f32, g.height as f32) * scale,
)
};
layout
.viewport_order()
.into_iter()
.skip_while(|&i| i != index)
.skip(1)
.filter(|&i| layout.visible(i))
.filter_map(|i| {
let g = layout.layers()[i];
let formats = layout.formats();
let mut rect = to_rect(g).intersect(to_rect(formats.mask_bounds(i, g).ok()?));
if let Some(fit) = formats.layer_fit[i] {
let retained = formats.advanced[i].remaining(formats.input(i).ok()?).ok()?;
rect = rect.intersect(to_rect(fit.image(retained, g).ok()?));
}
rect.is_positive().then_some(rect)
})
.collect()
}
// Merge covered intervals before painting: overlaps must not fill dash gaps twice.
fn intervals(start: f32, end: f32, fixed: f32, horizontal: bool, covers: &[Rect]) -> Vec<[f32; 2]> {
let mut spans: Vec<_> = covers
.iter()
.filter_map(|rect| {
let (min, max, cross_min, cross_max) = if horizontal {
(rect.left(), rect.right(), rect.top(), rect.bottom())
} else {
(rect.top(), rect.bottom(), rect.left(), rect.right())
};
let span = [start.max(min), end.min(max)];
(fixed >= cross_min && fixed <= cross_max && span[0] < span[1]).then_some(span)
})
.collect();
spans.sort_by(|a, b| a[0].total_cmp(&b[0]));
let mut merged: Vec<[f32; 2]> = Vec::new();
for span in spans {
if let Some(last) = merged.last_mut()
&& span[0] <= last[1]
{
last[1] = last[1].max(span[1]);
} else {
merged.push(span);
}
}
merged
}
pub(super) fn paint(painter: &egui::Painter, rect: Rect, covers: &[Rect], stroke: Stroke) {
let clip = painter.clip_rect();
for (horizontal, fixed, start, end) in [
(true, rect.top(), rect.left(), rect.right()),
(true, rect.bottom(), rect.left(), rect.right()),
(false, rect.left(), rect.top(), rect.bottom()),
(false, rect.right(), rect.top(), rect.bottom()),
] {
let (min, max, cross_min, cross_max) = if horizontal {
(clip.left(), clip.right(), clip.top(), clip.bottom())
} else {
(clip.top(), clip.bottom(), clip.left(), clip.right())
};
if fixed < cross_min || fixed > cross_max {
continue;
}
let (start, end) = (start.max(min), end.min(max));
if start >= end {
continue;
}
let point = |v| {
if horizontal {
Pos2::new(v, fixed)
} else {
Pos2::new(fixed, v)
}
};
let mut cursor = start;
for [from, to] in intervals(start, end, fixed, horizontal, covers) {
if cursor < from {
painter.line_segment([point(cursor), point(from)], stroke);
}
// Clip first so zooming into a huge layer never generates off-screen dashes.
painter.extend(egui::Shape::dashed_line(
&[point(from), point(to)],
stroke,
6.0,
4.0,
));
cursor = to;
}
if cursor < end {
painter.line_segment([point(cursor), point(end)], stroke);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn coverage_merges_overlaps_clips_and_keeps_uncovered_edges_solid() {
let rects = [
Rect::from_min_max(Pos2::new(10.0, 0.0), Pos2::new(40.0, 50.0)),
Rect::from_min_max(Pos2::new(30.0, 0.0), Pos2::new(60.0, 50.0)),
Rect::from_min_max(Pos2::new(80.0, 0.0), Pos2::new(100.0, 50.0)),
];
assert_eq!(
intervals(20.0, 90.0, 25.0, true, &rects),
[[20.0, 60.0], [80.0, 90.0]]
);
assert!(intervals(0.0, 100.0, 51.0, true, &rects).is_empty());
assert_eq!(intervals(10.0, 70.0, 35.0, false, &rects), [[10.0, 50.0]]);
}
#[test]
fn only_visible_higher_picture_regions_cover_guides() {
let mut layout = Layout::default();
layout.select(Some(1));
layout
.apply(
1,
Geometry {
x: 0.0,
y: 0.0,
width: 600.0,
height: 600.0,
},
)
.unwrap();
assert!(covers(&layout, 1, Pos2::ZERO, 1.0).is_empty());
layout
.set_mask(
1,
canvas_pilot::formats::Mask {
left: 0.25,
..Default::default()
},
)
.unwrap();
let covered = covers(&layout, 0, Pos2::new(10.0, 20.0), 2.0);
assert_eq!(
covered,
[Rect::from_min_max(
Pos2::new(310.0, 20.0),
Pos2::new(1210.0, 1220.0)
)]
);
layout.set_visible(1, false);
assert!(covers(&layout, 0, Pos2::ZERO, 1.0).is_empty());
layout.set_visible(1, true);
layout.set_mask(1, Default::default()).unwrap();
layout
.set_layer_fit(
1,
Some(canvas_pilot::formats::LayerFit::Centered),
Default::default(),
)
.unwrap();
let covered = covers(&layout, 0, Pos2::ZERO, 1.0);
assert!(covered[0].height() < 600.0);
assert_eq!(covered[0].center(), Pos2::new(300.0, 300.0));
}
#[test]
fn resize_crop_and_mask_handles_stay_above_covering_artwork() {
use super::super::tests::frame;
for mode in 0..3 {
let ctx = egui::Context::default();
let mut app = Editor::default();
let g = Geometry {
x: 200.0,
y: 200.0,
width: 640.0,
height: 360.0,
};
for i in 0..2 {
app.layout.select(Some(i));
app.layout.apply(i, g).unwrap();
}
app.layout.select(Some(0));
app.edit_content = mode != 0;
app.edit_mask = mode == 2;
app.sync();
let before = app.project();
frame(&mut app, &ctx, vec![]);
let output = frame(&mut app, &ctx, vec![]);
let palette = theme::palette(&ctx);
let color = match mode {
0 => palette.amber,
1 => palette.cyan,
_ => Color32::from_rgb(222, 108, 220),
};
let size = if mode == 0 { 7.0 } else { 9.0 };
let handles: Vec<_> = output
.shapes
.iter()
.enumerate()
.filter_map(|(index, shape)| {
if let egui::Shape::Rect(rect) = &shape.shape
&& (rect.rect.size() - Vec2::splat(size)).length() < 0.001
&& rect.stroke.color == color
{
Some((index, rect.rect.center()))
} else {
None
}
})
.collect();
assert_eq!(handles.len(), 8, "mode {mode}");
let top_artwork = output
.shapes
.iter()
.rposition(|shape| {
matches!(&shape.shape,
egui::Shape::Rect(rect) if rect.fill == palette.layer && rect.rect.width() > 100.0)
})
.unwrap();
assert!(handles.iter().all(|(index, _)| *index > top_artwork));
let dashes = output.shapes.iter().filter(|shape| matches!(&shape.shape,
egui::Shape::LineSegment { points, stroke } if stroke.color == color && points[0].distance(points[1]) <= 6.01)).count();
assert!(dashes > 20, "covered guide should be dashed in mode {mode}");
assert_eq!(app.project(), before);
}
}
#[test]
fn dashed_paint_is_bounded_by_viewport_at_extreme_zoom() {
let ctx = egui::Context::default();
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui
.painter()
.with_clip_rect(Rect::from_min_size(Pos2::ZERO, Vec2::splat(100.0)));
let rect = Rect::from_min_max(Pos2::new(-1e9, 20.0), Pos2::new(1e9, 80.0));
paint(&painter, rect, &[rect], Stroke::new(1.0, Color32::GOLD));
});
let lines = output
.shapes
.iter()
.filter(|shape| matches!(shape.shape, egui::Shape::LineSegment { .. }))
.count();
assert_eq!(lines, 20);
}
}

View File

@ -24,7 +24,7 @@ pub struct Settings {
impl Default for Settings {
fn default() -> Self {
Self {
version: 14,
version: 16,
ui_scale: 1.0,
text_scale: None,
language: Default::default(),
@ -45,6 +45,14 @@ impl Default for Settings {
impl Settings {
fn parse(text: &str) -> Result<Self, String> {
let mut value: serde_json::Value = serde_json::from_str(text).map_err(|e| e.to_string())?;
if value["version"].as_u64().is_some_and(|v| v <= 14)
&& (value["theme"].is_object()
|| value["recent_themes"]
.as_array()
.is_some_and(|themes| themes.iter().any(|t| t.is_object())))
{
return Err("Theme packs require settings version 15".into());
}
if value["version"] == 1 {
if value.get("recent_themes").is_some() {
return Err("Unexpected recent_themes in version 1 settings".into());
@ -66,7 +74,13 @@ impl Settings {
}
value["snapping"] = serde_json::to_value(canvas_pilot::snapping::Snapping::default())
.map_err(|e| e.to_string())?;
for field in ["grid", "show_grid", "grid_divisions", "mask_edges"] {
for field in [
"grid",
"show_grid",
"grid_divisions",
"mask_edges",
"force_pixels",
] {
value["snapping"].as_object_mut().unwrap().remove(field);
}
value["version"] = 3.into();
@ -173,17 +187,37 @@ impl Settings {
snapping.insert("mask_edges".into(), false.into());
value["version"] = 14.into();
}
if value["version"] == 14 && value.get("text_scale").is_none() {
return Err("Missing text_scale in version 14 settings".into());
if matches!(value["version"].as_u64(), Some(14..=16)) && value.get("text_scale").is_none() {
return Err("Missing text_scale in current settings".into());
}
if value["version"] == 14 {
value["version"] = 15.into();
}
if value["version"] == 15 {
let snapping = value["snapping"]
.as_object_mut()
.ok_or("Missing snapping")?;
if snapping.contains_key("force_pixels") {
return Err("Unexpected force_pixels in old settings".into());
}
snapping.insert("force_pixels".into(), false.into());
value["version"] = 16.into();
}
let settings: Self = serde_json::from_value(value).map_err(|e| e.to_string())?;
settings.validate()?;
Ok(settings)
}
fn validate(&self) -> Result<(), String> {
if self.version != 14 {
if self.version != 16 {
return Err(format!("unsupported settings version {}", self.version));
}
for theme in std::iter::once(&self.theme).chain(&self.recent_themes) {
if let Theme::Pack(id) = theme
&& !crate::theme_packs::valid_choice(id)
{
return Err("Invalid installed theme identifier".into());
}
}
if let crate::localization::Language::Pack(id) = &self.language
&& !crate::language_packs::valid_id(id)
{
@ -323,12 +357,38 @@ impl Store {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn installed_themes_require_v15_and_round_trip_without_losing_other_options() {
let legacy =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v14.example.json");
let current =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v16.example.json");
assert_eq!(
Settings::parse(legacy).unwrap(),
Settings::parse(current).unwrap()
);
let mut value: serde_json::Value = serde_json::from_str(current).unwrap();
value["theme"] = serde_json::json!({"pack":"tokyo-night/night"});
value["recent_themes"] =
serde_json::json!([{"pack":"tokyo-night/night"},"high_contrast","midra"]);
let saved = Settings::parse(&value.to_string()).unwrap();
assert_eq!(serde_json::to_value(saved).unwrap(), value);
value["version"] = 14.into();
assert!(Settings::parse(&value.to_string()).is_err());
value["version"] = 16.into();
for id in ["", "no-slash", "../theme", "pack/a/b", "pack/Upper"] {
value["theme"] = serde_json::json!({"pack":id});
value["recent_themes"][0] = value["theme"].clone();
assert!(Settings::parse(&value.to_string()).is_err());
}
}
#[test]
fn mask_snapping_migrates_and_requires_current_schema() {
let legacy =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v13.example.json");
let current =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v14.example.json");
include_str!("../../../docs/interfaces/canvas-pilot-settings-v16.example.json");
assert_eq!(
Settings::parse(legacy).unwrap(),
Settings::parse(current).unwrap()
@ -348,6 +408,28 @@ mod tests {
assert!(Settings::parse(&value.to_string()).is_err());
}
#[test]
fn forced_pixel_snapping_migrates_disabled_and_round_trips() {
let legacy =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v15.example.json");
let current =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v16.example.json");
assert_eq!(
Settings::parse(legacy).unwrap(),
Settings::parse(current).unwrap()
);
let mut value: serde_json::Value = serde_json::from_str(current).unwrap();
value["snapping"]["force_pixels"] = true.into();
assert!(
Settings::parse(&value.to_string())
.unwrap()
.snapping
.force_pixels
);
value["version"] = 15.into();
assert!(Settings::parse(&value.to_string()).is_err());
}
#[test]
fn scaling_migrates_and_round_trips_with_strict_limits() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v10.example.json");
@ -417,7 +499,7 @@ mod tests {
let old = include_str!("../../../docs/interfaces/canvas-pilot-settings-v8.example.json");
let migrated = Settings::parse(old).unwrap();
assert_eq!(migrated.language, Language::System);
assert_eq!(migrated.version, 14);
assert_eq!(migrated.version, 16);
let current =
include_str!("../../../docs/interfaces/canvas-pilot-settings-v10.example.json");
assert_eq!(Settings::parse(current).unwrap(), migrated);
@ -426,13 +508,14 @@ mod tests {
let mut old: serde_json::Value = serde_json::from_str(v9).unwrap();
old["language"] = old_language.into();
let upgraded = Settings::parse(&old.to_string()).unwrap();
assert_eq!(upgraded.version, 14);
assert_eq!(upgraded.version, 16);
assert_eq!(
serde_json::to_value(&upgraded.language).unwrap(),
old["language"]
);
old["version"] = 14.into();
old["version"] = 16.into();
old["snapping"]["mask_edges"] = false.into();
old["snapping"]["force_pixels"] = false.into();
old["ui_scale"] = serde_json::json!(1.0);
old["text_scale"] = serde_json::Value::Null;
assert_eq!(serde_json::to_value(upgraded).unwrap(), old);
@ -474,8 +557,9 @@ mod tests {
assert!(Settings::parse(&value.to_string()).is_err());
value["version"] = 13.into();
let saved = Settings::parse(&value.to_string()).unwrap();
value["version"] = 14.into();
value["version"] = 16.into();
value["snapping"]["mask_edges"] = false.into();
value["snapping"]["force_pixels"] = false.into();
assert_eq!(serde_json::to_value(saved).unwrap(), value);
for id in ["", "../uk", "uk_UA"] {
value["language"] = serde_json::json!({"pack":id});
@ -510,8 +594,9 @@ mod tests {
value["ui_scale"] = 1.5.into();
value["text_scale"] = 1.25.into();
let saved = Settings::parse(&value.to_string()).unwrap();
value["version"] = 14.into();
value["version"] = 16.into();
value["snapping"]["mask_edges"] = false.into();
value["snapping"]["force_pixels"] = false.into();
assert_eq!(serde_json::to_value(saved).unwrap(), value);
}
}
@ -584,7 +669,7 @@ mod tests {
for text in [
"broken".to_string(),
serde_json::to_string(&Settings {
version: 15,
version: 17,
..Default::default()
})
.unwrap(),

View File

@ -0,0 +1,208 @@
//! Explicit size presets in output-screen pixels, committed as one geometry edit.
use crate::{Geometry, Layout};
/// Position and size selected layers without routing sources or changing stacking.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SizePreset {
/// Every selected layer covers the output screen.
Fullscreen,
/// One half-width, half-height layer at a position in a 3×3 alignment grid.
Quarter { column: u8, row: u8 },
/// Fill cells left-to-right, top-to-bottom; excess layers repeat cells.
Tiles { columns: u16, rows: u16 },
/// Put the shorter dimension on X, preserving top-left position.
Portrait,
/// Put the longer dimension on X, preserving top-left position.
Landscape,
}
impl Layout {
/// Apply a preset in layer-list order, including members of collapsed folders.
/// All affected geometry/crop changes succeed together and share one Undo step.
pub fn apply_size_preset(&mut self, preset: SizePreset) -> Result<(), String> {
self.apply_size_preset_with_proportions(preset, false)
}
/// Fit each layer inside its destination without changing its current aspect
/// ratio when requested. Orientation presets remain explicit dimension swaps.
pub fn apply_size_preset_with_proportions(
&mut self,
preset: SizePreset,
keep_proportions: bool,
) -> Result<(), String> {
let selected = self.selected_indices();
if selected.is_empty() {
return Err("Select at least one layer for a size preset.".into());
}
if selected.iter().any(|&i| !self.selectable(i)) {
return Err("Unlock and show selected layers before resizing them.".into());
}
match preset {
SizePreset::Quarter { column, row } if column > 2 || row > 2 || selected.len() != 1 => {
return Err("Choose one layer and a position in the 3×3 quarter grid.".into());
}
SizePreset::Tiles { columns, rows }
if !(1..=256).contains(&columns) || !(1..=256).contains(&rows) =>
{
return Err("Use 1–256 columns and rows.".into());
}
_ => {}
}
let mut seen = std::collections::BTreeSet::new();
let mut order = Vec::new();
for i in (0..self.layers.len()).rev() {
let folder = &self.info[i].folder;
if folder.is_empty() {
if self.selected[i] {
order.push(i);
}
} else if seen.insert(folder.clone()) {
order.extend(
self.folder_members(folder)
.into_iter()
.rev()
.filter(|&j| self.selected[j]),
);
}
}
let [width, height] = self.formats.output.map(f64::from);
let mut next = self.layers.clone();
for (position, i) in order.into_iter().enumerate() {
let original = next[i];
next[i] = match preset {
SizePreset::Fullscreen => Geometry {
x: 0.0,
y: 0.0,
width,
height,
},
SizePreset::Quarter { column, row } => Geometry {
x: f64::from(column) * width / 4.0,
y: f64::from(row) * height / 4.0,
width: width / 2.0,
height: height / 2.0,
},
SizePreset::Tiles { columns, rows } => {
let column = position
% (usize::from(columns) * usize::from(rows))
% usize::from(columns);
let row = position % (usize::from(columns) * usize::from(rows))
/ usize::from(columns);
let cell_width = width / f64::from(columns);
let cell_height = height / f64::from(rows);
Geometry {
x: column as f64 * cell_width,
y: row as f64 * cell_height,
width: cell_width,
height: cell_height,
}
}
SizePreset::Portrait => Geometry {
width: original.width.min(original.height),
height: original.width.max(original.height),
..original
},
SizePreset::Landscape => Geometry {
width: original.width.max(original.height),
height: original.width.min(original.height),
..original
},
};
if keep_proportions && !matches!(preset, SizePreset::Portrait | SizePreset::Landscape) {
let target = next[i];
let scale = (target.width / original.width).min(target.height / original.height);
let width = original.width * scale;
let height = original.height * scale;
next[i] = Geometry {
x: target.x + (target.width - width) / 2.0,
y: target.y + (target.height - height) / 2.0,
width,
height,
};
}
}
self.finish_drag();
self.commit(next)
}
}
impl Layout {
/// Replace layer cropping with a centered ratio crop from uncropped bounds.
pub fn apply_crop_preset(&mut self, aspect: crate::formats::Aspect) -> Result<(), String> {
self.apply_crop_preset_with_existing(aspect, false)
}
/// Optionally trim inside the existing crop instead of restoring its bounds.
pub fn apply_crop_preset_with_existing(
&mut self,
aspect: crate::formats::Aspect,
keep_existing: bool,
) -> Result<(), String> {
use crate::formats::Aspect;
let ratio = match aspect {
Aspect::FourThree | Aspect::SixteenNine | Aspect::SixteenTen => aspect.ratio().unwrap(),
_ => return Err("Choose a 4:3, 16:9 or 16:10 crop preset.".into()),
};
let selected = self.selected_indices();
if selected.is_empty() {
return Err("Select at least one layer for a crop preset.".into());
}
let mut layers = self.layers.clone();
let mut formats = self.formats.clone();
for i in selected {
if !self.selectable(i) {
return Err("Unlock and show selected layers before cropping them.".into());
}
let mut old = layers[i];
if !keep_existing && formats.advanced[i] != Default::default() {
let input = formats.input(i)?;
let retained = formats.advanced[i].remaining(input)?;
let width = old.width * input[0] / retained[0];
let height = old.height * input[1] / retained[1];
old = Geometry {
x: old.x + (old.width - width) / 2.0,
y: old.y + (old.height - height) / 2.0,
width,
height,
}
.validate()?;
formats.advanced[i] = Default::default();
layers[i] = old;
}
if (old.width / old.height - ratio).abs() <= ratio * 1e-10 {
continue;
}
let width = old.width.min(old.height * ratio);
let height = old.height.min(old.width / ratio);
let next = Geometry {
x: old.x + (old.width - width) / 2.0,
y: old.y + (old.height - height) / 2.0,
width,
height,
}
.validate()?;
let input = formats.input(i)?;
let retained = formats.advanced[i].remaining(input)?;
let image = match formats.layer_fit[i] {
Some(mode) => mode.image(retained, old)?,
None => old,
};
let crop = &mut formats.advanced[i];
crop.left += ((next.x - image.x) / image.width * retained[0]).max(0.0);
crop.right +=
((image.x + image.width - next.x - width) / image.width * retained[0]).max(0.0);
crop.top += ((next.y - image.y) / image.height * retained[1]).max(0.0);
crop.bottom +=
((image.y + image.height - next.y - height) / image.height * retained[1]).max(0.0);
crop.remaining(input)?;
formats.mapping(i, next)?;
layers[i] = next;
}
self.finish_drag();
let before = self.snapshot();
self.layers = layers;
self.formats = formats;
self.remember(before);
Ok(())
}
}

View File

@ -0,0 +1,464 @@
use super::*;
use canvas_pilot::size_presets::SizePreset;
#[derive(Clone, Copy)]
enum Icon {
Fullscreen,
Quarter,
Tiles,
Portrait,
Landscape,
}
impl Icon {
fn key(self) -> &'static str {
match self {
Self::Fullscreen => "preset.fullscreen",
Self::Quarter => "preset.quarter",
Self::Tiles => "preset.tiling",
Self::Portrait => "preset.portrait",
Self::Landscape => "preset.landscape",
}
}
}
fn paint_icon(ui: &egui::Ui, rect: Rect, icon: Icon, enabled: bool) {
let palette = theme::palette(ui.ctx());
let color = if enabled {
palette.text
} else {
palette.muted.gamma_multiply(0.5)
};
let stroke = Stroke::new(1.5, color);
let center = rect.center();
let size = match icon {
Icon::Portrait => Vec2::new(13.0, 22.0),
Icon::Landscape => Vec2::new(24.0, 13.0),
_ => Vec2::new(24.0, 18.0),
};
let screen = Rect::from_center_size(center, size);
ui.painter()
.rect_stroke(screen, 1.0, stroke, StrokeKind::Inside);
match icon {
Icon::Fullscreen => {
ui.painter().rect_filled(
screen.shrink(4.0),
0.0,
palette.cyan.gamma_multiply(if enabled { 0.9 } else { 0.3 }),
);
}
Icon::Quarter | Icon::Tiles => {
let columns = if matches!(icon, Icon::Tiles) { 3 } else { 2 };
for column in 1..columns {
let x = screen.left() + screen.width() * column as f32 / columns as f32;
ui.painter().line_segment(
[Pos2::new(x, screen.top()), Pos2::new(x, screen.bottom())],
stroke,
);
}
ui.painter()
.line_segment([screen.left_center(), screen.right_center()], stroke);
ui.painter().rect_filled(
Rect::from_min_size(
screen.min + Vec2::splat(2.0),
Vec2::new(
screen.width() / columns as f32 - 3.0,
screen.height() / 2.0 - 3.0,
),
),
0.0,
palette.cyan.gamma_multiply(if enabled { 0.9 } else { 0.3 }),
);
}
Icon::Portrait | Icon::Landscape => {
ui.painter().line_segment(
[screen.min + Vec2::splat(4.0), screen.max - Vec2::splat(4.0)],
stroke,
);
}
}
}
impl Editor {
pub(super) fn size_presets_enabled(&self) -> bool {
!self.layout.selected_indices().is_empty()
&& !self.layout.dragging()
&& !self
.format_draft
.as_ref()
.is_some_and(|draft| draft.pending(&self.layout))
&& !(self.fields_edited && self.fields_pending())
&& !self.ratio_edit.dirty
}
pub(super) fn crop_preset_buttons(&mut self, ui: &mut egui::Ui) -> bool {
let mut changed = false;
ui.label("Crop borders to ratio");
ui.checkbox(&mut self.crop_preset_keep_existing, "Crop within existing crop")
.on_hover_text("Off: restore uncropped layer bounds before applying the ratio. On: trim the current crop further.");
ui.horizontal(|ui| {
for aspect in [canvas_pilot::formats::Aspect::FourThree, canvas_pilot::formats::Aspect::SixteenNine, canvas_pilot::formats::Aspect::SixteenTen] {
if ui.add_enabled(self.size_presets_enabled(), egui::Button::new(aspect.label()))
.on_hover_text("Trim centered borders and keep the layer center. By default each ratio replaces the previous crop.").clicked() {
match self.layout.apply_crop_preset_with_existing(aspect, self.crop_preset_keep_existing) {
Ok(()) => {
if self.format_draft.is_some() {
self.format_draft = self.layout.selected().map(|i| FormatDraft::new(&self.layout, i));
}
self.sync(); changed = true;
}
Err(error) => self.error = error,
}
}
}
});
changed
}
fn apply_size_preset(&mut self, preset: SizePreset) {
if !self.size_presets_enabled() {
return;
}
match self
.layout
.apply_size_preset_with_proportions(preset, self.size_keep_proportions)
{
Ok(()) => {
if self.format_draft.is_some() {
self.format_draft = self
.layout
.selected()
.map(|i| FormatDraft::new(&self.layout, i));
}
self.sync();
}
Err(error) => self.error = error,
}
}
pub(super) fn size_preset_toolbar(&mut self, ui: &mut egui::Ui, rect: Rect, captions: bool) {
let enabled = self.size_presets_enabled();
let palette = theme::palette(ui.ctx());
let label = "Size presets";
let response = ui
.add_enabled_ui(enabled, |ui| {
let response =
ui.interact(rect, egui::Id::new("size-presets"), egui::Sense::click());
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, label)
});
if response.hovered() || response.has_focus() {
ui.painter()
.rect_filled(rect.shrink(1.0), 3.0, palette.purple);
}
paint_icon(ui, rect, Icon::Tiles, enabled);
response
})
.inner;
egui::Popup::menu(&response)
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
.show(|ui| {
ui.label(label);
ui.checkbox(&mut self.size_keep_proportions, "Keep proportions")
.on_hover_text("Fit each layer inside its destination, centered, without changing its aspect ratio. Applies to fullscreen, quarters, halves and tiling.");
ui.separator();
for icon in [Icon::Fullscreen, Icon::Quarter, Icon::Tiles, Icon::Portrait, Icon::Landscape] {
ui.horizontal(|ui| {
let (_, rect) = ui.allocate_space(Vec2::new(30.0, 26.0));
paint_icon(ui, rect, icon, true);
let label = tr(ui.ctx(), icon.key());
match icon {
Icon::Quarter => { ui.collapsing(label, |ui| self.quarter_presets_menu(ui)); }
Icon::Tiles => { ui.collapsing(label, |ui| self.tiling_presets_menu(ui)); }
_ => {
if ui.button(label).clicked() {
self.apply_size_preset(match icon {
Icon::Fullscreen => SizePreset::Fullscreen,
Icon::Portrait => SizePreset::Portrait,
_ => SizePreset::Landscape,
});
egui::Popup::close_all(ui.ctx());
}
}
}
});
}
});
response.on_hover_text(if enabled {
label.to_owned()
} else {
format!("{label} — select layers and finish pending numeric edits first")
});
if captions {
ui.painter().text(
rect.center_bottom() + Vec2::new(0.0, 7.0),
Align2::CENTER_TOP,
label,
FontId::proportional(11.0),
palette.muted,
);
}
}
fn quarter_presets_menu(&mut self, ui: &mut egui::Ui) {
let count = self.layout.selected_indices().len();
ui.label(tr(ui.ctx(), "preset.quarter"));
if count == 1 {
let labels = [
["Top left", "Top middle", "Top right"],
["Middle left", "Center", "Middle right"],
["Bottom left", "Bottom middle", "Bottom right"],
];
for (row, labels) in labels.into_iter().enumerate() {
ui.horizontal(|ui| {
for (column, label) in labels.into_iter().enumerate() {
let (_, rect) = ui.allocate_space(Vec2::new(48.0, 38.0));
let response = ui.interact(
rect,
egui::Id::new(("quarter-position", column, row)),
egui::Sense::click(),
);
let p = theme::palette(ui.ctx());
let screen = rect.shrink(5.0);
ui.painter().rect_stroke(
screen,
1.0,
Stroke::new(1.0, p.text),
StrokeKind::Inside,
);
let quarter = Rect::from_min_size(
screen.min
+ Vec2::new(
column as f32 * screen.width() / 4.0,
row as f32 * screen.height() / 4.0,
),
screen.size() / 2.0,
);
ui.painter().rect_filled(
quarter,
0.0,
if response.hovered() { p.amber } else { p.cyan },
);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, label)
});
if response.on_hover_text(label).clicked() {
self.apply_size_preset(SizePreset::Quarter {
column: column as u8,
row: row as u8,
});
egui::Popup::close_all(ui.ctx());
}
}
});
}
} else {
if count == 2 {
for (label, columns, rows) in [("Up / Down", 1, 2), ("Left / Right", 2, 1)] {
if ui.button(label).clicked() {
self.apply_size_preset(SizePreset::Tiles { columns, rows });
egui::Popup::close_all(ui.ctx());
}
}
}
if count >= 3 && ui.button("Four quarters").clicked() {
self.apply_size_preset(SizePreset::Tiles {
columns: 2,
rows: 2,
});
egui::Popup::close_all(ui.ctx());
}
if count > 4 {
ui.weak("After the fourth layer, quarter positions repeat.");
}
ui.weak("Layer-list order: left to right, then top to bottom.");
}
}
fn tiling_presets_menu(&mut self, ui: &mut egui::Ui) {
ui.label(tr(ui.ctx(), "preset.tiling"));
egui::Grid::new("tiling-dimensions")
.spacing([16.0, 6.0])
.show(ui, |ui| {
for (axis, label) in ["X (columns)", "Y (rows)"].into_iter().enumerate() {
ui.label(label);
ui.scope(|ui| {
ui.visuals_mut().widgets.inactive.bg_stroke =
Stroke::new(1.0, theme::palette(ui.ctx()).line);
ui.add_sized(
[72.0, 24.0],
egui::DragValue::new(&mut self.size_tiles[axis]).range(1..=256),
);
});
ui.end_row();
}
});
let count = self.layout.selected_indices().len();
let [columns, rows] = self.size_tiles;
ui.label(format!(
"{count} selected layers · {} cells",
u32::from(columns) * u32::from(rows)
));
ui.weak("Layer-list order: left to right, then top to bottom.");
if count > usize::from(columns) * usize::from(rows) {
ui.weak("More layers than cells: positions repeat and layers overlap.");
}
if ui
.add_enabled(
self.size_presets_enabled(),
egui::Button::new("Apply tiling"),
)
.clicked()
{
self.apply_size_preset(SizePreset::Tiles { columns, rows });
egui::Popup::close_all(ui.ctx());
}
}
}
#[cfg(test)]
mod tests {
use super::super::tests::{click_text, frame, mouse};
use super::*;
fn click_id(app: &mut Editor, ctx: &egui::Context, id: egui::Id) {
frame(app, ctx, vec![]);
frame(app, ctx, vec![]);
let point = ctx.read_response(id).unwrap().rect.center();
frame(
app,
ctx,
vec![egui::Event::PointerMoved(point), mouse(point, true)],
);
frame(app, ctx, vec![mouse(point, false)]);
}
fn icon(app: &mut Editor, ctx: &egui::Context, key: &str) {
click_id(app, ctx, egui::Id::new("size-presets"));
if app.size_presets_enabled() {
let label = tr(ctx, key);
let output = frame(app, ctx, vec![]);
let expanded = output
.shapes
.iter()
.filter(|shape| {
matches!(&shape.shape,
egui::Shape::Text(text) if text.galley.text() == label)
})
.count()
> 1;
if !expanded {
click_text(app, ctx, &label);
}
}
}
#[test]
fn icon_box_applies_single_quarter_fullscreen_and_orientation() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.select(Some(1));
app.sync();
icon(&mut app, &ctx, "preset.quarter");
click_id(
&mut app,
&ctx,
egui::Id::new(("quarter-position", 2_usize, 2_usize)),
);
assert_eq!(
app.layout.layers()[1],
Geometry {
x: 960.0,
y: 540.0,
width: 960.0,
height: 540.0
}
);
icon(&mut app, &ctx, "preset.portrait");
assert_eq!(
app.layout.layers()[1],
Geometry {
x: 960.0,
y: 540.0,
width: 540.0,
height: 960.0
}
);
icon(&mut app, &ctx, "preset.landscape");
assert_eq!(app.layout.layers()[1].width, 960.0);
icon(&mut app, &ctx, "preset.fullscreen");
assert_eq!(
app.layout.layers()[1],
Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 1080.0
}
);
app.layout.undo();
assert_eq!(app.layout.layers()[1].x, 960.0);
}
#[test]
fn multi_selection_submenu_changes_with_count_and_tiling_uses_requested_grid() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.set_selection([true, true]);
app.sync();
icon(&mut app, &ctx, "preset.quarter");
let output = frame(&mut app, &ctx, vec![]);
assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "Four quarters")));
click_text(&mut app, &ctx, "Left / Right");
assert_eq!(app.layout.layers()[1].width, 960.0);
assert_eq!(app.layout.layers()[0].x, 960.0);
for _ in 0..3 {
app.layout.add_layer().unwrap();
}
app.layout.set_selection([true; 5]);
app.sync();
icon(&mut app, &ctx, "preset.quarter");
let output = frame(&mut app, &ctx, vec![]);
assert!(!output.shapes.iter().any(|shape| matches!(&shape.shape, egui::Shape::Text(text) if text.galley.text() == "Left / Right")));
click_text(&mut app, &ctx, "Four quarters");
assert_eq!(app.layout.layers()[0], app.layout.layers()[4]);
app.size_tiles = [3, 2];
icon(&mut app, &ctx, "preset.tiling");
click_text(&mut app, &ctx, "Apply tiling");
assert_eq!(app.layout.layers()[4].width, 640.0);
assert_eq!(app.layout.layers()[4].height, 540.0);
assert_eq!(app.layout.layers()[0].x, 640.0);
assert_eq!(app.layout.layers()[0].y, 540.0);
}
#[test]
fn proportions_toggle_fits_halves_and_is_shared_with_fullscreen() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.set_selection([true, true]);
app.sync();
let original = app.layout.layers().clone();
click_id(&mut app, &ctx, egui::Id::new("size-presets"));
click_text(&mut app, &ctx, "Keep proportions");
assert!(app.size_keep_proportions);
click_text(&mut app, &ctx, "Quarter");
click_text(&mut app, &ctx, "Left / Right");
for (i, g) in app.layout.layers().iter().enumerate() {
assert!((g.width / g.height - original[i].width / original[i].height).abs() < 1e-8);
assert!(g.width <= 960.0 && g.height <= 1080.0);
assert!((g.y + g.height / 2.0 - 540.0).abs() < 1e-8);
}
icon(&mut app, &ctx, "preset.fullscreen");
assert!(app.size_keep_proportions);
for (i, g) in app.layout.layers().iter().enumerate() {
assert!((g.width / g.height - original[i].width / original[i].height).abs() < 1e-8);
}
}
#[test]
fn empty_selection_and_pending_numeric_values_disable_presets() {
let ctx = egui::Context::default();
let mut app = Editor::default();
app.layout.select(None);
app.sync();
let before = app.project();
icon(&mut app, &ctx, "preset.fullscreen");
assert_eq!(app.project(), before);
app.layout.select(Some(1));
app.sync();
app.fields[0] = "-".into();
app.fields_edited = true;
let before = app.project();
app.apply_size_preset(SizePreset::Fullscreen);
assert_eq!(app.project(), before);
assert_eq!(app.fields[0], "-");
}
}

View File

@ -1,11 +1,21 @@
//! Proximity snapping for layer movement and anchored single/group resizing.
use crate::{Geometry, Layout, ResizeHandle, ResizeMode};
// Favor integer screen coordinates without turning the pixel option into a hard grid.
// A quarter-pixel capture zone leaves an equally wide free zone around half pixels.
const PIXEL_MAGNET_RADIUS: f64 = 0.25;
fn pixel_magnet(value: f64) -> Option<f64> {
let target = value.round();
((target - value).abs() <= PIXEL_MAGNET_RADIUS).then_some(target)
}
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Snapping {
pub enabled: bool,
pub pixels: bool,
pub force_pixels: bool,
pub screen_edges: bool,
pub layer_edges: bool,
pub mask_edges: bool,
@ -18,6 +28,7 @@ impl Default for Snapping {
Self {
enabled: false,
pixels: true,
force_pixels: false,
screen_edges: true,
layer_edges: true,
mask_edges: false,
@ -94,10 +105,14 @@ impl Snapping {
.mask_edges
.then(|| mask_geometry(formats, index, g))
.flatten();
[self.layer_edges.then_some(g), mask]
self.layer_edges
.then_some(g)
.into_iter()
.flatten()
.flat_map(move |g| edges(g, axis))
.chain(mask.into_iter().flat_map(move |g| {
let [low, high] = edges(g, axis);
[low, high, g.center()[axis]]
}))
}
}
@ -138,6 +153,9 @@ impl Layout {
if !options.enabled {
return (point, [None; 2]);
}
if options.force_pixels {
return (point.map(f64::round), [None; 2]);
}
let mut target = point;
let mut guides = [None; 2];
for axis in 0..2 {
@ -162,8 +180,10 @@ impl Layout {
{
target[axis] = edge;
guides[axis] = Some(edge);
} else if options.pixels {
target[axis] = point[axis].round();
} else if options.pixels
&& let Some(pixel) = pixel_magnet(point[axis])
{
target[axis] = pixel;
}
}
(target, guides)
@ -201,6 +221,13 @@ impl Layout {
}
};
for axis in 0..2 {
if options.force_pixels {
if let Some(i) = selected.iter().position(|v| *v) {
let coordinate = edge(before.layers[i], axis)[0] + delta[axis];
delta[axis] += coordinate.round() - coordinate;
}
continue;
}
let mut targets = Vec::new();
if options.screen_edges {
targets.extend(screen_guides(self.formats.output[axis]));
@ -211,10 +238,16 @@ impl Layout {
Vec::new()
};
targets.extend(grid_targets.iter().copied());
let mut mask_centers = Vec::new();
if options.layer_edges || options.mask_edges {
for (i, g) in before.layers.iter().enumerate() {
if !selected[i] && self.visible[i] {
targets.extend(options.targets(&before.formats, i, *g, axis));
if options.mask_edges
&& let Some(mask) = mask_geometry(&before.formats, i, *g)
{
mask_centers.push(mask.center()[axis]);
}
}
}
}
@ -227,19 +260,24 @@ impl Layout {
.mask_edges
.then(|| mask_geometry(&before.formats, i, *g))
.flatten();
for (is_center, moving) in edge(*g, axis)
for (is_center, moving) in options
.layer_edges
.then_some(*g)
.into_iter()
.flat_map(|g| edge(g, axis))
.chain(mask.into_iter().flat_map(|g| edge(g, axis)))
.map(|v| (false, v))
.chain(std::iter::once((true, g.center()[axis])))
.chain(mask.map(|g| (true, g.center()[axis])))
{
for target in &targets {
// Centers align to screen interior guides and overlay grid lines;
// other targets retain edge-to-edge behavior.
// Centers align to screen interior/grid lines and visible mask
// centers; existing layer-edge behavior stays unchanged.
if is_center
&& (!options.screen_edges
|| !screen_guides(self.formats.output[axis])[1..4].contains(target))
&& !grid_targets.contains(target)
&& !mask_centers.contains(target)
{
continue;
}
@ -259,7 +297,9 @@ impl Layout {
&& let Some(i) = selected.iter().position(|v| *v)
{
let coordinate = edge(before.layers[i], axis)[0] + delta[axis];
delta[axis] += coordinate.round() - coordinate;
if let Some(pixel) = pixel_magnet(coordinate) {
delta[axis] += pixel - coordinate;
}
}
}
let mut next = before.layers;
@ -333,7 +373,9 @@ impl Layout {
grid: Option<f64>,
) -> [Option<f64>; 2] {
let r = self.resize.clone().expect("resize gesture");
self.drag_to_with_precision(point, grid.is_some());
// Pixel-edge snapping needs the precise pointer result so its small magnetic
// zone can favor integers without making fractional resizing unreachable.
self.drag_to_with_precision(point, grid.is_some() || options.pixels);
if self.gesture_error.is_some() || point.iter().any(|v| !v.is_finite()) {
return [None; 2];
}
@ -387,18 +429,22 @@ impl Layout {
}
}
}
if let Some(target) = targets
.into_iter()
.filter(|t| (*t - current[axis]).abs() <= tolerance)
.min_by(|a, b| {
(a - current[axis])
.abs()
.total_cmp(&(b - current[axis]).abs())
})
if !options.force_pixels
&& let Some(target) = targets
.into_iter()
.filter(|t| (*t - current[axis]).abs() <= tolerance)
.min_by(|a, b| {
(a - current[axis])
.abs()
.total_cmp(&(b - current[axis]).abs())
})
{
candidates.push((1, (target - current[axis]).abs(), axis, target, None));
}
if options.layer_edges && matches!(r.mode, ResizeMode::Mirror | ResizeMode::Opposite) {
if !options.force_pixels
&& options.layer_edges
&& matches!(r.mode, ResizeMode::Mirror | ResizeMode::Opposite)
{
let original = r.before.layers[r.index];
let moving = handle_point(original)[axis];
let anchor = r.anchor(r.index)[axis];
@ -434,10 +480,13 @@ impl Layout {
}
}
}
if options.pixels {
if options.pixels || options.force_pixels {
let spacing = grid.unwrap_or(1.0);
let target = (current[axis] / spacing).round() * spacing;
candidates.push((2, (target - current[axis]).abs(), axis, target, None));
if grid.is_some() || options.force_pixels || pixel_magnet(current[axis]).is_some() {
let priority = if options.force_pixels { 0 } else { 2 };
candidates.push((priority, (target - current[axis]).abs(), axis, target, None));
}
}
}
candidates.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
@ -485,6 +534,26 @@ impl Layout {
&& touching
&& (handle_point(self.layers[r.index])[axis] - target).abs() < 1e-6
{
if options.force_pixels {
let mut rounded = self.layers.clone();
for (i, geometry) in rounded.iter_mut().enumerate() {
if !r.targets[i] {
continue;
}
let right = (geometry.x + geometry.width).round();
let bottom = (geometry.y + geometry.height).round();
geometry.x = geometry.x.round();
geometry.y = geometry.y.round();
geometry.width = right - geometry.x;
geometry.height = bottom - geometry.y;
}
if rounded.iter().all(|geometry| geometry.validate().is_ok()) {
self.layers = rounded;
} else {
self.restore(base.clone());
continue;
}
}
let mut guides = [None; 2];
if priority < 2 || grid.is_some() {
guides[axis] = Some(target);
@ -496,3 +565,75 @@ impl Layout {
[None; 2]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn pixels_only() -> Snapping {
Snapping {
enabled: true,
pixels: true,
screen_edges: false,
layer_edges: false,
mask_edges: false,
grid: false,
..Default::default()
}
}
#[test]
fn pixel_edges_are_magnetic_without_forbidding_fractional_resizes() {
let mut layout = Layout::default();
layout.start_handle_resize(1, ResizeHandle::Right, [1800.0, 360.0], false);
layout.drag_to_snapped([1800.2, 360.0], pixels_only(), 6.0);
assert_eq!(layout.layers()[1].x + layout.layers()[1].width, 1800.0);
layout.drag_to_snapped([1800.4, 360.0], pixels_only(), 6.0);
assert!((layout.layers()[1].x + layout.layers()[1].width - 1800.4).abs() < 1e-9);
}
#[test]
fn forced_pixels_round_moves_and_resize_handles_outside_the_soft_magnet() {
let options = Snapping {
enabled: true,
force_pixels: true,
screen_edges: false,
layer_edges: false,
..Default::default()
};
let mut layout = Layout::default();
layout.start_drag([1160.0, 180.0]);
layout.drag_to_snapped([1163.6, 184.4], options, 6.0);
assert_eq!(
[layout.layers()[1].x, layout.layers()[1].y],
[1164.0, 184.0]
);
layout.finish_drag();
layout.start_handle_resize(1, ResizeHandle::Right, [1804.0, 364.0], false);
layout.drag_to_snapped([1804.6, 364.0], options, 6.0);
assert_eq!(layout.layers()[1].x + layout.layers()[1].width, 1805.0);
let mut ratio_layout = Layout::default();
let original_ratio = ratio_layout.layers()[1].width / ratio_layout.layers()[1].height;
ratio_layout.start_handle_resize(
1,
ResizeHandle::Corner(crate::Corner::BottomRight),
[1800.0, 540.0],
true,
);
ratio_layout.drag_to_snapped([1801.4, 540.8], options, 6.0);
let resized = ratio_layout.layers()[1];
for edge in [
resized.x,
resized.y,
resized.x + resized.width,
resized.y + resized.height,
] {
assert_eq!(edge.fract(), 0.0);
}
assert!((resized.width / resized.height - original_ratio).abs() > 1e-9);
}
}

View File

@ -0,0 +1,312 @@
//! Startup snapshot of optional local software. Detection never launches applications.
use std::{
path::{Path, PathBuf},
sync::OnceLock,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Software {
LibreOffice,
Drawio,
VectorCraft,
}
impl Software {
pub const ALL: [Self; 3] = [Self::LibreOffice, Self::Drawio, Self::VectorCraft];
pub fn name(self) -> &'static str {
match self {
Self::LibreOffice => "LibreOffice",
Self::Drawio => "draw.io Desktop",
Self::VectorCraft => "VectorCraft CLI",
}
}
pub fn environment(self) -> &'static str {
match self {
Self::LibreOffice => "CANVAS_PILOT_LIBREOFFICE",
Self::Drawio => "CANVAS_PILOT_DRAWIO",
Self::VectorCraft => "MIDRA_VECTORCRAFT_CLI",
}
}
pub fn functionality(self) -> &'static str {
match self {
Self::LibreOffice => {
"Render PowerPoint slides as reference pictures. PPTX geometry import/export and layout-box references work without it."
}
Self::Drawio => {
"Render complete draw.io pages as reference pictures. Diagram geometry import/export and layout-box references work without it."
}
Self::VectorCraft => {
"Import and export Illustrator files, and render Illustrator artboards as reference pictures."
}
}
}
fn names(self) -> &'static [&'static str] {
match (self, cfg!(windows)) {
(Self::LibreOffice, true) => &["soffice.exe"],
(Self::LibreOffice, false) => &["libreoffice", "soffice"],
(Self::Drawio, true) => &["draw.io.exe"],
(Self::Drawio, false) => &["drawio", "draw.io"],
(Self::VectorCraft, true) => &["vectorcraft-cli.exe"],
(Self::VectorCraft, false) => &["vectorcraft-cli"],
}
}
fn enabled(self) -> bool {
self == Self::Drawio
|| cfg!(all(
feature = "vendor_formats",
not(feature = "no_proprietary")
))
}
pub fn integration(self) -> &'static Integration {
detected()
.iter()
.find(|i| i.software == self)
.expect("all integrations are detected")
}
pub fn executable(self) -> Result<&'static Path, String> {
let integration = self.integration();
if !integration.enabled {
return Err(format!(
"{} integration is disabled in this build.",
self.name()
));
}
integration.path.as_deref().ok_or_else(|| format!("{} was not found at startup. See Software integrations for setup, then restart Canvas Pilot.", self.name()))
}
}
#[derive(Clone, Debug)]
pub struct Integration {
pub software: Software,
pub path: Option<PathBuf>,
pub overridden: bool,
pub enabled: bool,
}
impl Integration {
pub fn available(&self) -> bool {
self.enabled && self.path.is_some()
}
pub fn status(&self) -> &'static str {
if !self.enabled {
"Disabled in this build"
} else if self.path.is_some() {
"Detected"
} else if self.overridden {
"Configured executable not found or not executable"
} else {
"Not found"
}
}
}
pub fn detected() -> &'static [Integration] {
static DETECTED: OnceLock<Vec<Integration>> = OnceLock::new();
DETECTED.get_or_init(|| {
Software::ALL
.into_iter()
.map(|software| {
let configured = std::env::var_os(software.environment()).map(PathBuf::from);
let mut directories = Vec::new();
if let Ok(exe) = std::env::current_exe()
&& let Some(parent) = exe.parent()
{
directories.extend([parent.to_owned(), parent.join("bin")]);
}
if let Some(path) = std::env::var_os("PATH") {
directories.extend(std::env::split_paths(&path));
}
directories.extend(installation_directories(software));
Integration {
software,
path: resolve(configured.as_deref(), software.names(), &directories),
overridden: configured.is_some(),
enabled: software.enabled(),
}
})
.collect()
})
}
fn executable_file(path: &Path) -> bool {
let Ok(metadata) = path.metadata() else {
return false;
};
if !metadata.is_file() {
return false;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
metadata.permissions().mode() & 0o111 != 0
}
#[cfg(not(unix))]
{
true
}
}
fn resolve(configured: Option<&Path>, names: &[&str], directories: &[PathBuf]) -> Option<PathBuf> {
let candidates: Vec<_> = if let Some(path) = configured {
if path.components().count() > 1 || path.is_absolute() {
vec![path.to_owned()]
} else {
directories.iter().map(|dir| dir.join(path)).collect()
}
} else {
directories
.iter()
.flat_map(|dir| names.iter().map(move |name| dir.join(name)))
.collect()
};
candidates
.into_iter()
.find(|p| executable_file(p))
.and_then(|p| std::path::absolute(p).ok())
}
fn installation_directories(software: Software) -> Vec<PathBuf> {
let mut dirs = Vec::new();
if cfg!(target_os = "macos") {
let suffix = match software {
Software::LibreOffice => "LibreOffice.app/Contents/MacOS",
Software::Drawio => "draw.io.app/Contents/MacOS",
Software::VectorCraft => "VectorCraft.app/Contents/MacOS",
};
dirs.push(Path::new("/Applications").join(suffix));
if let Some(home) = std::env::var_os("HOME") {
dirs.push(PathBuf::from(home).join("Applications").join(suffix));
}
}
if cfg!(windows) {
let suffix = match software {
Software::LibreOffice => "LibreOffice/program",
Software::Drawio => "draw.io",
Software::VectorCraft => "VectorCraft",
};
for variable in ["ProgramFiles", "ProgramFiles(x86)"] {
if let Some(root) = std::env::var_os(variable) {
dirs.push(PathBuf::from(root).join(suffix));
}
}
if let Some(root) = std::env::var_os("LOCALAPPDATA") {
dirs.push(PathBuf::from(root).join("Programs").join(suffix));
}
}
dirs
}
/// UI choices: compiled codecs whose required external converter was detected.
pub fn codecs() -> Vec<crate::interchange::Codec> {
crate::interchange::Codec::available()
.into_iter()
.filter(|c| {
*c != crate::interchange::Codec::Illustrator
|| Software::VectorCraft.integration().available()
})
.collect()
}
pub fn geometry_extensions() -> Vec<&'static str> {
let mut extensions: Vec<_> = codecs().into_iter().map(|c| c.extension()).collect();
extensions.push("xml");
extensions
}
pub fn artwork_available(path: &Path) -> bool {
let ext = path
.extension()
.and_then(|s| s.to_str())
.unwrap_or("")
.to_ascii_lowercase();
match ext.as_str() {
"pptx" => Software::LibreOffice.integration().available(),
"drawio" | "xml" => Software::Drawio.integration().available(),
"ai" => Software::VectorCraft.integration().available(),
"csv" | "dxf" | "dwg" => false,
_ => true,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn executable(path: &Path) {
std::fs::write(path, b"not launched by discovery").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
}
#[test]
fn startup_resolution_obeys_override_and_directory_priority() {
let temp = tempfile::tempdir().unwrap();
let app = temp.path().join("app");
let bin = app.join("bin");
let path = temp.path().join("path with spaces");
std::fs::create_dir_all(&bin).unwrap();
std::fs::create_dir_all(&path).unwrap();
let dirs = [app.clone(), bin.clone(), path.clone()];
executable(&path.join("tool"));
assert_eq!(resolve(None, &["tool"], &dirs), Some(path.join("tool")));
executable(&bin.join("tool"));
assert_eq!(resolve(None, &["tool"], &dirs), Some(bin.join("tool")));
executable(&app.join("tool"));
assert_eq!(resolve(None, &["tool"], &dirs), Some(app.join("tool")));
assert_eq!(
resolve(Some(&path.join("tool")), &["tool"], &dirs),
Some(path.join("tool"))
);
assert!(resolve(Some(&path.join("missing")), &["tool"], &dirs).is_none());
assert_eq!(
resolve(Some(Path::new("tool")), &["ignored"], &dirs),
Some(app.join("tool"))
);
assert!(
resolve(None, &["bin"], &dirs).is_none(),
"directories are not executables"
);
#[cfg(unix)]
{
std::fs::write(app.join("plain"), b"not executable").unwrap();
assert!(resolve(None, &["plain"], &dirs).is_none());
}
}
#[test]
fn integration_states_and_ui_choices_match_detected_capabilities() {
for software in Software::ALL {
let mut integration = Integration {
software,
path: None,
overridden: false,
enabled: true,
};
assert_eq!(integration.status(), "Not found");
assert!(!integration.available());
integration.overridden = true;
assert!(integration.status().starts_with("Configured"));
integration.path = Some("tool".into());
assert!(integration.available());
integration.enabled = false;
assert!(!integration.available());
assert_eq!(integration.status(), "Disabled in this build");
assert!(!software.functionality().is_empty());
assert_eq!(
software.executable().is_ok(),
software.integration().available()
);
}
assert_eq!(
codecs().contains(&crate::interchange::Codec::Illustrator),
Software::VectorCraft.integration().available()
);
assert_eq!(
artwork_available(Path::new("slides.PPTX")),
Software::LibreOffice.integration().available()
);
assert_eq!(
artwork_available(Path::new("diagram.xml")),
Software::Drawio.integration().available()
);
assert!(!artwork_available(Path::new("layout.csv")));
assert!(artwork_available(Path::new("client.pdf")));
}
}

View File

@ -1,7 +1,7 @@
//! Application palettes adapted from SOTV's song database; see docs/canvas-pilot/README.md.
use super::*;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Theme {
#[default]
@ -25,6 +25,7 @@ pub enum Theme {
Ustf,
VerdantRebel,
WeicatIndustrial,
Pack(String),
}
#[derive(Clone, Copy)]
@ -68,8 +69,9 @@ impl Theme {
Self::VerdantRebel,
Self::WeicatIndustrial,
];
pub fn name(self) -> &'static str {
pub fn name(&self) -> &str {
match self {
Self::Pack(id) => id,
Self::Midra => "Midra Dark",
Self::HighContrast => "High Contrast",
Self::FoxifiedDark => "Foxified Dark",
@ -92,7 +94,7 @@ impl Theme {
Self::WeicatIndustrial => "Weicat Industrial",
}
}
pub fn is_light(self) -> bool {
pub fn is_light(&self) -> bool {
matches!(
self,
Self::CorporateLight
@ -102,6 +104,39 @@ impl Theme {
| Self::Solarized
)
}
pub fn display_name(&self, ctx: &egui::Context) -> String {
match self {
Self::Pack(id) => crate::theme_packs::find(ctx, id)
.map_or_else(|| format!("{id} (unavailable)"), |t| t.name),
_ => self.name().to_owned(),
}
}
pub fn available(&self, ctx: &egui::Context) -> bool {
match self {
Self::Pack(id) => crate::theme_packs::find(ctx, id).is_some(),
_ => true,
}
}
pub fn resolved_palette(&self, ctx: &egui::Context) -> Palette {
match self {
Self::Pack(id) => crate::theme_packs::find(ctx, id)
.and_then(|t| t.colors.palette().ok())
.unwrap_or_else(|| Self::Midra.palette()),
_ => self.palette(),
}
}
pub fn resolved_light(&self, ctx: &egui::Context) -> bool {
match self {
Self::Pack(id) => crate::theme_packs::find(ctx, id).is_some_and(|t| t.light),
_ => self.is_light(),
}
}
pub fn choices(ctx: &egui::Context) -> Vec<Self> {
Self::ALL
.into_iter()
.chain(crate::theme_packs::choices(ctx))
.collect()
}
pub fn recent(ctx: &egui::Context) -> Vec<Self> {
ctx.data(|d| d.get_temp(egui::Id::new("recent-themes")))
.unwrap_or_else(|| vec![Self::current(ctx)])
@ -115,9 +150,10 @@ impl Theme {
.unwrap_or_default()
})
}
pub fn palette(self) -> Palette {
pub fn palette(&self) -> Palette {
let rgb = |hex: u32| Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8);
match self {
Self::Pack(_) => Self::Midra.palette(),
Self::HighContrast => Palette {
canvas: rgb(0x000000),
banner: rgb(0x101010),
@ -280,14 +316,27 @@ impl Theme {
},
}
}
pub fn apply(self, ctx: &egui::Context) {
/// Apply a user choice; selecting active High Contrast restores the previous theme.
pub fn select(&self, ctx: &egui::Context) {
let choice = if *self == Self::HighContrast && Self::current(ctx) == *self {
Self::recent(ctx)
.into_iter()
.find(|theme| *theme != Self::HighContrast)
.unwrap_or_default()
} else {
self.clone()
};
choice.apply(ctx);
}
pub fn apply(&self, ctx: &egui::Context) {
let mut recent = Self::recent(ctx);
recent.retain(|theme| *theme != self);
recent.insert(0, self);
recent.retain(|theme| theme != self);
recent.insert(0, self.clone());
recent.truncate(3);
Self::restore_recent(ctx, recent);
let p = self.palette();
let mut v = if self.is_light() {
let p = self.resolved_palette(ctx);
let mut v = if self.resolved_light(ctx) {
egui::Visuals::light()
} else {
egui::Visuals::dark()
@ -301,7 +350,7 @@ impl Theme {
v.code_bg_color = p.field;
v.hyperlink_color = p.cyan;
v.warn_fg_color = p.amber;
v.error_fg_color = if self.is_light() {
v.error_fg_color = if self.resolved_light(ctx) {
Color32::from_rgb(165, 30, 40)
} else {
Color32::LIGHT_RED
@ -322,7 +371,7 @@ impl Theme {
widget.bg_stroke = Stroke::new(1.0_f32, border);
widget.fg_stroke = Stroke::new(1.0_f32, p.text);
}
if self == Self::HighContrast {
if *self == Self::HighContrast {
v.window_stroke.width = 2.0;
for widget in [
&mut v.widgets.noninteractive,
@ -336,13 +385,15 @@ impl Theme {
}
}
ctx.set_visuals(v);
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-theme"), self));
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-palette"), p));
ctx.data_mut(|d| d.insert_temp(egui::Id::new("application-theme"), self.clone()));
ctx.request_repaint();
}
}
pub fn palette(ctx: &egui::Context) -> Palette {
Theme::current(ctx).palette()
ctx.data(|d| d.get_temp::<Palette>(egui::Id::new("application-palette")))
.unwrap_or_else(|| Theme::current(ctx).resolved_palette(ctx))
}
// SOTV CSS tokens: body, panel, sidebar, tab, main/subtle text, button, border.
@ -416,7 +467,7 @@ mod tests {
fn selectable_hover_focus_and_selection_keep_rows_and_neighbors_stationary() {
for (theme, menu) in Theme::ALL
.into_iter()
.flat_map(|theme| [(theme, false), (theme, true)])
.flat_map(|theme| [(theme.clone(), false), (theme, true)])
{
let ctx = egui::Context::default();
theme.apply(&ctx);

View File

@ -0,0 +1,631 @@
//! Runtime palette packs. Contract: docs/interfaces/theme-packs.md.
use crate::theme::Palette;
use eframe::egui;
use serde::{Deserialize, Serialize};
use std::{
collections::BTreeSet,
io::{Read, Write},
path::{Path, PathBuf},
};
const MAX_ARCHIVE: u64 = 2 * 1024 * 1024;
const MAX_EXPANDED: u64 = 4 * 1024 * 1024;
const MAX_PACKS: usize = 32;
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct Manifest {
version: u32,
id: String,
revision: u64,
themes: Vec<Description>,
/// Attribution and license notices travel with the pack.
#[serde(default)]
notices: String,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Description {
pub id: String,
pub name: String,
pub light: bool,
pub colors: Colors,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Colors {
pub canvas: String,
pub banner: String,
pub grid: String,
pub layer: String,
pub bg: String,
pub panel: String,
pub field: String,
pub line: String,
pub text: String,
pub muted: String,
pub cyan: String,
pub amber: String,
pub purple: String,
pub pattern: [String; 2],
}
fn color(text: &str) -> Result<egui::Color32, String> {
if text.len() != 7
|| !text.starts_with('#')
|| !text[1..].bytes().all(|b| b.is_ascii_hexdigit())
{
return Err(format!("Expected opaque #RRGGBB color: {text}"));
}
let value = u32::from_str_radix(&text[1..], 16).map_err(|e| e.to_string())?;
Ok(egui::Color32::from_rgb(
(value >> 16) as u8,
(value >> 8) as u8,
value as u8,
))
}
impl Colors {
pub fn palette(&self) -> Result<Palette, String> {
Ok(Palette {
canvas: color(&self.canvas)?,
banner: color(&self.banner)?,
grid: color(&self.grid)?,
layer: color(&self.layer)?,
bg: color(&self.bg)?,
panel: color(&self.panel)?,
field: color(&self.field)?,
line: color(&self.line)?,
text: color(&self.text)?,
muted: color(&self.muted)?,
cyan: color(&self.cyan)?,
amber: color(&self.amber)?,
purple: color(&self.purple)?,
pattern: [color(&self.pattern[0])?, color(&self.pattern[1])?],
})
}
}
#[derive(Clone)]
struct Pack {
manifest: Manifest,
}
#[derive(Clone, Debug)]
pub struct Installed {
pub id: String,
pub revision: u64,
pub themes: Vec<Description>,
pub notices: String,
path: PathBuf,
bytes: std::sync::Arc<[u8]>,
}
pub fn installed(ctx: &egui::Context) -> Vec<Installed> {
ctx.data(|data| data.get_temp::<Vec<Installed>>(egui::Id::new("theme-packs")))
.unwrap_or_default()
}
pub fn valid_choice(id: &str) -> bool {
id.split_once('/').is_some_and(|(pack, theme)| {
crate::language_packs::valid_id(pack) && crate::language_packs::valid_id(theme)
})
}
pub fn find(ctx: &egui::Context, id: &str) -> Option<Description> {
let (pack, theme) = id.split_once('/')?;
installed(ctx)
.into_iter()
.find(|p| p.id == pack)?
.themes
.into_iter()
.find(|t| t.id == theme)
}
pub fn choices(ctx: &egui::Context) -> Vec<crate::theme::Theme> {
installed(ctx)
.into_iter()
.flat_map(|p| {
p.themes
.into_iter()
.map(move |t| crate::theme::Theme::Pack(format!("{}/{}", p.id, t.id)))
})
.collect()
}
fn register(ctx: &egui::Context, pack: &Pack, path: &Path, bytes: &[u8]) {
let mut packs = installed(ctx);
packs.retain(|p| p.id != pack.manifest.id);
packs.push(Installed {
id: pack.manifest.id.clone(),
revision: pack.manifest.revision,
themes: pack.manifest.themes.clone(),
notices: pack.manifest.notices.clone(),
path: path.into(),
bytes: bytes.into(),
});
packs.sort_by(|a, b| a.id.cmp(&b.id));
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), packs));
}
fn parse(bytes: &[u8]) -> Result<Pack, String> {
if bytes.len() as u64 > MAX_ARCHIVE {
return Err("Theme pack exceeds 2 MiB".into());
}
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes)).map_err(|e| e.to_string())?;
if zip.len() != 1 {
return Err("Expected only manifest.json in the theme pack".into());
}
let mut entry = zip.by_index(0).map_err(|e| e.to_string())?;
if entry.name() != "manifest.json"
|| entry.is_dir()
|| entry
.unix_mode()
.is_some_and(|mode| mode & 0o170000 == 0o120000)
{
return Err("Expected a regular manifest.json at the ZIP root".into());
}
let mut data = Vec::new();
(&mut entry)
.take(MAX_EXPANDED + 1)
.read_to_end(&mut data)
.map_err(|e| e.to_string())?;
if data.len() as u64 > MAX_EXPANDED {
return Err("Expanded theme pack exceeds 4 MiB".into());
}
let manifest: Manifest = serde_json::from_slice(&data).map_err(|e| e.to_string())?;
if manifest.version != 1
|| manifest.revision == 0
|| !crate::language_packs::valid_id(&manifest.id)
|| manifest.themes.is_empty()
|| manifest.themes.len() > 16
{
return Err("Invalid theme-pack manifest or unsupported version".into());
}
if manifest.notices.len() > 65536
|| manifest
.notices
.chars()
.any(|c| c.is_control() && c != '\n' && c != '\t' && c != '\r')
{
return Err("Invalid attribution notices".into());
}
let mut ids = BTreeSet::new();
for theme in &manifest.themes {
if !crate::language_packs::valid_id(&theme.id)
|| !ids.insert(&theme.id)
|| theme.name.trim().is_empty()
|| theme.name.len() > 160
|| theme.name.chars().any(char::is_control)
{
return Err("Invalid or duplicate theme identifier/name".into());
}
theme.colors.palette()?;
}
Ok(Pack { manifest })
}
fn read(path: &Path) -> Result<Vec<u8>, String> {
let mut bytes = Vec::new();
std::fs::File::open(path)
.map_err(|e| e.to_string())?
.take(MAX_ARCHIVE + 1)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
Ok(bytes)
}
fn check_collisions(ctx: &egui::Context, pack: &Pack, replacing: bool) -> Result<(), String> {
if !replacing && installed(ctx).iter().any(|p| p.id == pack.manifest.id) {
return Err("Pack identifier is already installed".into());
}
Ok(())
}
/// Load once at application startup; invalid files do not prevent startup.
pub fn load(ctx: &egui::Context, directory: &Path) -> Vec<String> {
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), Vec::<Installed>::new()));
let entries = match std::fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return vec![],
Err(error) => return vec![error.to_string()],
};
let mut paths = Vec::new();
let mut errors = Vec::new();
for entry in entries {
match entry {
Ok(entry) if entry.path().extension().is_some_and(|ext| ext == "zip") => {
paths.push(entry.path())
}
Ok(_) => (),
Err(error) => errors.push(error.to_string()),
}
if paths.len() > MAX_PACKS {
errors.push("Too many theme packs (maximum 32)".into());
break;
}
}
paths.sort();
for path in paths.into_iter().take(MAX_PACKS) {
let result = read(&path).and_then(|bytes| {
let pack = parse(&bytes)?;
check_collisions(ctx, &pack, false)?;
register(ctx, &pack, &path, &bytes);
Ok(())
});
if let Err(error) = result {
errors.push(format!("{}: {error}", path.display()));
}
}
errors
}
/// Validated bytes and the exact destination reviewed by the user. Never re-read the source on confirmation.
pub struct Prepared {
pack: Pack,
bytes: Vec<u8>,
path: PathBuf,
previous: Option<Vec<u8>>,
pub previous_revision: Option<u64>,
}
impl Prepared {
pub fn id(&self) -> &str {
&self.pack.manifest.id
}
pub fn revision(&self) -> u64 {
self.pack.manifest.revision
}
pub fn needs_confirmation(&self) -> bool {
self.previous.is_some()
&& self
.previous_revision
.is_none_or(|old| self.revision() <= old)
}
}
fn existing_bytes(path: &Path) -> Result<Option<Vec<u8>>, String> {
match read(path) {
Ok(bytes) if bytes.len() as u64 <= MAX_ARCHIVE => Ok(Some(bytes)),
Ok(_) => Err("Existing pack exceeds 2 MiB; remove it manually before replacing it".into()),
Err(_error) if !path.exists() => Ok(None),
Err(error) => Err(error),
}
}
pub fn prepare(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<Prepared, String> {
let bytes = read(source)?;
let pack = parse(&bytes)?;
check_collisions(ctx, &pack, true)?;
let path = installed(ctx)
.into_iter()
.find(|p| p.id == pack.manifest.id)
.map_or_else(
|| directory.join(format!("{}.zip", pack.manifest.id)),
|p| p.path,
);
let previous = existing_bytes(&path)?;
if let Some(old) = previous.as_ref().and_then(|bytes| parse(bytes).ok())
&& old.manifest.id != pack.manifest.id
{
return Err("Destination belongs to a different pack; remove that pack first".into());
}
let previous_revision = previous
.as_ref()
.and_then(|bytes| parse(bytes).ok())
.filter(|old| old.manifest.id == pack.manifest.id)
.map(|old| old.manifest.revision);
Ok(Prepared {
pack,
bytes,
path,
previous,
previous_revision,
})
}
pub fn commit(ctx: &egui::Context, pending: Prepared, overwrite: bool) -> Result<(), String> {
if pending.needs_confirmation() && !overwrite {
return Err("Replacing this pack requires overwrite confirmation".into());
}
check_collisions(ctx, &pending.pack, true)?;
if existing_bytes(&pending.path)? != pending.previous {
return Err("Installed pack changed during review; choose the ZIP again".into());
}
let directory = pending.path.parent().ok_or("Missing pack directory")?;
std::fs::create_dir_all(directory).map_err(|e| e.to_string())?;
if pending.previous.is_none()
&& std::fs::read_dir(directory)
.map_err(|e| e.to_string())?
.filter_map(Result::ok)
.filter(|e| e.path().extension().is_some_and(|ext| ext == "zip"))
.count()
>= MAX_PACKS
{
return Err("Too many theme packs (maximum 32)".into());
}
let mut file = tempfile::NamedTempFile::new_in(directory).map_err(|e| e.to_string())?;
file.write_all(&pending.bytes).map_err(|e| e.to_string())?;
file.as_file().sync_all().map_err(|e| e.to_string())?;
if pending.previous.is_some() {
file.persist(&pending.path).map_err(|e| e.to_string())?;
} else {
file.persist_noclobber(&pending.path)
.map_err(|e| e.to_string())?;
}
register(ctx, &pending.pack, &pending.path, &pending.bytes);
Ok(())
}
pub fn remove(ctx: &egui::Context, pack: &Installed) -> Result<(), String> {
if read(&pack.path)?.as_slice() != pack.bytes.as_ref() {
return Err("Installed pack changed; restart before removing it".into());
}
std::fs::remove_file(&pack.path).map_err(|e| e.to_string())?;
let mut packs = installed(ctx);
packs.retain(|p| p.id != pack.id);
ctx.data_mut(|data| data.insert_temp(egui::Id::new("theme-packs"), packs));
Ok(())
}
#[cfg(test)]
pub fn install(ctx: &egui::Context, directory: &Path, source: &Path) -> Result<(), String> {
commit(ctx, prepare(ctx, directory, source)?, false)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::theme::Theme;
const EXAMPLES: [(&str, &[u8], &str); 5] = [
(
"tokyo-night",
include_bytes!("../../../docs/theme-packs/tokyo-night.zip"),
include_str!("../../../docs/theme-packs/tokyo-night/manifest.json"),
),
(
"catppuccin",
include_bytes!("../../../docs/theme-packs/catppuccin.zip"),
include_str!("../../../docs/theme-packs/catppuccin/manifest.json"),
),
(
"detroit-become-human",
include_bytes!("../../../docs/theme-packs/detroit-become-human.zip"),
include_str!("../../../docs/theme-packs/detroit-become-human/manifest.json"),
),
(
"vivid-world",
include_bytes!("../../../docs/theme-packs/vivid-world.zip"),
include_str!("../../../docs/theme-packs/vivid-world/manifest.json"),
),
(
"ravenswatch",
include_bytes!("../../../docs/theme-packs/ravenswatch.zip"),
include_str!("../../../docs/theme-packs/ravenswatch/manifest.json"),
),
];
fn zip(files: &[(&str, &[u8])]) -> Vec<u8> {
let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
for (name, bytes) in files {
zip.start_file(
*name,
zip::write::SimpleFileOptions::default()
.compression_method(zip::CompressionMethod::Deflated),
)
.unwrap();
zip.write_all(bytes).unwrap();
}
zip.finish().unwrap().into_inner()
}
fn modified(change: impl FnOnce(&mut serde_json::Value)) -> Vec<u8> {
let mut manifest: serde_json::Value = serde_json::from_str(EXAMPLES[0].2).unwrap();
change(&mut manifest);
zip(&[("manifest.json", &serde_json::to_vec(&manifest).unwrap())])
}
#[test]
fn examples_install_restart_preserve_bytes_and_have_legible_text() {
fn luminance(c: egui::Color32) -> f64 {
let channel = |v: u8| {
let v = v as f64 / 255.0;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * channel(c.r()) + 0.7152 * channel(c.g()) + 0.0722 * channel(c.b())
}
let ctx = egui::Context::default();
let dir = tempfile::tempdir().unwrap();
let packs = dir.path().join("packs");
for (id, bytes, source) in EXAMPLES {
let mut archive = zip::ZipArchive::new(std::io::Cursor::new(bytes)).unwrap();
let mut text = String::new();
archive
.by_name("manifest.json")
.unwrap()
.read_to_string(&mut text)
.unwrap();
assert_eq!(text, source);
let path = dir.path().join("source.zip");
std::fs::write(&path, bytes).unwrap();
install(&ctx, &packs, &path).unwrap();
assert_eq!(
std::fs::read(packs.join(format!("{id}.zip"))).unwrap(),
bytes
);
let pack = parse(bytes).unwrap();
for t in pack.manifest.themes {
let choice = Theme::Pack(format!("{id}/{}", t.id));
choice.select(&ctx);
assert_eq!(Theme::current(&ctx), choice);
assert_eq!(choice.display_name(&ctx), t.name);
assert_eq!(ctx.global_style().visuals.dark_mode, !t.light);
let p = choice.resolved_palette(&ctx);
for bg in [p.bg, p.panel, p.field, p.purple, p.pattern[0], p.pattern[1]] {
let (text, bg) = (luminance(p.text), luminance(bg));
assert!(
(text.max(bg) + 0.05) / (text.min(bg) + 0.05) >= 4.5,
"{id} text contrast"
);
}
}
}
assert_eq!(choices(&ctx).len(), EXAMPLES.len());
let restarted = egui::Context::default();
assert!(load(&restarted, &packs).is_empty());
assert_eq!(choices(&restarted), choices(&ctx));
let isolated = egui::Context::default();
assert!(choices(&isolated).is_empty());
let missing = Theme::Pack("ravenswatch/default".into());
missing.apply(&isolated);
assert_eq!(Theme::current(&isolated), missing);
assert_eq!(
missing.resolved_palette(&isolated).bg,
Theme::Midra.palette().bg
);
assert!(missing.display_name(&isolated).contains("unavailable"));
Theme::HighContrast.select(&ctx);
Theme::HighContrast.select(&ctx);
assert_eq!(Theme::current(&ctx), missing);
}
#[test]
fn categorized_collections_coexist_and_survive_restart() {
let collections: [(&str, &[u8]); 2] = [
(
"video-game-themes",
include_bytes!("../../../docs/theme-packs/video-game-themes.zip"),
),
(
"classic-themes",
include_bytes!("../../../docs/theme-packs/classic-themes.zip"),
),
];
let dir = tempfile::tempdir().unwrap();
let packs = dir.path().join("installed");
let ctx = egui::Context::default();
for (id, bytes) in collections {
let source = dir.path().join(format!("{id}.zip"));
std::fs::write(&source, bytes).unwrap();
install(&ctx, &packs, &source).unwrap();
assert_eq!(
std::fs::read(packs.join(format!("{id}.zip"))).unwrap(),
bytes
);
}
assert_eq!(installed(&ctx).len(), 2);
assert_eq!(choices(&ctx).len(), 17);
let restarted = egui::Context::default();
assert!(load(&restarted, &packs).is_empty());
assert_eq!(choices(&ctx), choices(&restarted));
let luminance = |c: egui::Color32| {
let rgb = [c.r(), c.g(), c.b()].map(|v| {
let v = f64::from(v) / 255.0;
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
});
rgb[0] * 0.2126 + rgb[1] * 0.7152 + rgb[2] * 0.0722
};
for (id, bytes) in collections {
for theme in parse(bytes).unwrap().manifest.themes {
let choice = Theme::Pack(format!("{id}/{}", theme.id));
choice.select(&restarted);
assert_eq!(Theme::current(&restarted), choice);
assert_eq!(choice.display_name(&restarted), theme.name);
let p = choice.resolved_palette(&restarted);
for bg in [p.bg, p.panel, p.field, p.purple, p.pattern[0], p.pattern[1]] {
let (fg, bg) = (luminance(p.text), luminance(bg));
assert!(
(fg.max(bg) + 0.05) / (fg.min(bg) + 0.05) >= 4.5,
"{} contrast",
theme.name
);
}
}
}
}
#[test]
fn updates_require_review_and_detect_disk_changes_before_commit_or_remove() {
let dir = tempfile::tempdir().unwrap();
let packs = dir.path().join("packs");
let source = dir.path().join("source.zip");
let ctx = egui::Context::default();
std::fs::write(&source, EXAMPLES[0].1).unwrap();
install(&ctx, &packs, &source).unwrap();
let original = installed(&ctx)[0].clone();
let pending = prepare(&ctx, &packs, &source).unwrap();
assert!(pending.needs_confirmation());
assert!(commit(&ctx, pending, false).is_err());
let updated = modified(|m| {
m["revision"] = 2.into();
m["themes"][0]["colors"]["bg"] = "#112233".into();
});
std::fs::write(&source, &updated).unwrap();
let pending = prepare(&ctx, &packs, &source).unwrap();
assert!(!pending.needs_confirmation());
commit(&ctx, pending, false).unwrap();
assert_eq!(installed(&ctx)[0].revision, 2);
assert!(remove(&ctx, &original).is_err());
std::fs::write(&source, EXAMPLES[0].1).unwrap();
let pending = prepare(&ctx, &packs, &source).unwrap();
assert!(pending.needs_confirmation());
let destination = packs.join("tokyo-night.zip");
std::fs::write(&destination, b"external change").unwrap();
assert!(commit(&ctx, pending, true).is_err());
assert_eq!(installed(&ctx)[0].revision, 2);
assert!(remove(&ctx, &installed(&ctx)[0]).is_err());
std::fs::write(&destination, &updated).unwrap();
commit(&ctx, prepare(&ctx, &packs, &source).unwrap(), true).unwrap();
assert_eq!(installed(&ctx)[0].revision, 1);
remove(&ctx, &installed(&ctx)[0]).unwrap();
assert!(installed(&ctx).is_empty());
assert!(source.exists());
assert!(!destination.exists());
}
#[test]
fn invalid_archives_never_register_or_replace_installed_data() {
let mut cases = vec![
b"not zip".to_vec(),
vec![0; MAX_ARCHIVE as usize + 1],
zip(&[]),
zip(&[("../manifest.json", EXAMPLES[0].2.as_bytes())]),
zip(&[
("manifest.json", EXAMPLES[0].2.as_bytes()),
("extra.json", b"{}"),
]),
zip(&[("manifest.json", &vec![b' '; MAX_EXPANDED as usize + 1])]),
];
for (pointer, value) in [
("/version", serde_json::json!(2)),
("/revision", serde_json::json!(0)),
("/id", serde_json::json!("../escape")),
("/themes/0/id", serde_json::json!("bad/id")),
("/themes/0/name", serde_json::json!("\n")),
("/themes/0/colors/text", serde_json::json!("#ffffff00")),
("/themes/0/colors/bg", serde_json::json!("#gggggg")),
("/themes/0/light", serde_json::json!("dark")),
("/themes", serde_json::json!([])),
] {
cases.push(modified(|m| *m.pointer_mut(pointer).unwrap() = value));
}
cases.push(modified(|m| {
m["unknown"] = true.into();
}));
cases.push(modified(|m| {
let theme = m["themes"][0].clone();
m["themes"].as_array_mut().unwrap().push(theme);
}));
cases.push(modified(|m| {
m["themes"][0]["colors"]
.as_object_mut()
.unwrap()
.remove("line");
}));
let dir = tempfile::tempdir().unwrap();
let source = dir.path().join("source.zip");
let packs = dir.path().join("packs");
let ctx = egui::Context::default();
std::fs::write(&source, EXAMPLES[0].1).unwrap();
install(&ctx, &packs, &source).unwrap();
for bytes in cases {
std::fs::write(&source, bytes).unwrap();
assert!(prepare(&ctx, &packs, &source).is_err());
assert_eq!(installed(&ctx).len(), 1);
assert_eq!(
std::fs::read(packs.join("tokyo-night.zip")).unwrap(),
EXAMPLES[0].1
);
}
std::fs::write(packs.join("bad.zip"), b"bad").unwrap();
std::fs::write(packs.join("duplicate.zip"), EXAMPLES[0].1).unwrap();
assert_eq!(load(&ctx, &packs).len(), 2);
assert_eq!(installed(&ctx).len(), 1);
for i in 0..32 {
std::fs::write(packs.join(format!("invalid-{i}.zip")), b"bad").unwrap();
}
assert!(load(&ctx, &packs).iter().any(|e| e.contains("maximum 32")));
}
}

View File

@ -407,31 +407,14 @@ fn collect_fig(
Ok(())
}
fn vectorcraft() -> std::path::PathBuf {
if let Some(path) = std::env::var_os("MIDRA_VECTORCRAFT_CLI") {
return path.into();
}
let name = if cfg!(windows) {
"vectorcraft-cli.exe"
} else {
"vectorcraft-cli"
};
if let Ok(exe) = std::env::current_exe()
&& let Some(parent) = exe.parent()
{
for path in [parent.join(name), parent.join("bin").join(name)] {
if path.is_file() {
return path;
}
}
}
name.into()
fn vectorcraft() -> Result<&'static std::path::Path, String> {
crate::software::Software::VectorCraft.executable()
}
fn import_ai(bytes: &[u8]) -> Result<Vec<Page>, String> {
let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
let input = dir.path().join("input.ai");
std::fs::write(&input, bytes).map_err(|e| e.to_string())?;
let mut command = std::process::Command::new(vectorcraft());
let mut command = std::process::Command::new(vectorcraft()?);
command.arg("--safe-mode").arg("info").arg(&input);
let info = run_vectorcraft(&mut command, dir.path())?;
let artboards = info
@ -466,6 +449,80 @@ fn import_ai(bytes: &[u8]) -> Result<Vec<Page>, String> {
Ok(pages)
}
pub(crate) fn reference_ai(bytes: &[u8]) -> Result<Vec<(String, String)>, String> {
let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
let input = dir.path().join("input.ai");
std::fs::write(&input, bytes).map_err(|e| e.to_string())?;
let mut command = std::process::Command::new(vectorcraft()?);
command.arg("--safe-mode").arg("info").arg(&input);
let info = run_vectorcraft(&mut command, dir.path())?;
let boards = info
.get("artboards")
.and_then(|v| v.as_array())
.ok_or("No Illustrator artboards")?;
if boards.is_empty() || boards.len() > 64 {
return Err("Illustrator supports 1–64 artboards.".into());
}
boards
.iter()
.enumerate()
.map(|(index, board)| {
let (svg, warnings) = convert_ai(bytes, "ai", "svg", Some(index))?;
let label = format!(
"Artboard {} · {} {}",
index + 1,
board
.get("name")
.and_then(|v| v.as_str())
.unwrap_or("Unnamed"),
warnings.join("; ")
);
Ok((label, String::from_utf8(svg).map_err(|e| e.to_string())?))
})
.collect()
}
pub(crate) fn reference_fig(
bytes: &[u8],
name: &str,
native: bool,
) -> Result<(Vec<(String, String)>, String), String> {
use figcraft_doc::NodeKind;
let (doc, warnings) = if native {
figcraft_format::load_bytes(bytes)
} else {
figcraft_format::fig::import(bytes, name)
}
.map_err(|e| e.to_string())?;
let mut pages = Vec::new();
for id in &doc.pages {
let Some(page) = doc.node(*id) else { continue };
let mut loose = Vec::new();
for id in &page.children {
let Some(node) = doc.node(*id) else { continue };
if matches!(node.kind, NodeKind::Frame | NodeKind::Component { .. }) {
let svg = figcraft_svg::export_svg(&doc, &[*id], &Default::default())
.ok_or("Cannot render Figma frame")?;
pages.push((format!("{} / {}", page.name, node.name), svg));
} else {
loose.push(*id);
}
}
if !loose.is_empty() {
let svg = figcraft_svg::export_svg(&doc, &loose, &Default::default())
.ok_or("Cannot render Figma page")?;
pages.push((page.name.clone(), svg));
}
if pages.len() > 256 {
return Err("Reference supports up to 256 pages/frames.".into());
}
}
if pages.is_empty() {
return Err("No visible Figma pages/frames.".into());
}
Ok((pages, warnings.join("; ")))
}
fn convert_ai(
bytes: &[u8],
from: &str,
@ -476,7 +533,7 @@ fn convert_ai(
let input = dir.path().join(format!("input.{from}"));
let output = dir.path().join(format!("output.{to}"));
std::fs::write(&input, bytes).map_err(|e| e.to_string())?;
let mut command = std::process::Command::new(vectorcraft());
let mut command = std::process::Command::new(vectorcraft()?);
command
.arg("--safe-mode")
.arg("convert")

View File

@ -212,11 +212,11 @@ fn plans_round_trip_fractional_geometry_crop_and_both_sizing_modes() {
}
}
#[test]
fn masks_fit_modes_and_shared_input_corrections_are_explicit() {
fn invalid_masks_fit_modes_and_shared_input_corrections_are_explicit() {
for (path, value) in [
(
"/device/screenList/items/S1/presetList/items/A/layerList/items/1/cropping/mask/pp/left",
json!(100),
json!(-1),
),
(
"/device/screenList/items/S1/presetList/items/A/layerList/items/1/cropping/classic/pp/aspectOverride",
@ -240,12 +240,12 @@ fn family_links_save_migrate_recover_and_validate() {
let mut old: Value = serde_json::from_str(old).unwrap();
old["layers"][0]["midra_link"] = json!({"screen":"001","layer":"02"});
let p = Project::from_json(&old.to_string()).unwrap();
assert_eq!(p.version, 18);
assert_eq!(p.version, 22);
assert_eq!(
p.layers[0].device_link.as_ref().unwrap().family,
p.layers[0].load_mapping.as_ref().unwrap().family,
Family::Midra4k
);
assert_eq!(p.layers[0].device_link.as_ref().unwrap().screen, "1");
assert_eq!(p.layers[0].load_mapping.as_ref().unwrap().screen, "1");
let mut layout = p.layout().unwrap();
let link = DeviceLink {
family: Family::Aquilon,
@ -255,15 +255,15 @@ fn family_links_save_migrate_recover_and_validate() {
layout.set_device_link(0, Some(link.clone())).unwrap();
let p = Project::from_layout(&layout);
let text = p.to_json().unwrap();
assert!(text.contains("device_link"));
assert!(text.contains("load_mapping"));
assert!(!text.contains("midra_link"));
assert_eq!(
Project::from_json(&text).unwrap().layers[0].device_link,
Project::from_json(&text).unwrap().layers[0].load_mapping,
Some(link)
);
layout.undo();
assert_eq!(
layout.layer_info(0).device_link.as_ref().unwrap().family,
layout.layer_info(0).load_mapping.as_ref().unwrap().family,
Family::Midra4k
);
for (family, screen) in [
@ -300,8 +300,8 @@ fn documented_v13_example_contains_native_aquilon_link() {
"../../../docs/interfaces/canvas-pilot-v13.example.json"
))
.unwrap();
assert_eq!(p.version, 18);
let link = p.layers[0].device_link.as_ref().unwrap();
assert_eq!(p.version, 22);
let link = p.layers[0].load_mapping.as_ref().unwrap();
assert_eq!(link.family, Family::Aquilon);
assert_eq!(link.screen, "S1");
assert_eq!(Project::from_json(&p.to_json().unwrap()).unwrap(), p);
@ -329,32 +329,191 @@ fn explicit_midra_fit_is_not_silently_sent_to_aquilon() {
}
}
fn clipped(reveal: Geometry, g: Geometry) -> Geometry {
let x = reveal.x.clamp(g.x, g.x + g.width);
let y = reveal.y.clamp(g.y, g.y + g.height);
Geometry {
x,
y,
width: (reveal.x + reveal.width).clamp(g.x, g.x + g.width) - x,
height: (reveal.y + reveal.height).clamp(g.y, g.y + g.height) - y,
}
}
#[test]
fn masked_editor_layers_are_rejected_before_aquilon_send() {
let snapshot = Snapshot::parse(&identity(), &routed()).unwrap();
let mut layout = Layout::default();
layout
.set_mask(
0,
canvas_pilot::formats::Mask {
origin: Default::default(),
left: 0.1,
..Default::default()
},
)
.unwrap();
assert!(
Plan::prepare(
&snapshot,
&layout,
0,
&[(layout.layer_info(0).id, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.unwrap_err()
.contains("masking")
);
fn masks_roundtrip_both_origins_sizing_modes_and_banks_without_changing_crop() {
use canvas_pilot::formats::{Mask, MaskOrigin};
for origin in [MaskOrigin::Layer, MaskOrigin::Source] {
for sizing in [Sizing::OutputBox, Sizing::SourceAspect] {
for target in [Target::Preview, Target::Program] {
for (width, height, zoom, offset) in [
(640.5, 360.25, 1.0, [0.0, 0.0]),
(301.25, 251.5, 2.0, [30.0, -10.0]),
(100.0, 200.0, 4.0, [-15.0, 20.0]),
] {
let mut layout = Layout::default();
layout
.apply(
0,
Geometry {
x: 12.125,
y: 34.375,
width,
height,
},
)
.unwrap();
layout.set_framing(0, Framing { zoom, offset }).unwrap();
let mut raw = routed();
let mut unmasked_fields = None;
for mask in [
Mask {
origin,
left: 0.2,
right: 0.1,
top: 0.3,
bottom: 0.2,
},
Mask {
origin,
left: 0.8,
right: 0.2,
top: 0.0,
bottom: 0.0,
},
Mask {
origin,
left: 0.0,
right: 0.0,
top: 0.4,
bottom: 0.6,
},
Mask::default(),
] {
layout.set_mask(0, mask).unwrap();
let snapshot = Snapshot::parse(&identity(), &raw).unwrap();
let plan = Plan::prepare(
&snapshot,
&layout,
0,
&[(layout.layer_info(0).id, "1".into())],
target,
sizing,
)
.unwrap();
let mut increasing_mask_seen = false;
for change in &plan.changes {
let path = format!("/{}", change.path.join("/"));
assert!(
!path.contains("/source/")
&& !path.contains("/inputList/")
&& !path.contains("xTake")
);
if path.contains("/mask/") {
let decrease = change.after.as_u64().unwrap()
< change.before.as_u64().unwrap();
if decrease {
assert!(!increasing_mask_seen);
} else {
increasing_mask_seen = true;
}
}
*raw.pointer_mut(&path).unwrap() = change.after.clone();
}
let base = Profile::Aquilon6.layer_path("S1", &plan.bank, "1");
let unchanged = (
raw.pointer(&format!("{base}/position")).unwrap().clone(),
raw.pointer(&format!("{base}/cropping/classic"))
.unwrap()
.clone(),
);
if let Some(previous) = &unmasked_fields {
assert_eq!(
previous, &unchanged,
"Masking must not resize or recrop the image"
);
}
unmasked_fields = Some(unchanged);
let mut decoded_raw = raw.clone();
let group = &mut decoded_raw["device"]["screenAuxGroupList"]["items"]["S1"];
group["status"]["pp"]["transition"] =
json!(if group["control"]["pp"]["presetDown"] == plan.bank {
"AT_UP"
} else {
"AT_DOWN"
});
let decoded = Snapshot::parse(&identity(), &decoded_raw).unwrap();
let layer = &decoded.screens[0].layers[0];
assert!(layer.unsupported.is_none(), "{:?}", layer.unsupported);
decoded.screens[0].import(&[0]).unwrap();
let expected = clipped(
layout.formats().mask_bounds(0, layout.layers()[0]).unwrap(),
layer.geometry,
);
let actual = layer.mask.bounds(layer.geometry);
for (a, b) in [
(expected.x, actual.x),
(expected.y, actual.y),
(expected.width, actual.width),
(expected.height, actual.height),
] {
assert!(
(a - b).abs() < 1.0,
"{origin:?} {sizing:?} {target:?}: {expected:?} vs {actual:?}"
);
}
if mask.is_empty() {
let base = Profile::Aquilon6.layer_path("S1", &plan.bank, "1");
for edge in ["left", "right", "top", "bottom"] {
assert_eq!(
raw.pointer(&format!("{base}/cropping/mask/pp/{edge}")),
Some(&json!(0))
);
}
}
}
}
}
}
}
}
#[test]
fn malformed_masks_block_import_and_send_but_valid_unrouted_masks_import() {
let base = Profile::Aquilon6.layer_path("S1", "A", "1");
for (left, right) in [
(json!(-1), json!(0)),
(json!(65536), json!(0)),
(json!(0.5), json!(0)),
(json!(40000), json!(30000)),
(json!(null), json!(0)),
] {
let mut r = raw();
*r.pointer_mut(&format!("{base}/cropping/mask/pp/left"))
.unwrap() = left;
*r.pointer_mut(&format!("{base}/cropping/mask/pp/right"))
.unwrap() = right;
let s = Snapshot::parse(&identity(), &r).unwrap();
assert!(s.screens[0].import(&[0]).is_err());
let layout = Layout::default();
assert!(
Plan::prepare(
&s,
&layout,
0,
&[(layout.layer_info(0).id, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.is_err()
);
}
let mut r = raw();
*r.pointer_mut(&format!("{base}/cropping/mask/pp/left"))
.unwrap() = json!(16384);
let s = Snapshot::parse(&identity(), &r).unwrap();
s.screens[0].import(&[0]).unwrap();
assert!((s.screens[0].layers[0].mask.left - 16384.0 / 65535.0).abs() < 1e-9);
}
#[test]
@ -411,3 +570,200 @@ fn all_models_and_firmware_versions_use_checked_geometry_with_compatibility_warn
assert!(Snapshot::parse(&id, &raw()).is_err());
}
}
#[test]
fn excessive_mask_quantization_is_recorded_without_blocking_send() {
let snapshot = Snapshot::parse(&identity(), &routed()).unwrap();
let mut layout = Layout::default();
layout
.apply(
0,
Geometry {
x: 0.0,
y: 0.0,
width: 900000.0,
height: 506250.0,
},
)
.unwrap();
layout
.set_mask(
0,
canvas_pilot::formats::Mask {
left: 0.123456,
..Default::default()
},
)
.unwrap();
let plan = Plan::prepare(
&snapshot,
&layout,
0,
&[(layout.layer_info(0).id, "1".into())],
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
assert!(
plan.discrepancies
.iter()
.any(|entry| entry["field"] == "mask_bounds")
);
}
#[test]
fn captured_rs1_mask_import_preserves_visible_geometry_and_reveal_bounds() {
let capture: Value =
serde_json::from_str(include_str!("fixtures/aquilon-rs1-mask-6.2.json")).unwrap();
let mut state = raw();
let path = Profile::Aquilon6.layer_path("S1", "A", "1");
*state.pointer_mut(&path).unwrap() = capture["layer"].clone();
let snapshot = Snapshot::parse(&capture["identity"], &state).unwrap();
let layer = &snapshot.screens[0].layers[0];
snapshot.screens[0].import(&[0]).unwrap();
let expected: Geometry = serde_json::from_value(capture["editor_geometry"].clone()).unwrap();
let mask: canvas_pilot::formats::Mask =
serde_json::from_value(capture["editor_mask"].clone()).unwrap();
let expected_reveal = clipped(mask.bounds(expected), layer.geometry);
let actual_reveal = layer.mask.bounds(layer.geometry);
for (want, got) in [(expected, layer.geometry), (expected_reveal, actual_reveal)] {
for (a, b) in [
(want.x, got.x),
(want.y, got.y),
(want.width, got.width),
(want.height, got.height),
] {
assert!((a - b).abs() < 1.0, "{want:?} vs {got:?}");
}
}
assert_eq!(layer.source, "LIVE_1");
assert_eq!(layer.mask.origin, canvas_pilot::formats::MaskOrigin::Layer);
}
#[test]
fn one_editor_layer_can_prepare_multiple_distinct_aquilon_destinations() {
let snapshot = Snapshot::parse(&identity(), &routed()).unwrap();
let layout = Layout::default();
let mappings = vec![(1, "1".into()), (1, "2".into())];
let plan = Plan::prepare(
&snapshot,
&layout,
0,
&mappings,
Target::Preview,
Sizing::OutputBox,
)
.unwrap();
for layer in ["1", "2"] {
assert!(
plan.observed
.iter()
.any(|(path, _)| path.ends_with(&format!("/layerList/items/{layer}")))
);
}
assert!(
Plan::prepare(
&snapshot,
&layout,
0,
&[(1, "1".into()), (2, "1".into())],
Target::Preview,
Sizing::OutputBox
)
.is_err()
);
}
#[test]
fn explicit_source_selection_is_guarded_and_verified_in_the_plan() {
let snapshot = Snapshot::parse(&identity(), &raw()).unwrap();
let layout = Layout::default();
let id = layout.layer_info(0).id;
let plan = Plan::prepare_with_inputs(
&snapshot,
&layout,
0,
&[(id, "1".into())],
Target::Preview,
Sizing::OutputBox,
&[(id, 1)].into(),
)
.unwrap();
assert_eq!(plan.changes[0].after, json!("LIVE_1"));
assert!(
plan.changes[0]
.path
.join("/")
.ends_with("source/pp/inputNum")
);
canvas_pilot::device_send::validate_fresh(&plan, &snapshot).unwrap();
let mut changed = snapshot.clone();
changed.raw["device"]["inputList"]["items"]["IN_1"]["status"]["pp"]["plug"] = json!("OTHER");
assert!(canvas_pilot::device_send::validate_fresh(&plan, &changed).is_err());
}
#[test]
fn reviewed_aquilon_source_adaptation_is_explicit_and_preserves_input_processing_guards() {
use canvas_pilot::device_send::{self, Conversion};
let mut state = routed();
state["device"]["inputList"]["items"]["IN_1"]["plugList"]["items"]["1"]["status"]["signal"]["pp"]
["imageWidth"] = json!(3840);
state["device"]["inputList"]["items"]["IN_1"]["plugList"]["items"]["1"]["status"]["signal"]["pp"]
["imageHeight"] = json!(2160);
let snapshot = Snapshot::parse(&identity(), &state).unwrap();
let editor = Layout::default();
let before = Project::from_layout(&editor);
let mappings = [(editor.layer_info(0).id, "1".into())];
assert!(
Plan::prepare(
&snapshot,
&editor,
0,
&mappings,
Target::Preview,
Sizing::OutputBox
)
.is_err()
);
let options = Conversion {
source: true,
..Default::default()
};
let plan = device_send::prepare_converted(
&snapshot,
&editor,
0,
&mappings,
Target::Preview,
Sizing::OutputBox,
&Default::default(),
options,
)
.unwrap();
assert_eq!(plan.conversions.len(), 1);
assert!(
!plan
.changes
.iter()
.any(|c| c.path.join("/").contains("source/"))
);
device_send::validate_fresh(&plan, &snapshot).unwrap();
assert_eq!(Project::from_layout(&editor), before);
state["device"]["inputList"]["items"]["IN_1"]["plugList"]["items"]["1"]["settings"]["aspect"]
["pp"]["transformTo"] = json!("CUSTOM");
let corrected = Snapshot::parse(&identity(), &state).unwrap();
assert!(
device_send::prepare_converted(
&corrected,
&editor,
0,
&mappings,
Target::Preview,
Sizing::OutputBox,
&Default::default(),
options
)
.unwrap_err()
.contains("aspect correction")
);
}

View File

@ -65,6 +65,7 @@ fn every_fit_roundtrips_exact_crop_mask_and_offset_with_atomic_undo() {
layout.set_mask(0, mask).unwrap();
let text = clipboard::encode(&layout, &[0], "Readable values").unwrap();
let shape = parse_values(&text).unwrap().shapes.remove(0);
layout.set_layer_fit(1, fit, Crop::default()).unwrap();
let before = Project::from_layout(&layout);
let a = shape.appearance.unwrap();
assert_eq!(a.fit, fit);
@ -84,7 +85,7 @@ fn every_fit_roundtrips_exact_crop_mask_and_offset_with_atomic_undo() {
}
assert_eq!(after.inputs, before.inputs);
assert_eq!(after.layers[1].source_id, before.layers[1].source_id);
assert_eq!(after.layers[1].device_link, before.layers[1].device_link);
assert_eq!(after.layers[1].load_mapping, before.layers[1].load_mapping);
assert_eq!(after.layers[1].name, before.layers[1].name);
let second = clipboard::encode(&layout, &[1], "Second copy").unwrap();
assert_eq!(parse_values(&second).unwrap().shapes[0].appearance, Some(a));
@ -96,8 +97,11 @@ fn every_fit_roundtrips_exact_crop_mask_and_offset_with_atomic_undo() {
}
}
#[test]
fn appearance_can_be_applied_independently_and_source_mismatch_is_atomic() {
fn appearance_adapts_source_sizes_independently_and_invalid_batches_are_atomic() {
let (mut layout, text) = copied(Some(LayerFit::Fullscreen));
layout
.set_layer_fit(1, Some(LayerFit::Fullscreen), Crop::default())
.unwrap();
let a = parse_values(&text).unwrap().shapes[0].appearance.unwrap();
let before = Project::from_layout(&layout);
let g = layout.layers()[1];
@ -105,12 +109,15 @@ fn appearance_can_be_applied_independently_and_source_mismatch_is_atomic() {
input_size: [1000., 500.],
..a
};
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, incompatible)], true, true)
.unwrap_err()
.contains("matching source dimensions")
);
let input = layout.formats().input(1).unwrap();
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, incompatible)], true, true)
.unwrap();
assert_eq!(layout.formats().input(1).unwrap(), input);
assert!((layout.formats().advanced[1].left - a.crop.left * input[0] / 1000.).abs() < 1e-9);
assert!((layout.formats().advanced[1].top - a.crop.top * input[1] / 500.).abs() < 1e-9);
assert_eq!(layout.formats().layer_fit[1], a.fit);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, incompatible)], false, true)
@ -156,20 +163,64 @@ fn appearance_can_be_applied_independently_and_source_mismatch_is_atomic() {
);
}
#[test]
fn normal_crop_requires_matching_aspect_and_does_not_silently_reframe() {
fn normal_crop_falls_back_to_centered_fit_for_a_different_box() {
let (mut layout, text) = copied(None);
let a = parse_values(&text).unwrap().shapes[0].appearance.unwrap();
let before = Project::from_layout(&layout);
let mut g = layout.layers()[1];
g.width = g.height;
assert!(
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, true)
.unwrap_err()
.contains("Include Format")
);
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, true)
.unwrap();
assert_eq!(layout.formats().layer_fit[1], Some(LayerFit::Centered));
assert_eq!(layout.formats().advanced[1], a.crop);
let retained = a.crop.remaining(a.input_size).unwrap();
let fitted = LayerFit::Centered.image(retained, g).unwrap();
assert!((fitted.width / fitted.height - retained[0] / retained[1]).abs() < 1e-9);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
#[test]
fn all_explicit_modes_paste_across_input_ratios_without_changing_sources() {
for fit in LayerFit::ALL {
let (mut layout, text) = copied(Some(if fit == LayerFit::Fullscreen {
LayerFit::Centered
} else {
LayerFit::Fullscreen
}));
layout.set_layer_fit(1, Some(fit), Crop::default()).unwrap();
let a = parse_values(&text).unwrap().shapes[0].appearance.unwrap();
layout.set_layer_source_resolution(1, [942, 1029]).unwrap();
let before = Project::from_layout(&layout);
let sources = layout.formats().sources.clone();
let g = layout.layers()[1];
layout
.apply_mapped_clipboard(&[(1, g)], &[], &[(1, a)], true, true)
.unwrap();
assert_eq!(layout.formats().sources, sources);
assert_eq!(layout.formats().layer_fit[1], Some(fit));
let crop = layout.formats().advanced[1];
for (actual, expected) in [
(crop.left / 942., a.crop.left / a.input_size[0]),
(crop.right / 942., a.crop.right / a.input_size[0]),
(crop.top / 1029., a.crop.top / a.input_size[1]),
(crop.bottom / 1029., a.crop.bottom / a.input_size[1]),
] {
assert!((actual - expected).abs() < 1e-9);
}
assert_eq!(layout.formats().masks[1], a.mask);
let copied_again = clipboard::encode(&layout, &[1], "").unwrap();
let restored = parse_values(&copied_again).unwrap().shapes[0]
.appearance
.unwrap();
assert_eq!(restored.crop, crop);
assert_eq!(restored.fit, Some(fit));
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
}
#[test]
fn clipboard_schema_is_bounded_versioned_and_never_falls_back_on_invalid_payload() {
let (layout, text) = copied(None);

View File

@ -217,6 +217,9 @@ fn device_addresses_support_ports_and_ipv6() {
("192.168.10.146", "192.168.10.146:80"),
(" 192.168.10.146:3000 ", "192.168.10.146:3000"),
("::1", "[::1]:80"),
("http://127.0.0.1:3000", "127.0.0.1:3000"),
(" http://192.168.10.142/ ", "192.168.10.142:80"),
("http://[::1]:3000/", "[::1]:3000"),
("[::1]:3000", "[::1]:3000"),
] {
assert_eq!(address(input).unwrap().to_string(), expected);
@ -224,7 +227,11 @@ fn device_addresses_support_ports_and_ipv6() {
for input in [
"",
"localhost",
"http://127.0.0.1:3000",
"https://127.0.0.1/",
"http://user:pass@127.0.0.1/",
"http://127.0.0.1/?query=1",
"http://127.0.0.1/#fragment",
"http://127.0.0.1/path",
"127.0.0.1:0",
"127.0.0.1:65536",
"127.0.0.1:abc",

View File

@ -0,0 +1,137 @@
use canvas_pilot::{
ConnectionTarget, DeviceLink, Layout, SendDestination, SendMapping, project::Project,
};
fn link(screen: &str, layer: &str) -> DeviceLink {
DeviceLink {
family: Default::default(),
screen: screen.into(),
layer: layer.into(),
}
}
fn sends() -> SendMapping {
SendMapping {
destinations: vec![link("1", "2"), link("2", "3")]
.into_iter()
.map(|layer| SendDestination {
connection: ConnectionTarget::Current,
layer,
})
.collect(),
}
}
#[test]
fn independent_directions_roundtrip_and_undo_together() {
let mut layout = Layout::default();
let before = Project::from_layout(&layout);
layout
.set_device_mappings(0, Some(link("1", "1")), sends())
.unwrap();
let project = Project::from_layout(&layout);
assert_eq!(project.layers[0].load_mapping, Some(link("1", "1")));
assert_eq!(project.layers[0].send_mapping, sends());
let reopened = Project::from_json(&project.to_json().unwrap()).unwrap();
assert_eq!(Project::from_layout(&reopened.layout().unwrap()), project);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(Project::from_layout(&layout), project);
layout.set_device_link(0, Some(link("3", "4"))).unwrap();
assert_eq!(layout.layer_info(0).load_mapping, Some(link("3", "4")));
assert_eq!(
layout.layer_info(0).send_mapping,
SendMapping::linked(Some(link("3", "4")))
);
layout.set_device_link(0, None).unwrap();
assert!(layout.layer_info(0).load_mapping.is_none());
assert!(layout.layer_info(0).send_mapping.destinations.is_empty());
}
#[test]
fn v18_migration_synchronizes_links_and_v19_requires_both_directions() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-v18.example.json");
let project = canvas_pilot::project_recovery::from_json(old)
.unwrap()
.project;
assert_eq!(project.version, 22);
for layer in &project.layers {
assert_eq!(
layer.send_mapping,
SendMapping::linked(layer.load_mapping.clone())
);
}
assert_eq!(
project,
Project::from_json(include_str!(
"../../../docs/interfaces/canvas-pilot-v22.example.json"
))
.unwrap()
);
let json = serde_json::to_value(&project).unwrap();
for key in ["load_mapping", "send_mapping"] {
let mut bad = json.clone();
bad["layers"][0].as_object_mut().unwrap().remove(key);
assert!(Project::from_json(&bad.to_string()).is_err());
}
let mut bad = json.clone();
bad["version"] = 18.into();
assert!(Project::from_json(&bad.to_string()).is_err());
let mut bad = json;
bad["layers"][0]["send_mapping"]["destinations"][0]["connection"] = "other-machine".into();
assert!(Project::from_json(&bad.to_string()).is_err());
}
#[test]
fn invalid_destinations_are_atomic_and_repeated_load_sources_are_allowed() {
let mut layout = Layout::default();
layout.set_device_link(0, Some(link("1", "1"))).unwrap();
layout.set_device_link(1, Some(link("1", "1"))).unwrap();
let before = Project::from_layout(&layout);
let mut duplicate = sends();
duplicate
.destinations
.push(duplicate.destinations[0].clone());
assert!(layout.set_device_mappings(0, None, duplicate).is_err());
let mut invalid = sends();
invalid.destinations[0].layer.screen = "../1".into();
assert!(layout.set_device_mappings(0, None, invalid).is_err());
assert!(layout.set_device_mappings(99, None, sends()).is_err());
assert_eq!(Project::from_layout(&layout), before);
}
#[test]
fn every_snapshot_codec_preserves_independent_directions_and_fanout() {
use canvas_pilot::{
exchange::Options,
exchange_metadata as metadata,
interchange::{self, Codec},
};
let mut layout = Layout::default();
layout
.set_device_mappings(0, Some(link("3", "1")), sends())
.unwrap();
let project = Project::from_layout(&layout);
let ids = [project.layers[0].id];
let expected = metadata::snapshot(&project, &ids).unwrap();
for codec in Codec::available()
.into_iter()
.filter(|&c| metadata::supported(c))
{
let bytes = interchange::export(
&project,
&ids,
codec,
Options {
extra_parameters: true,
..Default::default()
},
)
.unwrap();
assert_eq!(
metadata::extract(&bytes, codec).unwrap(),
Some(expected.clone()),
"{codec:?}"
);
}
}

View File

@ -20,11 +20,12 @@ fn fixture() -> Project {
let mut p = Project::from_layout(&layout);
p.layers[0].name = "<Speaker> & \"guest\"".into();
p.layers[0].folder = "Memory A".into();
p.layers[0].device_link = Some(canvas_pilot::DeviceLink {
p.layers[0].load_mapping = Some(canvas_pilot::DeviceLink {
family: Default::default(),
screen: "2".into(),
layer: "1".into(),
});
p.layers[0].send_mapping = canvas_pilot::SendMapping::linked(p.layers[0].load_mapping.clone());
p.workspace.collapsed_folders = vec!["Memory A".into()];
p
}
@ -345,11 +346,8 @@ fn figcraft_native_resave_preserves_snapshot_after_artwork_edits() {
}
#[test]
fn every_snapshot_codec_roundtrips_all_fit_modes_masks_sources_links_and_proposals() {
use canvas_pilot::{
formats::{Crop, LayerFit, Mask},
input_proposal::InputProposal,
};
fn every_snapshot_codec_roundtrips_all_fit_modes_masks_sources_links_and_workspace() {
use canvas_pilot::formats::{Crop, LayerFit, Mask};
for origin in [
canvas_pilot::formats::MaskOrigin::Layer,
canvas_pilot::formats::MaskOrigin::Source,
@ -387,27 +385,20 @@ fn every_snapshot_codec_roundtrips_all_fit_modes_masks_sources_links_and_proposa
)
.unwrap();
let mut p = Project::from_layout(&layout);
p.inputs[0].input_crop = Crop {
left: 10.25,
right: 20.5,
top: 5.25,
bottom: 10.75,
};
p.layers[0].name = "Speaker — é".into();
p.layers[0].folder = "Scene".into();
p.folders = vec!["Scene".into(), "Unused".into()];
p.layers[0].pivot = [0.25, 0.75];
p.layers[0].device_link = Some(canvas_pilot::DeviceLink {
p.layers[0].load_mapping = Some(canvas_pilot::DeviceLink {
family: Default::default(),
screen: "1".into(),
layer: "3".into(),
});
p.layers[0].send_mapping =
canvas_pilot::SendMapping::linked(p.layers[0].load_mapping.clone());
p.layers[1].source_id = p.layers[0].source_id;
let native = &p.inputs[0].native_resolution;
let input = p.inputs[0]
.input_crop
.remaining([native.width as f64, native.height as f64])
.unwrap();
let input = [native.width as f64, native.height as f64];
for layer in &mut p.layers {
if layer.layer_fit.is_none() {
layer.advanced_crop = canvas_pilot::formats::crop_from_framing(
@ -427,7 +418,7 @@ fn every_snapshot_codec_roundtrips_all_fit_modes_masks_sources_links_and_proposa
p.editor.show_source_pattern = true;
p.editor.viewport_zoom = 1.75;
p.editor.backdrop_title = "Round trip".into();
p.editor.keep_aspect_ratio = false;
p.layers[0].keep_aspect_ratio = false;
p.editor.outline_layers = true;
p.editor.show_toolbar_icon_names = true;
p.workspace.resize_mode = canvas_pilot::ResizeMode::Mirror;
@ -438,34 +429,13 @@ fn every_snapshot_codec_roundtrips_all_fit_modes_masks_sources_links_and_proposa
p.workspace.snapping.grid = true;
p.workspace.snapping.grid_divisions = [7, 5];
p.input_proposals.push(InputProposal {
layer_id: p.layers[0].id,
device_link: p.layers[0].device_link.clone().unwrap(),
input: "INPUT_4".into(),
plug: "2".into(),
settings: serde_json::from_value(serde_json::json!({
"aspect/pp/signal":"16_9", "aspect/pp/transformTo":"CUSTOM",
"aspect/pp/customRatio":1778, "aspect/pp/layerFill":"CENTERED",
"cropping/control/pp/predefined":"NONE", "cropping/control/pp/left":41,
"cropping/control/pp/right":17, "cropping/control/pp/top":3,
"cropping/control/pp/bottom":9
}))
.unwrap(),
});
let ids: Vec<_> = p.layers.iter().map(|l| l.id).collect();
assert_eq!(Project::from_json(&p.to_json().unwrap()).unwrap(), p);
let expected = metadata::snapshot(&p, &ids).unwrap();
assert_eq!(expected.layers, p.layers);
assert_eq!(expected.inputs.len(), 1);
assert_eq!(expected.input_proposals, p.input_proposals);
assert_eq!(expected.layers[0].mask, p.layers[0].mask);
assert_eq!(expected.layers[0].layer_fit, fit);
assert!(
metadata::snapshot(&p, &[p.layers[1].id])
.unwrap()
.input_proposals
.is_empty()
);
for codec in Codec::available()
.into_iter()
.filter(|&c| metadata::supported(c))

View File

@ -17,3 +17,18 @@ Analog Way's AWJ V6.2 guide, section 2.1 (including the RS Alpha spelling alias)
Tests substitute these identities and firmware versions into the Cmax fixture.
These synthetic cases exercise identity matching and the common adapter; they
are not captures or acceptance evidence for those models/firmware releases.
Mask regressions vary the sanitized layer's four `cropping.mask.pp` edges and
container geometry. They cover both editor mask origins, centered margins in both
sizing strategies, Preview/Program, full blanking, reset-to-zero, malformed units
and quantization limits. The separate RS1 6.2.79 live diagnostic and WebRCS evidence
are recorded in `docs/canvas-pilot/aquilon-compatibility.md`; the fixture remains
the original Cmax capture, not a relabelled RS1 capture.
`aquilon-rs1-mask-6.2.json` is a separate sanitized RS1 6.2.79 layer readback from
2026-11-17. The explicitly invoked diagnostic temporarily sent a fractional
640.5 × 360.25 Preview layer with asymmetric mask, then restored its baseline.
The fixture retains identity, one routed layer's geometry/crop/mask, and the
requested editor geometry/mask for the one-pixel round-trip assertion. WebRCS's
rendered clip percentages matched the native mask units. No labels, addresses,
credentials or unrelated configuration are included.

View File

@ -0,0 +1,60 @@
{
"identity": {
"type": "AQL RS1",
"isLinked": false,
"version": {
"major": 6,
"minor": 2,
"patch": 79,
"beta": false
}
},
"layer": {
"position": {
"pp": {
"posH": 332,
"posV": 215,
"sizeH": 641,
"sizeV": 360,
"anchor": "MIDDLE_CENTER"
}
},
"source": {
"pp": {
"inputNum": "LIVE_1"
}
},
"cropping": {
"classic": {
"pp": {
"aspectOverride": "CENTERED",
"left": 0,
"right": 0,
"top": 3,
"bottom": 3
}
},
"mask": {
"pp": {
"left": 13161,
"right": 6536,
"top": 19560,
"bottom": 13184
}
}
}
},
"editor_geometry": {
"x": 12.125,
"y": 34.375,
"width": 640.5,
"height": 360.25
},
"editor_mask": {
"origin": "layer",
"left": 0.2,
"right": 0.1,
"top": 0.3,
"bottom": 0.2
}
}

View File

@ -0,0 +1,39 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << >> /Contents 4 0 R >>
endobj
4 0 obj
<< /Length 25 >>
stream
1 0 0 rg 0 0 200 100 re f
endstream
endobj
5 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /CropBox [0 0 100 100] /Rotate 90 /Resources << >> /Contents 6 0 R >>
endobj
6 0 obj
<< /Length 25 >>
stream
0 1 0 rg 0 0 200 100 re f
endstream
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000121 00000 n
0000000225 00000 n
0000000300 00000 n
0000000438 00000 n
trailer
<< /Size 7 /Root 1 0 R >>
startxref
513
%%EOF

View File

@ -134,7 +134,7 @@ fn explicit_empty_folders_survive_history_save_rename_and_membership_changes() {
fn version_12_explicit_folder_validation_and_v11_migration() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-v11.example.json");
let p = Project::from_json(old).unwrap();
assert_eq!(p.version, 18);
assert_eq!(p.version, 22);
assert!(p.folders.is_empty());
let example = include_str!("../../../docs/interfaces/canvas-pilot-v12.example.json");
assert_eq!(

View File

@ -162,11 +162,11 @@ fn invalid_formats_crops_and_offsets_are_rejected() {
}
}
#[test]
fn input_crop_is_composed_once_and_keeps_original_source_format() {
fn processed_source_dimensions_are_used_without_extra_input_crop() {
let mut layout = Layout::default();
let source = Source {
input_crop: Crop::centered([1920.0, 1080.0], [1920.0, 1000.0]).unwrap(),
..Source::default()
native: [1920, 1000],
aspect: Aspect::Custom,
};
layout
.configure(1, 1, source, box_size(300.0, 250.0), false)
@ -180,13 +180,13 @@ fn input_crop_is_composed_once_and_keeps_original_source_format() {
},
)
.unwrap();
assert_eq!(layout.formats().sources[1].aspect, Aspect::SixteenNine);
assert_eq!(layout.formats().sources[1].aspect, Aspect::Custom);
let c = layout.formats().advanced[1];
close(source.input_crop.top + c.top, 290.0);
close(source.input_crop.left + c.left, 660.0);
close(c.top, 250.0);
close(c.left, 660.0);
let report = layout.calculation_report(1).unwrap();
assert!(report.contains("not a verified device recipe"));
assert!(report.contains("x 660.0, y 290.0, w 600.0, h 500.0"));
assert!(report.contains("x 660.0, y 250.0, w 600.0, h 500.0"));
}
#[test]
fn shared_sources_update_atomically_and_layer_framing_stays_independent() {
@ -206,8 +206,8 @@ fn shared_sources_update_atomically_and_layer_framing_stays_independent() {
let old = layout.formats().clone();
let boxes = layout.layers().clone();
let source = Source {
input_crop: Crop::centered([1920.0, 1080.0], [1920.0, 1000.0]).unwrap(),
..Source::default()
native: [1920, 1000],
aspect: Aspect::Custom,
};
layout.configure(1, 0, source, boxes[1], false).unwrap();
assert_eq!(layout.formats().input(0).unwrap(), [1920.0, 1000.0]);

View File

@ -402,3 +402,32 @@ fn explicit_mapping_without_selection_is_atomic_and_preserves_selection() {
.is_err()
);
}
#[test]
fn clipboard_tries_embedded_svg_after_invalid_drawio_candidate() {
let text = r#"<html><body><mxGraphModel/><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><rect x="10" y="20" width="30" height="40"/></svg></body></html>"#;
let imported = parse_values(text).unwrap();
assert_eq!(imported.shapes.len(), 1);
assert_eq!(imported.shapes[0].geometry.x, 10.);
assert!(imported.note.contains("used embedded SVG"));
assert!(imported.note.contains("rejected"));
}
#[test]
fn clipboard_unknown_text_is_not_misdiagnosed_as_drawio() {
for text in ["PowerPoint slide title and ordinary text", "\u{2060}"] {
let error = parse_values(text).unwrap_err();
assert!(error.contains("native PowerPoint clipboard"));
assert!(!error.contains("Invalid draw.io"));
}
let error =
parse_values("<html><body><mxGraphModel/><svg><path d='M0 0'/></svg></body></html>")
.unwrap_err();
assert!(error.contains("draw.io:"));
assert!(error.contains("SVG:"));
}
#[test]
fn clipboard_keeps_explicit_versions_strict_and_rejects_ambiguous_svg() {
assert!(parse_values(r#"<html data-midra-layout-geometry="99"><svg width="100" height="100"><rect width="30" height="40"/></svg></html>"#).is_err());
let error = parse_values("<html><svg/><svg/></html>").unwrap_err();
assert!(error.contains("multiple embedded documents"));
}

View File

@ -84,7 +84,7 @@ fn explicit_fit_survives_resize_undo_reordering_and_project_roundtrip() {
layout.apply(0, box_geometry()).unwrap();
assert_eq!(layout.formats().advanced[0], crop);
let before = Project::from_layout(&layout);
assert_eq!(before.version, 18);
assert_eq!(before.version, 22);
let loaded = Project::from_json(&before.to_json().unwrap()).unwrap();
assert_eq!(loaded, before);
assert_eq!(
@ -107,7 +107,7 @@ fn explicit_fit_survives_resize_undo_reordering_and_project_roundtrip() {
fn v13_migration_defaults_to_normal_crop_and_v14_requires_valid_fit() {
let text = include_str!("../../../docs/interfaces/canvas-pilot-v13.example.json");
let migrated = Project::from_json(text).unwrap();
assert_eq!(migrated.version, 18);
assert_eq!(migrated.version, 22);
assert!(migrated.layers.iter().all(|l| l.layer_fit.is_none()));
let mut json = serde_json::to_value(&migrated).unwrap();
json["layers"][0]
@ -125,7 +125,7 @@ fn current_documented_example_is_valid() {
"../../../docs/interfaces/canvas-pilot-v14.example.json"
))
.unwrap();
assert_eq!(p.version, 18);
assert_eq!(p.version, 22);
p.layout().unwrap();
}
@ -190,10 +190,10 @@ fn one_to_one_handles_trim_source_edges_without_zoom_and_undo_atomically() {
assert_eq!(
[crop.left, crop.right, crop.top, crop.bottom],
[
100.0 + changes[0],
80.0 + changes[1],
60.0 + changes[2],
40.0 + changes[3]
100.0 + changes[0] / 2.0,
80.0 + changes[1] / 2.0,
60.0 + changes[2] / 2.0,
40.0 + changes[3] / 2.0
]
);
assert_eq!(layout.layers()[0], g);
@ -221,11 +221,10 @@ fn one_to_one_crop_stops_at_source_limits_and_uncropped_image_cannot_move() {
layout
.set_layer_fit(0, Some(LayerFit::OneToOne), Crop::default())
.unwrap();
let input = layout.formats().input(0).unwrap();
layout.start_content_resize(0, ResizeHandle::Left, [0.0, 0.0]);
layout.drag_to([100000.0, 0.0]);
let crop = layout.formats().advanced[0];
near(crop.remaining(input).unwrap()[0], 0.001);
near(layout.edge_crop_bounds(0).unwrap().width, 0.001);
assert_eq!(layout.formats().advanced[0], Crop::default());
layout.drag_to([-100000.0, 0.0]);
assert_eq!(layout.formats().advanced[0], Crop::default());
layout.finish_drag();
@ -237,7 +236,7 @@ fn one_to_one_crop_stops_at_source_limits_and_uncropped_image_cannot_move() {
.set_layer_fit(0, Some(LayerFit::Centered), Crop::default())
.unwrap();
layout.start_content_resize(0, ResizeHandle::Left, [0.0, 0.0]);
assert!(!layout.dragging());
assert!(layout.dragging());
}
#[test]
@ -306,3 +305,248 @@ fn one_to_one_pan_preserves_crop_size_and_clamps_each_axis_with_undo_cancel() {
assert_eq!(Project::from_layout(&layout), after);
assert!(crop.pan_image([f64::NAN, 0.0]).is_err());
}
#[test]
fn advanced_edges_freeze_image_until_release_and_cancel_atomically() {
use canvas_pilot::ResizeHandle;
for fit in LayerFit::ALL {
let mut layout = Layout::default();
layout.select(Some(0));
layout.set_layer_fit(0, Some(fit), Crop::default()).unwrap();
let before = Project::from_layout(&layout);
let bounds = layout.edge_crop_bounds(0).unwrap();
layout.start_content_resize(0, ResizeHandle::Left, [bounds.x, bounds.y]);
layout.drag_to([bounds.x + bounds.width / 4.0, bounds.y]);
assert_eq!(Project::from_layout(&layout), before);
let pending = layout.edge_crop_bounds(0).unwrap();
near(pending.x, bounds.x + bounds.width / 4.0);
near(pending.width, bounds.width * 0.75);
layout.finish_drag();
near(
layout.formats().advanced[0].left,
layout.formats().input(0).unwrap()[0] / 4.0,
);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.start_content_resize(0, ResizeHandle::Right, [0.0, 0.0]);
layout.drag_to([-10.0, 0.0]);
layout.cancel_drag();
assert_eq!(Project::from_layout(&layout), before);
}
}
#[test]
fn device_exact_fit_uses_smart_crop_but_letterbox_and_stretch_stay_advanced() {
use canvas_pilot::formats::Source;
for (fit, width, height, normal) in [
(LayerFit::Centered, 960.0, 540.0, true),
(LayerFit::Cropped, 960.0, 540.0, true),
(LayerFit::OneToOne, 1920.0, 1080.0, true),
(LayerFit::Fullscreen, 960.0, 540.0, true),
(LayerFit::Centered, 960.0, 600.0, false),
(LayerFit::Cropped, 960.0, 600.0, false),
(LayerFit::Fullscreen, 960.0, 540.01, false),
] {
let mut layout = Layout::default();
let g = Geometry {
x: 10.0,
y: 20.0,
width,
height,
};
layout
.import_device_layers_with_fit(
&[(None, g, Some((Source::default(), Crop::default())))],
&[Some(fit)],
)
.unwrap();
let i = layout.layers().len() - 1;
assert_eq!(
layout.formats().layer_fit[i].is_none(),
normal,
"{fit:?} {height}"
);
let before = Project::from_layout(&layout);
layout.convert_to_smart_crop(i).unwrap();
assert!(layout.formats().layer_fit[i].is_none());
assert_eq!(layout.layers()[i], g);
if !normal {
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
}
}
#[test]
fn exact_import_keeps_nonzero_crop_and_mask() {
use canvas_pilot::formats::{LayerAppearance, Mask, Source};
let mut layout = Layout::default();
let crop = Crop {
left: 160.0,
right: 160.0,
top: 90.0,
bottom: 90.0,
};
let mask = Mask {
left: 0.1,
..Default::default()
};
let g = Geometry {
x: 20.0,
y: 30.0,
width: 800.0,
height: 450.0,
};
layout
.import_device_layers_with_appearance(
&[(None, g, Some((Source::default(), crop)))],
&[LayerAppearance {
fit: Some(LayerFit::Centered),
mask,
}],
)
.unwrap();
let i = layout.layers().len() - 1;
assert_eq!(layout.formats().layer_fit[i], None);
assert_eq!(layout.formats().advanced[i], crop);
assert_eq!(layout.formats().masks[i], mask);
layout
.set_layer_fit(i, Some(LayerFit::Centered), crop)
.unwrap();
layout.convert_to_smart_crop(i).unwrap();
assert_eq!(layout.formats().advanced[i], crop);
assert_eq!(layout.formats().masks[i], mask);
}
#[test]
fn midra_rounded_fit_imports_as_exact_smart_crop_without_moving_container_or_center() {
use canvas_pilot::formats::{LayerAppearance, Mask, Source};
// Read-only observation: Midra Screen 2 Layer 2, 2026-11-19.
let crop = Crop {
left: 408.75623712520024,
right: 460.02655069810027,
top: 262.6871137560082,
bottom: 225.98672465094987,
};
let g = Geometry {
x: 552.0,
y: 260.5,
width: 1296.0,
height: 729.0,
};
for fit in [LayerFit::Centered, LayerFit::Cropped] {
let mut layout = Layout::default();
let before = Project::from_layout(&layout);
let mask = Mask {
left: 0.1,
..Default::default()
};
layout
.import_device_layers_with_appearance(
&[(
Some(before.layers[0].id),
g,
Some((Source::default(), crop)),
)],
&[LayerAppearance {
fit: Some(fit),
mask,
}],
)
.unwrap();
let i = 0;
assert_eq!(layout.formats().layer_fit[i], None);
assert_eq!(layout.layers()[i], g);
assert_eq!(layout.formats().masks[i], mask);
let normalized = layout.formats().advanced[i];
near(normalized.left - normalized.right, crop.left - crop.right);
near(normalized.top - normalized.bottom, crop.top - crop.bottom);
let mapping = layout.formats().mapping(i, g).unwrap();
near(mapping.retained[0] * mapping.scale, g.width);
near(mapping.retained[1] * mapping.scale, g.height);
assert!(normalized.left >= crop.left && normalized.top >= crop.top);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
}
#[test]
fn rounded_import_tolerance_is_bounded_and_does_not_change_native_or_stretch_modes() {
use canvas_pilot::formats::Source;
for (fit, width, normal) in [
(LayerFit::Centered, 1919.0, true),
(LayerFit::Centered, 1918.0, false),
(LayerFit::Cropped, 1919.0, true),
(LayerFit::Cropped, 1918.0, false),
(LayerFit::Fullscreen, 1919.0, false),
(LayerFit::OneToOne, 1919.0, false),
] {
let mut layout = Layout::default();
let g = Geometry {
x: 0.0,
y: 0.0,
width,
height: 1080.0,
};
layout
.import_device_layers_with_fit(
&[(None, g, Some((Source::default(), Crop::default())))],
&[Some(fit)],
)
.unwrap();
let i = layout.layers().len() - 1;
assert_eq!(
layout.formats().layer_fit[i].is_none(),
normal,
"{fit:?} {width}"
);
if normal {
layout.formats().mapping(i, g).unwrap();
}
}
}
#[test]
fn smart_crop_converts_to_centered_edge_crop_losslessly_and_undoes() {
use canvas_pilot::formats::{Framing, Mask};
let mut layout = Layout::default();
layout.select(Some(0));
layout
.set_framing(
0,
Framing {
zoom: 1.75,
offset: [41.0, -23.0],
},
)
.unwrap();
let mask = Mask {
left: 0.1,
right: 0.05,
..Default::default()
};
layout.set_mask(0, mask).unwrap();
let before = Project::from_layout(&layout);
let geometry = layout.layers()[0];
let crop = layout.formats().advanced[0];
let input = layout.formats().input(0).unwrap();
layout.convert_to_edge_crop(0).unwrap();
assert_eq!(layout.formats().layer_fit[0], Some(LayerFit::Centered));
assert_eq!(layout.layers()[0], geometry);
assert_eq!(layout.formats().advanced[0], crop);
assert_eq!(layout.formats().masks[0], mask);
let image = LayerFit::Centered
.image(crop.remaining(input).unwrap(), geometry)
.unwrap();
near(image.x, geometry.x);
near(image.y, geometry.y);
near(image.width, geometry.width);
near(image.height, geometry.height);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
layout.convert_to_smart_crop(0).unwrap();
assert_eq!(Project::from_layout(&layout), before);
}

View File

@ -102,8 +102,10 @@ fn mask_schema_migration_validation_reorder_resize_and_atomic_import() {
let p = Project::from_layout(&l);
assert_eq!(Project::from_json(&p.to_json().unwrap()).unwrap(), p);
let old = include_str!("../../../docs/interfaces/canvas-pilot-v14.example.json");
let migrated = Project::from_json(old).unwrap();
assert_eq!(migrated.version, 18);
let migrated = canvas_pilot::project_recovery::from_json(old)
.unwrap()
.project;
assert_eq!(migrated.version, 22);
assert!(migrated.layers.iter().all(|l| l.mask == Mask::default()));
let mut json = serde_json::to_value(&p).unwrap();
json["layers"][0].as_object_mut().unwrap().remove("mask");
@ -195,7 +197,7 @@ fn mask_alignment_moves_only_the_reveal_window() {
}
#[test]
fn source_mask_reference_tracks_crop_fit_and_source_input_crop() {
fn source_mask_reference_tracks_crop_fit_and_processed_source_dimensions() {
use canvas_pilot::formats::MaskOrigin;
let mask = Mask {
origin: MaskOrigin::Source,
@ -305,11 +307,8 @@ fn source_mask_reference_tracks_crop_fit_and_source_input_crop() {
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
let source = canvas_pilot::formats::Source {
input_crop: Crop {
left: 100.0,
..Default::default()
},
..Default::default()
native: [1820, 1080],
aspect: canvas_pilot::formats::Aspect::Custom,
};
assert_eq!(source.input().unwrap(), [1820.0, 1080.0]);
let reference = mask
@ -326,7 +325,7 @@ fn source_mask_reference_tracks_crop_fit_and_source_input_crop() {
#[test]
fn mask_origin_migrates_strictly_and_survives_project_save() {
use canvas_pilot::formats::MaskOrigin;
Project::from_json(include_str!(
canvas_pilot::project_recovery::from_json(include_str!(
"../../../docs/interfaces/canvas-pilot-v17.example.json"
))
.unwrap();
@ -343,7 +342,9 @@ fn mask_origin_migrates_strictly_and_survives_project_save() {
MaskOrigin::Source
);
let old = include_str!("../../../docs/interfaces/canvas-pilot-v16.example.json");
let migrated = Project::from_json(old).unwrap();
let migrated = canvas_pilot::project_recovery::from_json(old)
.unwrap()
.project;
assert!(
migrated
.layers

View File

@ -250,9 +250,13 @@ fn pivot_placement_honors_screen_layer_pixel_and_grid_options() {
options.layer_edges = false;
options.pixels = true;
assert_eq!(
layout.snap_pivot(1, [833.3, 653.7], options, 6.0, None, true),
layout.snap_pivot(1, [833.2, 653.8], options, 6.0, None, true),
([833.0, 654.0], [None; 2])
);
assert_eq!(
layout.snap_pivot(1, [833.3, 653.7], options, 6.0, None, true),
([833.3, 653.7], [None; 2])
);
for spacing in [10.0, 100.0] {
let target = [833.3_f64, 653.7].map(|p| (p / spacing).round() * spacing);
assert_eq!(

View File

@ -1,6 +1,6 @@
use canvas_pilot::{
Geometry, Layout,
formats::{Crop, Framing, Source},
formats::{Framing, Source},
project::{Project, write_file},
};
@ -24,14 +24,7 @@ fn full_precision_project_roundtrip_restores_sources_crops_flags_and_selection()
width: 300.125,
height: 250.25,
};
let source = Source {
input_crop: Crop {
top: 40.0,
bottom: 40.0,
..Crop::default()
},
..Source::default()
};
let source = Source::default();
layout.configure(1, 0, source, g, true).unwrap();
layout
.set_framing(
@ -221,30 +214,30 @@ fn persistent_device_links_roundtrip_migrate_and_undo() {
.unwrap()
.layout()
.unwrap();
assert_eq!(restored.layer_info(0).device_link, Some(first_link));
assert_eq!(restored.layer_info(1).device_link, Some(link.clone()));
assert_eq!(restored.layer_info(0).load_mapping, Some(first_link));
assert_eq!(restored.layer_info(1).load_mapping, Some(link.clone()));
layout.undo();
assert!(layout.layer_info(1).device_link.is_none());
assert!(layout.layer_info(1).load_mapping.is_none());
layout.redo();
assert_eq!(layout.layer_info(1).device_link, Some(link));
assert_eq!(layout.layer_info(1).load_mapping, Some(link));
layout.set_device_link(1, None).unwrap();
assert!(layout.layer_info(1).device_link.is_none());
assert!(layout.layer_info(1).load_mapping.is_none());
for text in [
include_str!("../../../docs/interfaces/canvas-pilot-v4.example.json"),
include_str!("../../../docs/interfaces/canvas-pilot-v5.example.json"),
] {
let p = Project::from_json(text).unwrap();
assert_eq!(p.version, 18);
assert!(p.layers.iter().all(|l| l.device_link.is_none()));
assert_eq!(p.version, 22);
assert!(p.layers.iter().all(|l| l.load_mapping.is_none()));
}
let mut value = serde_json::to_value(&project).unwrap();
value["layers"][1]["device_link"]["screen"] = "../2".into();
value["layers"][1]["load_mapping"]["screen"] = "../2".into();
assert!(Project::from_json(&value.to_string()).is_err());
value["layers"][1]["device_link"] = serde_json::Value::Null;
value["layers"][1]["load_mapping"] = serde_json::Value::Null;
value["layers"][1]
.as_object_mut()
.unwrap()
.remove("device_link");
.remove("load_mapping");
assert!(Project::from_json(&value.to_string()).is_err());
}
@ -311,7 +304,7 @@ fn position_point_schema_migrates_corners_and_rejects_mislabeled_files() {
.unwrap();
old["editor"]["position_corner"] = name.into();
let loaded = Project::from_json(&old.to_string()).unwrap();
assert_eq!(loaded.version, 18);
assert_eq!(loaded.version, 22);
assert_eq!(loaded.editor.position_point, expected);
old["editor"]["position_corner"] = "center".into();
assert!(Project::from_json(&old.to_string()).is_err());
@ -320,7 +313,7 @@ fn position_point_schema_migrates_corners_and_rejects_mislabeled_files() {
assert!(Project::from_json(&old.to_string()).is_err());
}
let value: serde_json::Value = serde_json::from_str(&current.to_json().unwrap()).unwrap();
for version in [0, 19] {
for version in [0, 23] {
let mut invalid = value.clone();
invalid["version"] = version.into();
assert!(
@ -361,7 +354,7 @@ fn backdrop_title_roundtrips_and_older_projects_gain_the_default() {
}
let old = include_str!("../../../docs/interfaces/canvas-pilot-v6.example.json");
let migrated = Project::from_json(old).unwrap();
assert_eq!(migrated.version, 18);
assert_eq!(migrated.version, 22);
assert_eq!(migrated.editor.backdrop_title, DEFAULT_BACKDROP_TITLE);
let mut invalid: serde_json::Value = serde_json::from_str(old).unwrap();
invalid["editor"]["backdrop_title"] = "Unexpected".into();
@ -432,7 +425,7 @@ fn saved_pivots_roundtrip_and_old_projects_default_to_center() {
assert_eq!(loaded.layer_info(0).pivot, custom);
assert_eq!(loaded.layer_info(1).pivot, [0.5; 2]);
let example = include_str!("../../../docs/interfaces/canvas-pilot-v9.example.json");
assert_eq!(Project::from_json(example).unwrap().version, 18);
assert_eq!(Project::from_json(example).unwrap().version, 22);
let old = include_str!("../../../docs/interfaces/canvas-pilot-v8.example.json");
let migrated = Project::from_json(old).unwrap();
assert!(migrated.layers.iter().all(|l| l.pivot == [0.5; 2]));
@ -454,6 +447,65 @@ fn saved_pivots_roundtrip_and_old_projects_default_to_center() {
assert!(Project::from_json(&value.to_string()).is_err());
}
#[test]
fn aspect_ratio_lock_is_per_layer_undoable_and_migrates_from_v20() {
let mut layout = Layout::default();
layout.set_keep_aspect_ratio(0, false).unwrap();
assert!(!layout.layer_info(0).keep_aspect_ratio);
assert!(layout.layer_info(1).keep_aspect_ratio);
layout.undo();
assert!(layout.layer_info(0).keep_aspect_ratio);
layout.redo();
assert!(!layout.layer_info(0).keep_aspect_ratio);
let project = Project::from_json(&Project::from_layout(&layout).to_json().unwrap()).unwrap();
assert!(!project.layers[0].keep_aspect_ratio);
assert!(project.layers[1].keep_aspect_ratio);
assert_eq!(
Project::from_json(include_str!(
"../../../docs/interfaces/canvas-pilot-v22.example.json"
))
.unwrap()
.version,
22
);
let mut old: serde_json::Value = serde_json::from_str(include_str!(
"../../../docs/interfaces/canvas-pilot-v20.example.json"
))
.unwrap();
old["editor"]["keep_aspect_ratio"] = false.into();
let migrated = Project::from_json(&old.to_string()).unwrap();
assert!(migrated.layers.iter().all(|layer| !layer.keep_aspect_ratio));
let mut missing = serde_json::to_value(project).unwrap();
missing["layers"][0]
.as_object_mut()
.unwrap()
.remove("keep_aspect_ratio");
assert!(Project::from_json(&missing.to_string()).is_err());
}
#[test]
fn forced_pixel_snapping_migrates_from_v21_and_is_strict() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-v21.example.json");
let current = include_str!("../../../docs/interfaces/canvas-pilot-v22.example.json");
assert_eq!(
Project::from_json(old).unwrap(),
Project::from_json(current).unwrap()
);
let mut project = Project::from_json(current).unwrap();
project.workspace.snapping.force_pixels = true;
assert_eq!(
Project::from_json(&project.to_json().unwrap()).unwrap(),
project
);
let mut mislabeled = serde_json::to_value(project).unwrap();
mislabeled["version"] = 21.into();
assert!(Project::from_json(&mislabeled.to_string()).is_err());
}
#[test]
fn reference_collection_migrates_single_images_and_rejects_mislabeled_or_oversized_collections() {
use base64::{Engine, engine::general_purpose::STANDARD};
@ -464,7 +516,7 @@ fn reference_collection_migrates_single_images_and_rejects_mislabeled_or_oversiz
let reference = serde_json::json!({"name":"guide.png","image_base64":STANDARD.encode(b"image bytes"),"visible":false,"opacity":0.4,"preserve_ratio":true,"native_size":false,"offset":[0.0,0.0]});
old["reference"] = reference.clone();
let migrated = Project::from_json(&old.to_string()).unwrap();
assert_eq!(migrated.version, 18);
assert_eq!(migrated.version, 22);
assert_eq!(migrated.references.len(), 1);
assert!(!migrated.references[0].visible);
assert_eq!(migrated.references[0].opacity, 0.4);
@ -484,7 +536,7 @@ fn reference_collection_migrates_single_images_and_rejects_mislabeled_or_oversiz
gallery.references = vec![migrated.references[0].clone(); 33];
assert!(gallery.to_json().unwrap_err().contains("32 reference"));
let example = include_str!("../../../docs/interfaces/canvas-pilot-v10.example.json");
assert_eq!(Project::from_json(example).unwrap().version, 18);
assert_eq!(Project::from_json(example).unwrap().version, 22);
}
#[test]
@ -607,64 +659,19 @@ fn workspace_roundtrip_migration_and_validation() {
assert!(Project::from_json(&missing.to_string()).is_err());
}
#[test]
fn input_proposals_migrate_validate_and_require_explicit_version_16() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-v15.example.json");
let migrated = Project::from_json(old).unwrap();
assert_eq!(migrated.version, 18);
assert!(migrated.input_proposals.is_empty());
let fixture = include_str!("../../../docs/interfaces/canvas-pilot-v16.example.json");
let project = Project::from_json(fixture).unwrap();
assert_eq!(project.input_proposals.len(), 1);
assert_eq!(
Project::from_json(&project.to_json().unwrap()).unwrap(),
project
);
let mut json = serde_json::to_value(&project).unwrap();
json.as_object_mut().unwrap().remove("input_proposals");
assert!(Project::from_json(&json.to_string()).is_err());
for (pointer, value) in [
("/version", serde_json::json!(15)),
("/input_proposals/0/layer_id", serde_json::json!(999)),
(
"/input_proposals/0/input",
serde_json::json!("INPUT_4/../../source"),
),
("/input_proposals/0/plug", serde_json::json!("0")),
(
"/input_proposals/0/device_link/layer",
serde_json::json!("999"),
),
(
"/input_proposals/0/settings/aspect~1pp~1customRatio",
serde_json::json!(0),
),
] {
let mut invalid = serde_json::to_value(&project).unwrap();
*invalid.pointer_mut(pointer).unwrap() = value;
assert!(
Project::from_json(&invalid.to_string()).is_err(),
"{pointer}"
);
}
let mut invalid = project.clone();
invalid.input_proposals[0]
.settings
.insert("source/pp/input".into(), serde_json::json!("INPUT_9"));
assert!(invalid.to_json().is_err());
let mut duplicate = project.clone();
duplicate
.input_proposals
.push(project.input_proposals[0].clone());
assert!(duplicate.to_json().is_err());
}
#[test]
fn mask_snapping_migration_and_strict_round_trip() {
let old = include_str!("../../../docs/interfaces/canvas-pilot-v17.example.json");
let current = include_str!("../../../docs/interfaces/canvas-pilot-v18.example.json");
let mut project = Project::from_json(old).unwrap();
assert_eq!(project, Project::from_json(current).unwrap());
let mut project = canvas_pilot::project_recovery::from_json(old)
.unwrap()
.project;
assert_eq!(
project,
canvas_pilot::project_recovery::from_json(current)
.unwrap()
.project
);
assert!(!project.workspace.snapping.mask_edges);
project.workspace.snapping.mask_edges = true;
assert_eq!(
@ -674,7 +681,7 @@ fn mask_snapping_migration_and_strict_round_trip() {
let mut value = serde_json::to_value(project).unwrap();
value["version"] = 17.into();
assert!(Project::from_json(&value.to_string()).is_err());
value["version"] = 18.into();
value["version"] = 20.into();
value["workspace"]["snapping"]
.as_object_mut()
.unwrap()

View File

@ -0,0 +1,139 @@
use canvas_pilot::{Layout, project::Project, project_recovery::from_json};
use serde_json::json;
fn value() -> serde_json::Value {
serde_json::to_value(Project::from_layout(&Layout::default())).unwrap()
}
#[test]
fn valid_project_round_trip_is_exact_without_warnings_or_retired_fields() {
let project = Project::from_layout(&Layout::default());
let text = project.to_json().unwrap();
assert!(!text.contains("input_crop"));
assert!(!text.contains("input_proposals"));
let loaded = from_json(&text).unwrap();
assert!(loaded.warnings.is_empty());
assert_eq!(loaded.project, project);
assert_eq!(loaded.project.version, 22);
}
#[test]
fn bad_layer_does_not_discard_valid_geometry_and_invalid_selection_is_reset() {
let mut v = value();
let expected = v["layers"][1].clone();
v["layers"][0]["bounds"]["width"] = json!(-1);
v["editor"]["selected_layer_ids"] = json!([v["layers"][0]["id"]]);
let loaded = from_json(&v.to_string()).unwrap();
assert_eq!(loaded.project.layers.len(), 1);
assert_eq!(
serde_json::to_value(&loaded.project.layers[0]).unwrap(),
expected
);
assert!(loaded.project.editor.selected_layer_ids.is_empty());
assert!(
loaded
.warnings
.iter()
.any(|w| w.contains("Layer row 1 skipped"))
);
loaded.project.to_json().unwrap();
}
#[test]
fn invalid_optional_layer_settings_preserve_geometry_and_valid_names() {
let mut v = value();
v["layers"][0]["name"] = json!("Keep this name");
v["layers"][0]["mask"]["left"] = json!(99);
v["layers"][0]["load_mapping"] = json!({"invalid":true});
v["layers"][1]["advanced_crop"]["left"] = json!(-1);
v["editor"]["viewport_zoom"] = json!(0);
v["workspace"]["capture_interval_seconds"] = json!(0);
let loaded = from_json(&v.to_string()).unwrap();
assert_eq!(loaded.project.layers.len(), 2);
assert_eq!(loaded.project.layers[0].name, "Keep this name");
assert_eq!(loaded.project.layers[0].mask, Default::default());
assert!(loaded.project.layers[0].load_mapping.is_none());
assert!(loaded.warnings.iter().any(|w| w.contains("mask")));
for (actual, original) in loaded
.project
.layers
.iter()
.zip(v["layers"].as_array().unwrap())
{
assert_eq!(
serde_json::to_value(actual.bounds).unwrap(),
original["bounds"]
);
}
loaded.project.to_json().unwrap();
}
#[test]
fn missing_source_skips_its_consumers_and_sparse_ids_are_remapped() {
let mut v = value();
v["inputs"][0]["native_resolution"]["width"] = json!(0);
v["inputs"][1]["id"] = json!(800);
v["layers"][1]["source_id"] = json!(800);
let loaded = from_json(&v.to_string()).unwrap();
assert_eq!(loaded.project.inputs.len(), 1);
assert_eq!(loaded.project.layers.len(), 1);
assert_eq!(loaded.project.layers[0].source_id, 1);
assert_eq!(loaded.project.inputs[0].id, 1);
loaded.project.layout().unwrap();
}
#[test]
fn removed_precrop_and_proposals_are_reported_and_never_resaved() {
let mut v = value();
v["version"] = json!(19);
v["input_proposals"] = json!([{"arbitrary":"old proposal"}]);
for input in v["inputs"].as_array_mut().unwrap() {
input["input_crop"] = json!({"left":0,"right":0,"top":40,"bottom":40});
}
assert!(Project::from_json(&v.to_string()).is_err());
let loaded = from_json(&v.to_string()).unwrap();
assert!(loaded.warnings.iter().any(|w| w.contains("proposals")));
assert!(loaded.warnings.iter().any(|w| w.contains("pre-crop")));
let text = loaded.project.to_json().unwrap();
assert!(!text.contains("input_crop"));
assert!(!text.contains("input_proposals"));
}
#[test]
fn unsupported_unparseable_or_empty_projects_are_not_invented() {
assert!(from_json("{broken").is_err());
for (key, bad) in [
("version", json!(999)),
("format", json!("other")),
("layers", json!([])),
("inputs", json!([])),
] {
let mut v = value();
v[key] = bad;
assert!(from_json(&v.to_string()).is_err(), "{key}");
}
let mut v = value();
v["layers"][0]["id"] = json!(u64::MAX);
v["layers"][1]["id"] = json!(0);
assert!(from_json(&v.to_string()).is_err());
}
#[test]
fn invalid_embedded_images_do_not_prevent_geometry_recovery() {
let mut v = value();
v["references"] = json!([{"name":"bad", "image_base64":"invalid!", "visible":true, "opacity":1.0, "preserve_ratio":true, "native_size":false, "offset":[0.0,0.0]}]);
let loaded = from_json(&v.to_string()).unwrap();
assert_eq!(loaded.project.layers.len(), 2);
assert!(loaded.project.references.is_empty());
assert!(loaded.warnings.iter().any(|w| w.contains("references")));
}
#[test]
fn strict_legacy_reader_does_not_silently_drop_malformed_retired_settings() {
let mut v = value();
v["version"] = json!(19);
v["input_proposals"] = json!({"unexpected":"object"});
assert!(Project::from_json(&v.to_string()).is_err());
let loaded = from_json(&v.to_string()).unwrap();
assert!(loaded.warnings.iter().any(|w| w.contains("proposals")));
loaded.project.layout().unwrap();
}

View File

@ -0,0 +1,490 @@
use canvas_pilot::{DeviceLink, Geometry, Layout, project::Project, size_presets::SizePreset};
fn close(a: f64, b: f64) {
assert!((a - b).abs() < 1e-8, "{a} != {b}");
}
#[test]
fn full_screen_and_nine_quarter_positions_use_exact_output_dimensions() {
let mut layout = Layout::default();
layout.set_output([1919, 1079]).unwrap();
layout.select(Some(0));
let unselected = layout.layers()[1];
for row in 0..3 {
for column in 0..3 {
let before = Project::from_layout(&layout);
layout
.apply_size_preset(SizePreset::Quarter { column, row })
.unwrap();
let g = layout.layers()[0];
assert_eq!(
g,
Geometry {
x: column as f64 * 479.75,
y: row as f64 * 269.75,
width: 959.5,
height: 539.5
}
);
assert_eq!(layout.layers()[1], unselected);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
}
layout.set_selection([true, true]);
let before = Project::from_layout(&layout);
layout.apply_size_preset(SizePreset::Fullscreen).unwrap();
for g in layout.layers() {
assert_eq!(
*g,
Geometry {
x: 0.0,
y: 0.0,
width: 1919.0,
height: 1079.0
}
);
}
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(layout.layers()[0], layout.layers()[1]);
}
#[test]
fn tiling_follows_folder_list_order_and_repeats_cells_without_reordering() {
let mut layout = Layout::default();
for _ in 0..4 {
layout.add_layer().unwrap();
}
layout.assign_folder(&[1, 4], "Cameras").unwrap();
layout.set_selection([true; 6]);
layout
.set_device_link(
0,
Some(DeviceLink {
family: Default::default(),
screen: "1".into(),
layer: "1".into(),
}),
)
.unwrap();
layout
.set_mask(
0,
canvas_pilot::formats::Mask {
left: 0.1,
..Default::default()
},
)
.unwrap();
let before = Project::from_layout(&layout);
let formats = layout.formats().clone();
let identities: Vec<_> = (0..6).map(|i| layout.layer_info(i).clone()).collect();
layout
.apply_size_preset(SizePreset::Tiles {
columns: 2,
rows: 2,
})
.unwrap();
for (slot, id) in [6, 5, 4, 1, 3, 2].into_iter().enumerate() {
let i = (0..6).find(|&i| layout.layer_info(i).id == id).unwrap();
assert_eq!(
layout.layers()[i],
Geometry {
x: (slot % 2) as f64 * 960.0,
y: ((slot % 4) / 2) as f64 * 540.0,
width: 960.0,
height: 540.0
}
);
}
assert_eq!(layout.formats().sources, formats.sources);
assert_eq!(layout.formats().source_for, formats.source_for);
assert_eq!(layout.formats().masks, formats.masks);
assert_eq!(layout.formats().layer_fit, formats.layer_fit);
assert_eq!(
(0..6)
.map(|i| layout.layer_info(i).clone())
.collect::<Vec<_>>(),
identities
);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
}
#[test]
fn halves_and_fractional_tiling_preserve_grid_edges() {
let mut layout = Layout::default();
layout.set_selection([true, true]);
layout
.apply_size_preset(SizePreset::Tiles {
columns: 1,
rows: 2,
})
.unwrap();
assert_eq!(
layout.layers()[1],
Geometry {
x: 0.0,
y: 0.0,
width: 1920.0,
height: 540.0
}
);
assert_eq!(layout.layers()[0].y, 540.0);
layout
.apply_size_preset(SizePreset::Tiles {
columns: 2,
rows: 1,
})
.unwrap();
assert_eq!(
layout.layers()[1],
Geometry {
x: 0.0,
y: 0.0,
width: 960.0,
height: 1080.0
}
);
assert_eq!(layout.layers()[0].x, 960.0);
layout.add_layer().unwrap();
layout.set_selection([true; 3]);
layout.set_output([1001, 777]).unwrap();
layout
.apply_size_preset(SizePreset::Tiles {
columns: 3,
rows: 1,
})
.unwrap();
close(layout.layers()[0].x + layout.layers()[0].width, 1001.0);
close(
layout.layers()[1].x + layout.layers()[1].width,
layout.layers()[0].x,
);
close(layout.layers()[2].width, 1001.0 / 3.0);
}
#[test]
fn orientation_changes_only_dimensions_and_repeated_orientation_is_noop() {
let mut layout = Layout::default();
layout.set_selection([true, true]);
let original = layout.layers().clone();
let formats = layout.formats().clone();
layout.apply_size_preset(SizePreset::Portrait).unwrap();
for (i, g) in layout.layers().iter().enumerate() {
assert_eq!([g.x, g.y], [original[i].x, original[i].y]);
assert_eq!([g.width, g.height], [original[i].height, original[i].width]);
}
layout.apply_size_preset(SizePreset::Portrait).unwrap();
layout.undo();
assert_eq!(*layout.layers(), original);
assert_eq!(*layout.formats(), formats);
layout.redo();
layout.apply_size_preset(SizePreset::Landscape).unwrap();
assert_eq!(*layout.layers(), original);
}
#[test]
fn preset_validation_and_hidden_locked_layers_cannot_partially_change_document() {
let mut layout = Layout::default();
layout.set_selection([true, true]);
let before = Project::from_layout(&layout);
for preset in [
SizePreset::Tiles {
columns: 0,
rows: 2,
},
SizePreset::Tiles {
columns: 257,
rows: 1,
},
SizePreset::Quarter { column: 1, row: 1 },
] {
assert!(layout.apply_size_preset(preset).is_err());
assert_eq!(Project::from_layout(&layout), before);
}
layout.set_locked(0, true);
let protected = layout.layers()[0];
layout.apply_size_preset(SizePreset::Fullscreen).unwrap();
assert_eq!(layout.layers()[0], protected);
layout.set_visible(1, false);
assert!(layout.apply_size_preset(SizePreset::Fullscreen).is_err());
layout.set_visible(1, true);
layout.select(Some(1));
assert!(
layout
.apply_size_preset(SizePreset::Quarter { column: 3, row: 0 })
.is_err()
);
}
#[test]
fn crop_presets_trim_current_picture_without_scaling_and_round_trip() {
use canvas_pilot::formats::{Aspect, Framing, LayerFit};
for fit in [
None,
Some(LayerFit::Fullscreen),
Some(LayerFit::Centered),
Some(LayerFit::Cropped),
Some(LayerFit::OneToOne),
] {
for (aspect, width, edge) in [
(Aspect::FourThree, 1440.0, 240.0),
(Aspect::SixteenTen, 1728.0, 96.0),
] {
let mut layout = Layout::default();
layout.select(Some(0));
layout.apply_size_preset(SizePreset::Fullscreen).unwrap();
layout.set_layer_fit(0, fit, Default::default()).unwrap();
let before = Project::from_layout(&layout);
layout
.apply_crop_preset_with_existing(aspect, true)
.unwrap();
let g = layout.layers()[0];
close(g.x, edge);
close(g.y, 0.0);
close(g.width, width);
close(g.height, 1080.0);
let f = layout.formats();
close(f.advanced[0].left, edge);
close(f.advanced[0].right, edge);
close(f.advanced[0].top, 0.0);
assert_eq!(f.layer_fit[0], fit);
let after = Project::from_layout(&layout);
assert_eq!(
Project::from_json(&after.to_json().unwrap()).unwrap(),
after
);
layout
.apply_crop_preset_with_existing(aspect, true)
.unwrap();
assert_eq!(Project::from_layout(&layout), after);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(Project::from_layout(&layout), after);
}
}
// Existing off-center framing is trimmed in place, not reset or recentered.
let mut layout = Layout::default();
layout.select(Some(0));
layout
.set_framing(
0,
Framing {
zoom: 2.0,
offset: [30.0, -10.0],
},
)
.unwrap();
let old = layout.layers()[0];
let crop = layout.formats().advanced[0];
let scale = layout.formats().mapping(0, old).unwrap().scale;
layout
.apply_crop_preset_with_existing(Aspect::FourThree, true)
.unwrap();
let new = layout.layers()[0];
close(layout.formats().mapping(0, new).unwrap().scale, scale);
close(
layout.formats().advanced[0].left,
crop.left + (old.width - new.width) / 2.0 / scale,
);
close(layout.formats().advanced[0].top, crop.top);
}
#[test]
fn crop_presets_letterbox_multi_selection_matching_ratio_and_errors() {
use canvas_pilot::formats::Aspect;
let mut layout = Layout::default();
layout.select(Some(0));
layout
.apply(
0,
Geometry {
x: 13.25,
y: 27.5,
width: 800.0,
height: 600.0,
},
)
.unwrap();
layout.set_selection([true, true]);
let before = Project::from_layout(&layout);
let same = layout.layers()[1];
let same_crop = layout.formats().advanced[1];
let old_crop = layout.formats().advanced[0];
let old_scale = layout
.formats()
.mapping(0, layout.layers()[0])
.unwrap()
.scale;
layout
.apply_crop_preset_with_existing(Aspect::SixteenNine, true)
.unwrap();
assert_eq!(
layout.layers()[0],
Geometry {
x: 13.25,
y: 102.5,
width: 800.0,
height: 450.0
}
);
close(
layout.formats().advanced[0].top,
old_crop.top + 75.0 / old_scale,
);
assert_eq!(layout.layers()[1], same);
assert_eq!(layout.formats().advanced[1], same_crop);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
assert!(
layout
.apply_crop_preset_with_existing(Aspect::Custom, true)
.is_err()
);
assert_eq!(Project::from_layout(&layout), before);
layout.select(None);
assert!(
layout
.apply_crop_preset_with_existing(Aspect::FourThree, true)
.is_err()
);
}
#[test]
fn proportional_presets_fit_each_layer_and_undo_as_one_edit() {
for (preset, columns, rows) in [
(SizePreset::Fullscreen, 1, 1),
(
SizePreset::Tiles {
columns: 1,
rows: 2,
},
1,
2,
),
(
SizePreset::Tiles {
columns: 2,
rows: 1,
},
2,
1,
),
(
SizePreset::Tiles {
columns: 3,
rows: 2,
},
3,
2,
),
] {
let mut layout = Layout::default();
layout.set_output([1919, 1079]).unwrap();
layout.select(Some(0));
layout
.apply(
0,
Geometry {
x: 10.0,
y: 20.0,
width: 300.0,
height: 600.0,
},
)
.unwrap();
layout.set_selection([true, true]);
let before = Project::from_layout(&layout);
let original = layout.layers().clone();
layout
.apply_size_preset_with_proportions(preset, true)
.unwrap();
for (position, i) in [1, 0].into_iter().enumerate() {
let g = layout.layers()[i];
let w = 1919.0 / columns as f64;
let h = 1079.0 / rows as f64;
let cell = position % (columns * rows);
close(g.width / g.height, original[i].width / original[i].height);
close(g.x + g.width / 2.0, (cell % columns) as f64 * w + w / 2.0);
close(g.y + g.height / 2.0, (cell / columns) as f64 * h + h / 2.0);
assert!(g.width <= w + 1e-8 && g.height <= h + 1e-8);
assert!((g.width - w).abs() < 1e-8 || (g.height - h).abs() < 1e-8);
}
let after = Project::from_layout(&layout);
layout.undo();
assert_eq!(Project::from_layout(&layout), before);
layout.redo();
assert_eq!(Project::from_layout(&layout), after);
}
}
#[test]
fn proportional_quarters_center_in_all_nine_regions_and_orientation_stays_explicit() {
let mut layout = Layout::default();
layout.select(Some(0));
layout
.apply(
0,
Geometry {
x: 0.0,
y: 0.0,
width: 600.0,
height: 600.0,
},
)
.unwrap();
for row in 0..3 {
for column in 0..3 {
layout
.apply_size_preset_with_proportions(SizePreset::Quarter { column, row }, true)
.unwrap();
assert_eq!(
layout.layers()[0],
Geometry {
x: column as f64 * 480.0 + 210.0,
y: row as f64 * 270.0,
width: 540.0,
height: 540.0,
}
);
}
}
layout.apply_size_preset(SizePreset::Fullscreen).unwrap();
layout
.apply_size_preset_with_proportions(SizePreset::Portrait, true)
.unwrap();
assert_eq!(
[layout.layers()[0].width, layout.layers()[0].height],
[1080.0, 1920.0]
);
}
#[test]
fn replacing_crop_ratio_restores_bounds_while_opt_in_keeps_trimming() {
use canvas_pilot::formats::Aspect;
let mut layout = Layout::default();
layout.select(Some(0));
layout.apply_size_preset(SizePreset::Fullscreen).unwrap();
let original = Project::from_layout(&layout);
layout.apply_crop_preset(Aspect::FourThree).unwrap();
let cropped = Project::from_layout(&layout);
layout.apply_crop_preset(Aspect::SixteenTen).unwrap();
close(layout.layers()[0].width, 1728.0);
close(layout.layers()[0].height, 1080.0);
layout.undo();
assert_eq!(Project::from_layout(&layout), cropped);
layout.apply_crop_preset(Aspect::SixteenNine).unwrap();
assert_eq!(Project::from_layout(&layout), original);
layout.apply_crop_preset(Aspect::FourThree).unwrap();
layout
.apply_crop_preset_with_existing(Aspect::SixteenNine, true)
.unwrap();
close(layout.layers()[0].width, 1440.0);
close(layout.layers()[0].height, 810.0);
layout.apply_crop_preset(Aspect::SixteenNine).unwrap();
assert_eq!(Project::from_layout(&layout), original);
}

View File

@ -3,11 +3,12 @@ use canvas_pilot::{Layout, snapping::Snapping};
#[test]
fn screen_snapping_recomputes_from_original_and_is_one_undo_step() {
let mut layout = Layout::default();
layout.set_visible(0, false);
let before = layout.layers().clone();
let formats = layout.formats().clone();
let options = Snapping {
enabled: true,
layer_edges: false,
layer_edges: true,
..Default::default()
};
layout.start_drag([1200.0, 200.0]);
@ -75,25 +76,26 @@ fn group_snapping_preserves_spacing_and_cancel_restores_geometry() {
assert_eq!(layout.layers()[0].x, 3.0);
}
#[test]
fn pixel_snap_can_be_disabled_and_numeric_entry_bypasses_it() {
fn pixel_snap_is_soft_and_optional_while_numeric_entry_bypasses_it() {
let mut layout = Layout::default();
let mut g = layout.layers()[1];
g.x = 1160.25;
layout.apply(1, g).unwrap();
for pixels in [false, true] {
let options = |pixels| Snapping {
enabled: true,
pixels,
screen_edges: false,
layer_edges: false,
..Default::default()
};
for (pixels, pointer, expected) in [
(false, 1199.9, 1160.15),
(true, 1199.9, 1160.0),
(true, 1200.2, 1160.45),
] {
layout.start_drag([1200.0, 200.0]);
layout.drag_to_snapped(
[1200.2, 200.0],
Snapping {
enabled: true,
pixels,
screen_edges: false,
layer_edges: false,
..Default::default()
},
6.0,
);
assert!((layout.layers()[1].x - if pixels { 1160.0 } else { 1160.45 }).abs() < 1e-8);
layout.drag_to_snapped([pointer, 200.0], options(pixels), 6.0);
assert!((layout.layers()[1].x - expected).abs() < 1e-8);
layout.cancel_drag();
assert_eq!(layout.layers()[1], g);
}
@ -141,6 +143,7 @@ fn resize_can_bypass_snapping_and_cancel() {
let options = Snapping {
enabled: true,
pixels: false,
force_pixels: false,
screen_edges: true,
layer_edges: false,
..Default::default()
@ -563,12 +566,13 @@ fn screen_quarters_snap_moving_edges_and_centers_and_survive_release() {
let options = Snapping {
enabled: true,
pixels: false,
layer_edges: false,
layer_edges: true,
..Default::default()
};
for fraction in [0.25, 0.5, 0.75] {
for anchor in [0.0, 0.5, 1.0] {
let mut layout = Layout::default();
layout.set_visible(0, false);
let g = layout.layers()[1];
let target = [1920.0 * fraction, 1080.0 * fraction];
let point = [
@ -646,8 +650,9 @@ fn overlay_grid_snaps_moves_resizes_and_pivots_with_fractional_divisions() {
let options = Snapping {
enabled: true,
pixels: false,
force_pixels: false,
screen_edges: false,
layer_edges: false,
layer_edges: true,
grid: true,
show_grid: false,
grid_divisions: [7, 5],
@ -710,7 +715,7 @@ fn mask_options() -> Snapping {
enabled: true,
pixels: false,
screen_edges: false,
layer_edges: false,
layer_edges: true,
mask_edges: true,
..Default::default()
}
@ -934,6 +939,207 @@ fn mask_targets_follow_all_fit_modes_and_skip_letterbox_space() {
);
assert_eq!(actual, expected, "{fit:?} {origin:?}");
assert_eq!(guides, expected.map(Some));
let high = [
(g.x + g.width)
.min(mask.x + mask.width)
.min(picture.x + picture.width),
(g.y + g.height)
.min(mask.y + mask.height)
.min(picture.y + picture.height),
];
let center = std::array::from_fn(|axis| (expected[axis] + high[axis]) / 2.0);
assert_eq!(
layout.snap_pivot(1, center.map(|v| v + 2.0), mask_options(), 6.0, None, false),
(center, center.map(Some)),
"{fit:?} {origin:?}"
);
}
}
}
#[test]
fn mask_centers_snap_pivots_resizes_and_moves_and_respect_visibility() {
use canvas_pilot::{
ResizeHandle,
formats::{Mask, MaskOrigin},
};
for origin in [MaskOrigin::Layer, MaskOrigin::Source] {
let mut layout = Layout::default();
layout
.set_mask(
0,
Mask {
origin,
right: 0.25,
..Default::default()
},
)
.unwrap();
layout.set_locked(0, true);
// Visible mask spans x=120..600; its center is 360, not the layer's 440.
let options = mask_options();
assert_eq!(
layout.snap_pivot(1, [362.0, 362.0], options, 6.0, None, false),
([360.0, 360.0], [Some(360.0), Some(360.0)])
);
layout.start_handle_resize(1, ResizeHandle::Left, [1160.0, 360.0], false);
assert_eq!(
layout.drag_to_snapped([362.0, 360.0], options, 6.0)[0],
Some(360.0)
);
assert_eq!(layout.layers()[1].x, 360.0);
layout.cancel_drag();
// A whole layer's center can also align to the visible mask center.
layout.start_drag([1200.0, 200.0]);
assert_eq!(
layout.drag_to_snapped([82.0, 200.0], options, 6.0)[0],
Some(360.0)
);
assert_eq!(layout.layers()[1].center()[0], 360.0);
layout.cancel_drag();
for hidden in [false, true] {
layout.set_visible(0, !hidden);
for enabled in [false, true] {
let options = Snapping {
mask_edges: enabled,
..options
};
assert_eq!(
layout
.snap_pivot(1, [362.0, 362.0], options, 6.0, None, false)
.1,
if enabled && !hidden {
[Some(360.0); 2]
} else {
[None; 2]
}
);
}
}
}
}
#[test]
fn moving_mask_center_aligns_to_masks_screen_and_grid_with_rigid_groups_and_undo() {
use canvas_pilot::formats::Mask;
let mut layout = Layout::default();
layout
.set_mask(
0,
Mask {
right: 0.375,
..Default::default()
},
)
.unwrap();
layout
.set_mask(
1,
Mask {
left: 0.25,
..Default::default()
},
)
.unwrap();
let before = layout.layers().clone();
let formats = layout.formats().clone();
layout.start_drag([1200.0, 200.0]);
assert_eq!(
layout.drag_to_snapped([-37.0, 200.0], mask_options(), 6.0)[0],
Some(320.0)
);
assert_eq!(
layout
.formats()
.mask_bounds(1, layout.layers()[1])
.unwrap()
.center()[0],
320.0
);
layout.finish_drag();
assert_eq!(*layout.formats(), formats);
layout.undo();
assert_eq!(*layout.layers(), before);
layout.set_selection([true, true]);
for grid in [false, true] {
layout.start_drag([1200.0, 200.0]);
let options = Snapping {
screen_edges: !grid,
grid,
grid_divisions: [2, 2],
..mask_options()
};
assert_eq!(
layout.drag_to_snapped([603.0, 200.0], options, 6.0)[0],
Some(960.0)
);
assert_eq!(
layout
.formats()
.mask_bounds(1, layout.layers()[1])
.unwrap()
.center()[0],
960.0
);
assert_eq!(
layout.layers()[1].x - layout.layers()[0].x,
before[1].x - before[0].x
);
layout.cancel_drag();
assert_eq!(*layout.layers(), before);
assert_eq!(*layout.formats(), formats);
}
}
#[test]
fn layer_borders_and_mask_anchors_can_be_disabled_independently() {
use canvas_pilot::formats::Mask;
for borders in [false, true] {
for masks in [false, true] {
let mut layout = Layout::default();
layout.select(Some(1));
layout
.set_mask(
1,
Mask {
left: 0.25,
right: 0.1,
..Default::default()
},
)
.unwrap();
let g = layout.layers()[1];
let formats = layout.formats().clone();
let options = Snapping {
enabled: true,
pixels: false,
screen_edges: true,
layer_edges: borders,
mask_edges: masks,
..Default::default()
};
// Outer border near screen edge; masked edges and both centers are far away.
layout.start_drag([g.x, g.y]);
let guides = layout.drag_to_snapped([2.0, g.y + 17.0], options, 6.0);
assert_eq!(guides[0], borders.then_some(0.0));
assert_eq!(layout.layers()[1].x, if borders { 0.0 } else { 2.0 });
layout.cancel_drag();
// Mask's left edge near screen edge; outer border is far from guides.
layout.start_drag([g.x, g.y]);
let guides = layout.drag_to_snapped(
[-158.0, g.y + 17.0],
Snapping {
screen_edges: true,
layer_edges: false,
..options
},
6.0,
);
assert_eq!(guides[0], masks.then_some(0.0));
assert_eq!(layout.layers()[1].x, if masks { -160.0 } else { -158.0 });
layout.cancel_drag();
assert_eq!(layout.layers()[1], g);
assert_eq!(*layout.formats(), formats);
}
}
}

View File

@ -21,7 +21,71 @@ Synthetic tests cover model identity agreement, cross-model rejection, firmware
warnings and Preview/Program send planning. These do not establish actual older
firmware compatibility or extend the Cmax emulator evidence below to other models.
## Current acceptance
## Rectangular-mask acceptance — RS1 6.2.79, 2026-11-17
The local simulator identifies as **AQL RS1, standalone, firmware 6.2.79**.
Canvas Pilot's HTTP identity and bounded AWJ connection succeeded. The previously
recorded remote emulator endpoint did not respond; no remote-device writes were made.
Rectangular blanking now imports and sends using `cropping.mask.pp` without
resizing the image or converting blanking to source crop. Both Layer and Source
editor origins convert to the device container; import returns a Layer-relative
mask on the visible centered image. See the [mask contract](../interfaces/device-adapters.md#mask-appearance).
Cut & Fill/keying, explicit layer-fit sends and physical-output acceptance remain
outside this result.
**96 combinations passed across the completed checks:** Preview/Program ×
Output-sized/Source aspect × three fractional/portrait/asymmetric-crop layouts
(zoom 1, 2 and 4) × both mask origins × asymmetric blanking, fully blanked
horizontal axis, fully blanked vertical axis and reset-to-zero. Sends passed exact
native-field readback; re-imported image geometry and reveal bounds matched within
one output pixel. The diagnostic temporarily routed S1 layer 1 to LIVE_1;
production sends never route sources, TAKE or alter shared input settings.
The initial combined run was interrupted by the execution environment after 94
successful cases, before its cleanup. The pre-write temporary recovery record
restored and verified all 28 original routing/geometry/crop/mask fields in both
physical banks. The diagnostic now accepts a bank scope: a subsequent Program-only
run passed all 48 cases and verified full targeted screen/auxiliary baseline
restoration. The first run had already passed all 48 Preview cases. This is not
represented as one uninterrupted 96-case run.
A final Preview-only visual check on the final implementation passed mathematical
readback and displayed the expected mask in WebRCS with no captured JavaScript
runtime exceptions. Its native mask values were left **13161**, right **6536**,
top **19560**, bottom **13184**; the rendered clipping percentages were **20.08%**,
**9.97%**, **29.85%**, **20.12%**. The slight difference from requested
20/10/30/20 percent is the expected conversion from fractional editor geometry to
the rounded device container. The baseline was restored and all targeted screen
and auxiliary fields matched afterward.
Final repository checks passed: 467 default-feature tests, 461 in each restricted
configuration, both Clippy configurations, formatting, rustdoc and the pinned
manual build. Whole-application line coverage is 91.72%.
The separate sanitized `aquilon-rs1-mask-6.2.json` regression fixture preserves that
one masked layer and its requested editor geometry/mask. Existing Cmax fixtures
retain their original provenance. WebRCS bundle `app.1a22b5b509cf7c14eb86.js`
(SHA-256 `9233ad54d9c2e0aa2b640bc080aea82c0450d85cd1d855a481533b6de9a67eb5`)
provided the independent mask-unit, opposite-edge-limit and layer-container
reference evidence. Raw simulator state, recovery files and screenshots remain
local temporary artifacts, not repository contents.
The diagnostic saves an exclusive temporary recovery JSON before its first write.
Run banks separately on hosts with execution time limits:
```sh
cargo run --locked -p canvas-pilot --example check_aquilon_send -- --apply-and-restore IP:PORT preview
cargo run --locked -p canvas-pilot --example check_aquilon_send -- --apply-and-restore IP:PORT program
```
The optional `--visual-check-and-restore IP:PORT preview` mode holds an asymmetric
mask for 60 seconds and restores afterward. These are explicitly invoked device
writes, never CI tests. Interrupted processes cannot promise cleanup: preserve the
printed recovery record and restore/verify its captured native fields before
another run. The recovery record contains private device context and stays outside Git.
## Original Cmax acceptance — 2026-11-15
- Identity, bounded targeted AWJ reads, screen/layer allocations and
Preview/Program transition-group resolution work on the emulator.

View File

@ -4,9 +4,688 @@
## Unreleased
### v0.10.10
- Disclose the project's MIT license, LLM-generated or LLM-assisted development,
human review and professional use in the public README.
- The pinned mdBook build passes, validating 25 HTML pages and 1,660 local
links/assets.
### v0.10.9
- Add optional forced whole-pixel snapping for moves, resizes and pivots, with a
temporary Shift+Space modifier. The existing soft pixel magnet remains the default.
### v0.10.8
- Remove inspector Copy/Paste buttons, including the multi-selection Copy button,
while retaining clipboard shortcuts and context-menu actions.
### v0.10.7
- Pre-map geometry imports by exact included-item count: selected layers, their
shared folder, then all available layers. Manual scope and mapping remain available.
### v0.10.6
- Keep the alignment menu open while choosing its target, making **Selected
layers** and individual layer targets usable from both the toolbar and canvas
context menu.
### v0.10.5
- Place **Size presets** before **Output format** and **Viewport options** in the
canvas toolbar, including when toolbar groups wrap onto another row.
### v0.10.4
- Make the selected layer's resolution row toggle its Layer properties window:
click once to open it and again to close it, preserving the existing review
prompt when the window contains unapplied edits.
### v0.10.3
- Tighten the selected-layer inspector spacing around crop, measurement, geometry
and ratio controls, keeping the same controls visible in less vertical space.
### v0.10.2
- Store **Keep aspect ratio when resizing** on each layer, so layers can use
different resize behavior. The choice is undoable, survives reordering and
project round trips, and old project-wide choices migrate to every layer.
### v0.10.1
- Size the right inspector to its visible empty/reference message when no layer is
selected, removing the long blank scroll range while retaining scrolling for
layer properties and long layer/reference lists. Remove the duplicated read-only
**Visible box / center position** block and pull the copy/paste actions upward.
## v0.10.0-rc.18 — 2026-11-19
Published release candidate collecting the extreme-zoom performance fix and
soft whole-pixel canvas placement below. See the
[release notes](../development/release-notes/v0.10.0-rc.18.md) for downloads,
pack contents and validation limits.
### v0.10.0-rc.18
- Make **Pixel edges** a soft whole-pixel preference for mouse movement and
resizing. Coordinates within one quarter pixel settle on the integer after
stronger screen, layer and grid snaps; farther fractional placement remains
available for precise work at high canvas zoom.
- Refresh three yanked transitive packages to their compatible patch releases so
local Cargo installation and release builds resolve without yanked-package warnings.
### v0.10.0-rc.17
- Keep extreme scroll zoom responsive by omitting camera-scaled decorative canvas
text before it would request oversized glyphs from egui's shared font atlas.
Layer geometry, fixed-size layer labels, pixel guides and the existing 256× camera
range remain available for precise placement.
## v0.10.0-rc.16 — 2026-11-19
Published release candidate collecting the crop, preview, input adaptation and
transfer-recovery changes below. See the
[release notes](../development/release-notes/v0.10.0-rc.16.md) for highlights,
pack downloads, compatibility and validation limits.
### v0.10.0-rc.16
- Keep **Convert to Smart crop** and **Convert to Edge crop** on one line in the
layer context menu, allowing the menu to grow to the action label width.
### v0.10.0-rc.15
- Add the inverse **Convert to Edge crop** action to the layer context menu and
Crop properties. Preserve the Smart crop's picture, crop, container and mask,
enter the green edge helper immediately, and return to Smart crop with Undo.
### v0.10.0-rc.14
- Enabling an input preview from the right-click menu or Preview properties queues
its first still immediately, without requiring auto-refresh. Keep capture
cooldown, single-request scheduling and local-picture behavior. UI regression
coverage checks one-shot scheduling, disabling and the cooldown.
### v0.10.0-rc.13
- Tolerate up to one output pixel of device rounding when importing Centered/Cropped
fits. Normalize to an exact Smart crop without moving the container or source
center; preserve larger mismatches and stretched/native modes. Regression tests
include the observed Midra crop fractions that left a 0.036-pixel width gap.
- Import exact device fits as normal Smart crop. Preserve advanced modes for
letterboxing, overflow and stretching, and preserve saved project choices.
- Add green advanced edge-crop handles with a frozen image during dragging and
refitting on release. Add explicit, undoable Convert to Smart crop actions in
Crop properties and the context menu. Geometry/interaction regression tests
cover exact-fit selection, staged edits, source limits and undo/cancel.
### v0.10.0-rc.12
- Double-click and Enter open Crop properties for Centered/Cropped layers instead
of silently doing nothing. Preserve automatic fitting, geometry and crop; normal
crop and 1:1 still use their interactive helper. Regression tests cover both
shortcuts across all explicit fit modes.
### v0.10.0-rc.11
- Review problematic transfers with explicit included/skipped layer lists and
**Send valid layers**. Conflicting mappings never select an arbitrary winner.
- Offer send-only canvas conversion (keep pixels or scale to destination) and
source-dimension adaptation. Projects and saved mappings remain unchanged.
- Record conversion discrepancies above one output pixel in bounded local JSONL
logs instead of blocking valid geometry. Subpixel and one-pixel discrepancies
remain silent; invalid ranges, exhausted crops and readback mismatches still fail.
Logs describe calculated geometry and verification, not physical-output accuracy.
### v0.10.0-rc.10
- Recover from temporary send-readback failures using up to three read attempts,
without repeating writes or apply pulses. Stop starting retries after five
seconds; an in-flight read retains its existing timeout. Report uncertain
outcomes when verification remains unavailable.
- Accept pasted root HTTP device URLs as well as IP addresses, and disable linked
Send while a shared-input send is active. Socket-write counts no longer imply
device acknowledgement. Regression tests cover recovery and address validation.
### v0.10.0-rc.9
- Enabling Follow input now adapts the layer to the selected input’s processed
dimensions, using the same undoable crop/fit path as manual preview selection.
- Avoid a transient mismatch warning in Follow input mode: hide the previous
capture while its input binding catches up with a changed source selection.
- New preview controls default to Follow input. Independent preview inputs show
resolution warnings and stronger ratio warnings in both Source and Preview
properties, including a canvas/preview
overlay. Compare processed signal dimensions, not reduced capture thumbnails;
existing image framing and explicit reference-picture choices are preserved.
- Picture overlays identify previews that are not the selected layer input:
blue for a different input, amber for differing resolution, red for differing
ratio. Text states the reason as well, and wraps inside the picture.
### v0.10.0-rc.8
- Support switching to cropped Midra inputs using their processed image dimensions,
without applying input crop twice. Verify crop controls against signal readback
and retain freshness checks. Preview source adaptation uses the same validation.
- Aquilon shared-crop and input aspect-correction restrictions remain unchanged.
### v0.10.0-rc.7
- Stabilize input-preview GUI tests under CI load with a controlled capture clock.
Check cooldown boundaries without real-time delays; production capture intervals
and device behavior remain unchanged.
### v0.10.0-rc.6
- Allow Crop & fit paste across different input dimensions. Crop edges transfer
proportionally without changing source assignments or input preprocessing.
The destination’s Advanced fit is preserved; normal crops that no longer match the box
use Centered (fit), retaining ratio rather than stretching or refusing paste.
### v0.10.0-rc.5
- Adapt a layer to the selected input resolution instead of requiring a manual
source-size match. Preserve its outer box and normal zoom/focus; advanced fit
retains proportional crop edges. Shared editor sources are detached per layer.
- Preview input selection uses the same undoable adaptation. Explicit input-switch
plans adapt a temporary layout too, retaining device freshness validation.
### v0.10.0-rc.4
- Fix Midra layer input switching reading the wrong input crop path. Validate
Midra crop controls rather than Aquilon crop status; missing or malformed data
still blocks switching, as do active crop and aspect correction.
### v0.10.0-rc.3
- Use stable selectable rows and a subtle background hover in device input
pickers, avoiding border-driven shifts when moving between inputs.
### v0.10.0-rc.2
- Tighten input reference picture rows from 44 to 32 pixels apart while retaining
the existing button size. Reclaim the space below the list as well.
## v0.10.0-rc.1 — 2026-11-18
First release candidate for the 0.10 minor release, collecting the changes below.
See the [release candidate notes](../development/release-notes/v0.10.0-rc.1.md)
for highlights, compatibility changes and validation limits.
### v0.9.76
- Preserve the actual picture ratio when fitting input captures and local reference
pictures into source space. Midra cropped captures no longer stretch back to
the declared source ratio before layer crop, zoom, fit and mask are applied.
### v0.9.75
- Highlight Send changes when an input has pending edits. Keep view zoom, panning
and Fit view available while Keep device values protects the input crop.
### v0.9.74
- Reorganize Input settings around a larger crop workspace, with crop protection
and live capture next to the preview. Numeric crop values/presets are collapsible.
- Keep input selection, Send changes and the pending-change count above the
scrolling editor. Advanced processing uses a category picker with aligned
fields; narrow windows stack the panels. Device write and draft rules are unchanged.
### v0.9.73
- Add Cancel to Apply/Discard close confirmations for layer properties, renaming,
batch names/folders, clipboard import and device import review. Cancel returns
to editing with the draft intact and cancels deferred layer-list actions.
### v0.9.72
- Fix input-crop capture on Midra: its PNG contains only the retained crop, unlike
Aquilon’s full-frame snapshot. Place it in the applied crop rectangle without
cropping twice, leaving unknown pixels as the sizing grid.
- Validate capture dimensions and before/after device state; read-only checks on
Eikos 4K 3.3.10 covered uncropped, portrait-cropped and asymmetrically cropped input.
### v0.9.71
- Load a local reference picture into a layer’s input preview for offline crop,
zoom, fit and mask preparation. Pictures never upload to a switcher.
- List input reference pictures separately beneath fixed reference pictures.
Local pictures save with projects and disable capture refresh/follow for that layer.
### v0.9.70
- Stop treating unrecognized clipboard text as draw.io XML. Unsupported text now
explains the supported text formats and PowerPoint’s .pptx file-import route.
- Well-formed HTML supplied as clipboard text can fall back from a rejected
embedded draw.io document to embedded SVG. Rejected candidates are reported in
the review; ambiguous multiple documents and invalid explicit Canvas Pilot
versions remain errors. Native binary clipboard support is unchanged.
### v0.9.69
- Enter now opens crop edit for the selected editable layer using the same rules
as double-click, and finishes an active crop/mask edit. Text fields, dialogs,
active drags and held-key repeats retain their existing safeguards.
### v0.9.68
- Moved **Send changes**, validation feedback and status above the input editor.
- Keep the captured picture and sizing-grid composite at full opacity while
**Keep device values** disables crop editing. Verified capture geometry is still
required; draft crop changes never reposition or stretch the captured pixels.
### v0.9.67
- Input editor categories now start with **Keep device values** enabled.
- Crop zoom uses a 100–500% slider with manual entry beyond its range, subject
to device limits. Selecting 100% clears both crop axes exactly, avoiding a
residual crop after asymmetric edits.
### v0.9.66
- Reopening a project now resumes saved preview auto-refresh when its matching
device is connected and snapshots are available. Offline stills remain visible;
loading does not connect to a saved address. Disabled and still-only previews
remain idle. Project format is unchanged.
### v0.9.65
- Added per-destination **Send options** to the mapping window mockup: Position,
Size, Crop, Fit mode, Mask and opt-in Input. This is a visual proposal only;
application transfer behavior and save formats are unchanged.
### v0.9.64
- Source properties can stage a physical input with **Change input**, applied only
on explicit Send. Fresh-state checks and readback include the selected source.
- Preview **Follow input** follows that selection without routing the device.
These choices are session-only; project/export schemas are unchanged.
- Switching currently requires a valid, uncorrected input matching the editor
source dimensions. Unsupported input processing is rejected before writes.
### v0.9.63
- Added a device-state conflict dialog with changed fields, Cancel send, Send my
layout anyway, and a warning-colored Discard local changes and reload action.
All screens are checked before the first write. Explicit overwrite rebuilds
plans against fresh state without bypassing validation; scoped Preview reload
is undoable and refuses ambiguous multi-destination layers.
### v0.9.62
- A rejected or failed layer send now refreshes device state read-only and keeps
the connection available when that refresh succeeds. The send error remains
visible and sending is never retried automatically. A failed refresh still
marks the device unavailable.
### v0.9.61
- Removed Crop Finder from shared input settings and replaced the review step with
a direct **Send changes** button. Fresh device validation, category protection
and verified readback remain in place.
### v0.9.60
- Input capture is now a live toggle while Input settings is open, sharing the
existing refresh interval and pooled requests with layer previews.
- Show captures directly in their verified device-crop region, with the sizing grid
elsewhere. Sending invalidates the image until a new verified capture arrives;
local crop edits never stretch the preview.
### v0.9.59
- Added “Keep device values” per input-settings category. Protected categories
discard draft edits, disable editing and never contribute device writes, including
after Undo. Crop protection also disables the visual crop editor.
### v0.9.58
- Made shared input crop handles easier to grab, with larger targets, resize
cursors and drag tracking from the original press position.
- Added a percentage crop-zoom slider between − and +, using the selected pivot.
- Input option labels now show readable names and ratios (for example `16:9`
and `Keep input ratio`); device enum values remain unchanged.
### v0.9.57
- Removed the legacy local source/pre-crop editor and inactive input proposals.
Shared Input settings owns device preprocessing; layer rendering/sends use the
processed source dimensions without adding another input crop. Aquilon’s existing
refusal of framing transfers with active shared crop/aspect correction remains.
- Project schema 20 no longer stores either retired setting. Open project recovers
usable content from supported JSON, reports skipped/reset data, and opens repaired
documents as unsaved copies. Invalid JSON, unknown versions and documents with
no usable layers remain errors. Source files are never rewritten during loading.
- Updated snapshots/clipboard round-trip coverage and added partial-load tests for
damaged geometry, optional settings, images and original-file protection.
### v0.9.56
- Removed legacy input proposal controls and the input-setting additions to layer
sends. Native device edits now use the shared Input settings window exclusively.
Local source geometry has its own editor-only permission. Existing saved
proposals remain preserved and inactive without changing project/export schemas.
### v0.9.55
- Added a shared **Input settings** window, independent of layer selection, with
native input crop edges, move, pivot-based crop zoom, view zoom, Undo and explicit
reviewed input-only sends. Aspect, color and processing controls follow the
connected adapter; supported keying/LUT controls are capability-dependent.
- Aquilon reads only the selected input's additional controls. Sends preflight fresh
state, use each adapter's input apply command, verify readback and never send
layer geometry or pulse preset apply. Existing local source geometry and saved
input proposals retain a compatibility path.
- Created the local `pre-input-settings-refactor` checkpoint. Pulse 4K 3.3.7 and
Aquilon Cmax 6.2.79 emulator crop tests verified restoration and unchanged screen
settings. Aquilon captures show cropped edges blanked; raw capture is unconfirmed.
The input crop editor reuses the sizing artwork for unavailable pixels and
anchors verified Aquilon capture pixels to their original source region. An
unchanged capture remains available below the editor.
### v0.9.54
- Expanded the adapter candidate survey with vMix Layers and a focused ATEM
SuperSource assessment, including readback, Linux integration and test-target
gates. Research only; neither adapter is implemented or validated.
### v0.9.53
- Crop borders to ratio now restores uncropped bounds before each preset. Added
an optional “Crop within existing crop” toggle for cumulative trimming, with
regression coverage for switching ratios, restoration and Undo.
### v0.9.52
- Closed localization for its accepted scope and Midra rendering precision for
now; retained technical limitations and reference notes. Videos remain in
progress; additional adapters, mapping GUI and multiple project screens stay open.
### v0.9.51
- Added a standalone mapping-window visual study with one load source, grouped
send destinations and a proposed “Follow load source” shortcut. Sample controls
have no application or device logic; production UI and behavior are unchanged.
### v0.9.50
- Added a stretch goal for independent load/send mapping controls, multiple send
destinations and eventual named connections, retaining the synchronized workflow
as the default. Implementation remains deferred.
### v0.9.49
- Split load sources from send destination collections internally, keeping existing
controls synchronized with one destination and unchanged visuals. Send destinations
explicitly name the current connection scope; both adapters can prepare fan-out
to distinct layers while retaining collision checks. Project v19 migrates old
mappings into both directions; recovery and embedded snapshots retain the split.
Added routing, undo, migration and exchange round-trip regression checks.
### v0.9.48
- Keep the four layer-header buttons inside the sidebar content area so their
icons are no longer clipped along the top edge.
### v0.9.47
- Detect optional software at startup and use the same executable paths for
conversion. Hide unavailable artwork modes and Illustrator format choices;
retain built-in geometry and layout-box workflows. Added Software integrations
to the application menu, listing detected/missing tools, paths, setup and enabled
functions. Discovery checks executable files without launching applications.
Added executable-search precedence, capability and UI regression checks.
Required Rust checks and manual build passed; whole-app coverage is 92.06%.
### v0.9.46
- Added PDF/document reference import with page selection, resolution control and
preview before adding. PDF/SVG and Figma artwork render locally; JSON/HTML retain
embedded pictures. PPTX and draw.io artwork use optional local converters, AI
uses VectorCraft, and all geometry formats offer labelled layout-box pictures.
Rendered PNGs preserve proportions and reopen without the source/converter.
PDF remains reference-only; complex rendering and external converters have the
documented limits. Added page/crop/rotation, artwork, cancellation and save/load
regression checks; checked the showcase PDFs and LibreOffice slide conversion.
Required Rust checks and the manual build passed; whole-app coverage is 91.99%.
External draw.io/VectorCraft rendering was not exercised (tools unavailable).
### v0.9.45
- Split bundled themes into video-game-themes (6, including Ravenswatch) and
classic-themes (11). Retired the combined extra-themes download; standalone
palettes are unchanged. New pack IDs coexist with old installations, with
explicit selection/removal instructions. Checked partitioning, notices,
reproducible archives, simultaneous installation, restart and contrast.
### v0.9.44
- Added a separate, reproducible Lumen Forum showcase kit: polished PIP infodecor,
synthetic speaker media, an editable three-slide deck, raster-only/editable
handoffs, three layouts in five exchange formats, projects and silent demo loops.
Generated assets stay local and Git-ignored. Verified native geometry imports,
LibreOffice rendering and video dimensions/durations; no device activity.
### v0.9.43
- Added a standalone Ravenswatch palette with midnight-blue surfaces, aged ivory
text and crimson accents inspired by the supplied reference. Kept the existing
16-theme collection unchanged at the version-1 limit; packaging now lists its
members explicitly. Added import/contrast and collection membership checks.
### v0.9.42
- Replaced the distributed Minecraft palette with Vivid World: midnight navy,
violet, pink and cyan crystal accents inspired by the supplied reference.
Added its standalone pack and updated extra-themes to revision 4. Existing
standalone Minecraft installs remain user-managed; an active removed collection
theme falls back to Midra Dark. Updated downloads, docs and contrast coverage.
### v0.9.41
- Retuned Deep Rock Galactic to gold and molten-orange accents on dark rock/brown
surfaces, following the supplied title-art reference. Updated its standalone
pack to revision 2 and extra-themes to revision 3; regenerated downloads and
checked text contrast.
### v0.9.40
- Retuned Dispatch to vivid yellow and cyan accents on charcoal/olive surfaces,
with off-white text, following the supplied title-art reference. Updated both
Dispatch and the extra-themes collection to revision 2 for existing installs;
regenerated downloads and checked text contrast.
### v0.9.39
- Removed the secondary Dark/Light/In use lines from theme choices and locale-code
lines from language choices in installed packs, leaving compact named buttons
with theme swatches and selected-state highlighting.
### v0.9.38
- Keep resize, crop and mask handles visible above overlapping layers. Covered
guide edges are dashed; exposed portions remain solid, respecting hidden layers,
masks and fitted picture bounds. Rendering is clipped before generating dashes
to remain bounded at high zoom. No geometry, stacking or save-format changes.
### v0.9.37
- Grouped size presets under one toolbar icon and separated tiling labels from
bordered numeric fields. Added a session-only Keep proportions toggle for
fullscreen, quarters, halves and tiling: each layer fits centered inside its
region without changing aspect ratio. Portrait/Landscape remain explicit swaps.
Geometry and UI regression tests cover fitting, placement and Undo/Redo.
### v0.9.36
- Fixed theme-pack reproducibility checks across build hosts by using stored ZIP
entries and fixed Unix metadata, avoiding zlib-dependent compressed bytes.
Regenerated all 17 downloads without changing manifests; regression coverage
rebuilds them without zlib and with simulated Windows platform metadata.
- Added extra-themes.zip: one import installs all 16 themes, with individual ZIPs
still available. Added Dracula, Nord, Gruvbox Dark, Solarized Dark/Light, One Dark,
GitHub Dark/Light, Monokai and original Dispatch, Helldivers and Deep Rock Galactic
palettes. Included upstream notices, deterministic packaging and regression checks
for full-collection import, restart, selection and text contrast. Uses the existing
version-1 multi-theme format.
### v0.9.35
- Replaced expanding theme/language pack stacks with a searchable pack browser:
bounded collection list, one selected pack's details, in-use indicators, counts
and revisions. Search includes pack contents; narrow windows stack the panes.
- Kept live theme switching, language confirmation, overwrite review and removal
safeguards. Pack browsing is session-only and changes no archive/settings schema.
## Release v0.9.34 — 2026-11-17
### v0.9.34
- Renamed Visible layer edges to Layer borders and made disabling it exclude moving
outer borders as well as stationary border targets. Mask edges & centers remains
independently selectable, with both choices preserved in preferences/projects.
Center alignment and direct resize-handle snapping retain their existing behavior.
### v0.9.33
- Device mapping/transfer and import now use wider solid scrollbars whenever their
content overflows. Bars remain visible with the pointer elsewhere so additional
layer rows and controls are discoverable, without changing mappings or transfers.
### v0.9.32
- Made dragging layers out of folders easier: doubled the child-row gutter and
made it a root drop target, including row gaps. Enlarged the No folder strip
and added cyan drag feedback with an explicit release hint. Folder membership
changes preserve geometry and stacking and remain undoable.
### v0.9.31
- Extended Mask edges snapping to include visible masked-area centers as movement
anchors and move/resize/pivot targets. Centers use the clipped visible picture,
including source-relative masks and explicit fit modes; hidden or fully blanked
targets stay excluded. Existing preferences, group movement and Undo are preserved.
### v0.9.30
- Replaced the toolbar Import tray with an inward-arrow box and added a matching
outward-arrow Export icon beside it. Both open the existing reviewed workflows;
export supports the same layer files and device-transfer options as the menu.
### v0.9.29
- Added 4:3, 16:9 and 16:10 crop presets in Crop properties and the selected-layer
context menu. Trim symmetric embedded borders and shrink the layer around its
center together; matching ratios are no-ops. Multi-layer changes undo atomically,
preserve existing source/input settings and fit modes, and send no device writes.
### v0.9.28
- Added a toolbar icon box for selected-layer Fullscreen, Quarter, X/Y Tiling,
Portrait and Landscape presets. Quarter offers nine positions for one layer,
halves for two and four quarters for larger selections. Overflow repeats cells
with an explanation; placement follows the layer list, including folder members.
- Presets retain fractional geometry, preserve source/link/mask identity and commit
atomically with crop adjustment in one Undo step. Orientation keeps top-left
positions; explicit preset sizes override manual aspect-ratio locking.
### v0.9.27
- Enter now finishes viewport crop/mask editing, including clean Crop/Mask
properties, while retaining live changes and Undo history. Numeric fields keep
their Enter-to-commit behavior; pending properties receive Apply/Discard review.
Held Enter and active pointer drags do not accidentally finish the helper.
### v0.9.26
- Added offline theme ZIP packs with bounded validation, live installation/update,
reviewed overwrites/removal and collapsible management with swatches and notices.
Packed themes appear in the persistent picker/recent history and work with the
High Contrast return toggle. Missing packs retain their saved choice with a
Midra Dark fallback; removing an active theme saves Midra Dark.
- Added downloadable Tokyo Night, Catppuccin Mocha, Detroit: Become Human and
Minecraft Overworld examples, editable manifests and reproducible ZIP tooling.
Upstream notices are included; game-inspired palettes contain no game assets.
- Settings v15 migrates versions 1–14 and documents namespaced theme references.
Project, recovery, geometry and device formats are unchanged.
- All required Rust/Python checks, reproducible example ZIP checks, native palette
rendering and the pinned manual build pass. Whole-application coverage: 91.92%.
### v0.9.25
- Fix Load collapsing Device mapping & transfer to its title bar: the shared
control now closes only menus, not the window's internal collapsible body.
Mapping/import windows also recover previously saved collapsed states.
- Regression checks reproduce the Load click and cover recovery with a connection
error visible; no physical device is needed for these UI checks.
### v0.9.24
- Group installed language packs under bold, collapsible ID/revision headings,
with languages and the removal action indented beneath their pack. Packs start
expanded and retain their open/closed state while browsing settings.
### v0.9.23
- Clicking High Contrast again restores the previous theme in the theme browser,
recent-theme menus and Appearance settings. The saved theme history supplies
the previous choice, with Midra Dark as the fallback.
### v0.9.22
- Fix High Contrast source-helper coordinates disappearing on white checkerboard
tiles: labels now use black on white tiles and white on black tiles.
### v0.9.21
- Keep the More themes picker open after each selection so multiple themes can
be previewed before closing it. Each choice still applies and saves immediately.
### v0.9.20
- Added a full-width No folder drop area and widened the heading drop target to
make dragging layers out of folders easier. Layer/folder context menus offer
Move up/down, preserving folder membership and whole-folder stacking blocks.
- Added an Add layer icon and viewport/empty-list context-menu action, selecting
the new layer without opening the manager. The 256-layer limit still applies.
- Formatting, both Clippy configurations, all required Rust test suites, rustdoc,
native rendering and the pinned manual build pass. Whole-application line
coverage: 91.79%.
### v0.9.19
- Added Aquilon rectangular-mask import and reviewed sends for Layer/Source
origins, both sizing strategies, fully blanked axes and explicit reset-to-zero.
Container/visible-image conversion preserves crop and image scale; malformed
masks and excessive quantization error fail explicitly. Opposite-edge releases
precede increases, with existing preflight, apply and readback safeguards.
- Expanded the explicit Aquilon diagnostic to preserve a temporary recovery
baseline and verify masks as well as geometry/crop in Preview and Program.
The RS1 6.2.79 simulator passed the 96-case mask matrix across runs and a WebRCS
rendering check. Baselines were restored and verified, including recovery after
an interrupted run. A sanitized RS1 readback fixture guards the round trip.
Cut & Fill, explicit fit modes and physical-output acceptance remain separate.
- Formatting, both Clippy configurations, rustdoc, 467 default/461 restricted
tests and the pinned manual build pass. Whole-application line coverage: 91.72%.
## v0.9.18 — 2026-11-17
Release preparation: see the [release notes](../development/release-notes/v0.9.18.md).
Published with four-platform portable bundles, cargo-binstall archives and raw
binaries, plus the Ukrainian/Bhojpuri language pack and reproducibility files.
See the [release notes](../development/release-notes/v0.9.18.md).
### v0.9.18

View File

@ -41,6 +41,49 @@ The SVG demonstrations exercise interchange without pretending to record Illustr
Figma or draw.io. Actual captures from those applications, live input capture, other
file codecs and physical device output require separate application/device sessions.
## Conference handoff kit
A separate local `showcase-conference-kit/` directory supplies a fictional **Lumen
Forum** event for recording the raster-only versus editable-client workflow.
It leaves the existing `showcase-videos/` recordings intact. Start with its
`index.html` preview and `START-HERE.txt` recording guide.
The kit includes a clean 1920 × 1080 background, empty PIP infodecor, a placement
guide and a complete speaker/slide composite; three editable presentation slides;
a synthetic portrait; and silent speaker-motion, presentation and background MP4s.
The speaker loop is a pan/zoom of a generated still, not a real recorded talk.
All names, event content and slide data are fictional.
`delivery-jpg-only/` contains flattened PNG/JPGs and a deliberately degraded
960 × 540 JPEG. Raster files are reference artwork, not editable geometry.
`delivery-editable/` contains native PPTX text/shapes, vector SVG slides and a
composition whose speaker/slide pictures move independently in PPTX/draw.io/SVG.
Three layout folders each contain a project plus SVG, draw.io, PPTX, JSON and CSV
geometry. The main speaker box is `(72,260,432,576)`; the slide box is
`(552,260,1296,729)`. Coordinates are top-left screen pixels. The other layouts
show a large slide and a side-by-side pair. Projects have no device links.
Rebuild into a **new** directory with the supplied 3:4 speaker PNG:
```sh
python3 scripts/prepare-conference-showcase.py \
--speaker showcase-conference-kit/media/speaker/alex-morgan-synthetic.png \
--output /tmp/lumen-forum-rebuilt
```
The recipe uses Python's standard library, `rsvg-convert`, FFmpeg and ffprobe,
and refuses to replace an existing output folder. DejaVu Sans is the design font.
The portrait was made with the built-in image-generation tool using
[the saved prompt](../../scripts/showcase-speaker-prompt.txt); rebuilds reuse the
image rather than make new network calls. Generated assets remain local and ignored
by Git. The recipe, prompt and checks are versioned.
Prepared-kit validation includes exact geometry imports through Canvas Pilot,
project loading, LibreOffice PDF renders of the native decks, and ffprobe checks
of dimensions and durations. PowerPoint itself and the draw.io GUI were not used;
draw.io geometry was checked by the application importer. `verification/` holds
the local evidence. This is offline artwork evidence, not device acceptance.
## Recording environment
Use a dedicated X11 display, not the working desktop. The script sends real mouse

View File

@ -23,13 +23,12 @@ means a supported exchange format exported with extra parameters and reopened th
| Stacking order | ✅ | ❌ | ✅ |
| Folders, collapsed folders, visibility and locks | ✅ | ❌ | ✅ [2](#editing-notes) |
| Source formats, assignments and shared input relationships | ✅ | ❌ | ✅ [2](#editing-notes) |
| Input crop edges | ✅ | ❌ | ✅ |
| Normal layer crop zoom and offsets | ✅ | ❌ | ✅ |
| Advanced fit modes and their crop edges | ✅ | ❌ | ✅ |
| Editable blanking masks (Layer / Source) | ✅ | ❌ | ✅ |
| Resize pivots and group resize settings | ✅ | ❌ | ✅ |
| Saved device screen/layer links (not physical source routing) | ✅ | ❌ | ✅ |
| Opt-in saved device input correction proposals, restored inactive | ✅ | ❌ | ✅ |
| Shared device input settings drafts (session-only) | ❌ | ❌ | ❌ |
| Reference images and their individual settings | ✅ | ❌ | ❌ |
| Capture assignments and saved preview stills | ✅ | ❌ | ❌ |
| Selection, camera, guides, snapping and workspace settings | ✅ | ❌ | ✅ [2](#editing-notes) |
@ -53,29 +52,20 @@ For a complete editable backup, **Save project** remains the recommended choice.
Canvas Pilot’s **Copy layer values** also preserves exact geometry, crop edges,
offsets, fit and blanking through the clipboard. Its mapping review offers an
optional **Appearance** group; source assignments and device links remain unchanged.
optional **Appearance** group. Pasted crop edges adapt proportionally to the
destination input and use its selected **Advanced fit**; the copied fit does not
replace that choice. Source assignments and device links remain unchanged.
The separate **Rename destination layers** option applies supplied source names.
See [clipboard preservation and limits](files.md#canvas-pilot-layer-clipboard).
This is separate from plain geometry import and export snapshot restoration.
## Saved input corrections
In the advanced input controls, explicitly choose **Save staged input edits as a
project proposal** to retain the corrections you have staged. Projects save these
proposals; Silver exports include them only when **Include extra Canvas Pilot
parameters (experimental)** is enabled. Saving a proposal is optional and separate
from staging or sending it.
Proposals cover Content ratio, Transform to, custom ratio, layer fill, input crop
preset and the four input crop edges. Local source dimensions/crops and shared
source assignments already belong to the project and need no proposal.
Opening a project or restoring a snapshot leaves corrections **inactive**. Connect,
check the layer's device mapping and routed input/plug, enable advanced input edits,
and choose **Stage saved input proposal**. Review before sending. A changed mapping,
input/plug or missing device field prevents staging. Corrections affect shared
inputs and can therefore affect other layers and Program. Removing a saved proposal
does not undo device changes or discard separately staged edits.
Device input corrections live in the [shared Input settings window](formats-and-crop.md#shared-device-input-settings).
Drafts are session-only and require explicit review and send. Projects and exchange
snapshots save processed source dimensions and layer settings, but no input crop or
inactive device-input proposal. Opening an older native project reports discarded
legacy settings; inspect the recovered layout before saving.
For practical examples across editors, see [what gets lost between formats](conversion-losses.md).
@ -93,7 +83,7 @@ also does not restore embedded snapshots. Use **Restore parameters from export**
for Silver; use ordinary geometry import for the artwork's latest positions.
Automated round trips cover all fit modes, fractional crops, both mask references, shared
inputs, mappings, saved proposals and workspace state through every Silver codec.
inputs, mappings and workspace state through every Silver codec.
FigCraft metadata is also tested through its native load/save cycle. External
application resaves can strip metadata; this is not a promise of lossless round
trips through every editor. See the [carrier contract](../../interfaces/midra-extra-parameters.md)

View File

@ -59,7 +59,12 @@ not unlock it. These are local session controls, separate from geometry undo/red
Selected layers use gold outlines, labels, handles and position guides; unselected
layers use muted outlines and labels. Gold in the layer list follows the same
selection state, including when several layers are selected.
selection state, including when several layers are selected. When a higher layer
covers an editing box, covered edge portions are dashed and exposed portions stay
solid. Resize, crop (cyan) and mask (magenta) corner and side handles remain visible
above the artwork, so you can edit a selected layer underneath another. Hidden
layers and blanked regions do not cover guides. This display does not change
stacking, geometry or device output.
### Reference pictures
@ -154,12 +159,26 @@ Navigation tool choice survives selection changes and project loads in the curre
session; a new launch starts with Select. Pan/Zoom do not alter geometry, crop values
or document history. Existing project saves still preserve zoom/pan values.
### Layer border snapping
**Layer borders** is independent of **Mask edges & centers**. Turn it off to stop
using outer layer borders as movement anchors or stationary snapping targets.
You can leave mask snapping on to position the visible masked picture, or disable
both options. Neither checkbox changes the other. Screen/grid center alignment,
pixel rounding and directly dragged resize handles retain their own behavior;
mirrored/opposite border-contact snapping follows **Layer borders**.
### Snap to masks
Enable **Mask edges** in the snapping options to add the visible mask boundaries
as targets, independently of **Visible layer edges**. Movement can align either
Enable **Mask edges & centers** in the snapping options to add the visible mask boundaries
and their centers as targets, independently of **Layer borders**. Movement can align either
outer layer edges or mask edges to those targets, screen guides and grid lines.
Resize handles and pivots can snap to stationary layers’ mask boundaries;
The center of a moving visible masked area can align to screen interior guides,
overlay grid lines and other masked-area centers. Whole-layer centers can also
align to masked-area centers. The center comes from the visible remainder after
masking, rather than the hidden/blanked part. Groups move rigidly and Undo restores
the complete move without changing mask values.
Resize handles and pivots can snap to stationary layers’ mask boundaries or centers;
resize handles still belong to the outer layer rectangle. Mirrored/opposite
resize contact remains based on outer layer edges.
@ -198,6 +217,11 @@ stay selected across selection changes and project loads in this session; they
are not saved to projects/settings and start off on launch. They affect layer
movement/resize, not numeric edits or crop-content handles.
With snapping enabled, **Pixel edges** gives whole output pixels a small magnetic
zone during layer movement and resizing. Screen, layer and grid alignment keeps
priority. Moving beyond one quarter pixel from the nearest integer retains the
fractional coordinate, so precise subpixel placement remains available at high zoom.
<!-- Screenshot recipe: ../images/capture.md#advanced-guide-captures -->
![Overlay grid controls with eight columns, six rows and separate visibility and snapping switches](../images/10-guide-grid.png)

View File

@ -6,7 +6,9 @@
Enter an IP address in **Device IP / port**, optionally followed by a TCP port:
`192.168.10.146:3000`. Without a port, the app uses port 80. IPv6 addresses
with a port use brackets, for example `[::1]:3000`. Omit URL schemes and paths.
with a port use brackets, for example `[::1]:3000`. A pasted root HTTP URL,
for example `http://192.168.10.142/`, also works. Omit credentials, queries,
fragments and page paths; HTTPS and hostnames are not supported.
The address is saved in preferences and used for identity, input snapshots,
automatic reconnect and WebSocket sends. Aquilon also requires AWJ TCP port
10606 on the same IP for its targeted geometry reads; Midra reads use the HTTP port.
@ -23,6 +25,43 @@ are still validated. Eikos 4K hardware and a Pulse 4K 3.3.7 emulator have been
read successfully; QuickVu/QuickMatrix have parser regression coverage but
still need individual emulator/hardware acceptance.
## Review resolution conversions
When a linked transfer cannot be prepared, its review offers explicit conversions.
The mapping window also has **Review conversions / send valid layers…**.
Choices apply to this transfer only: the project, saved links and source routing
are unchanged unless an input change was already explicitly selected.
- **Require matching resolution** is the default.
- **Keep pixel coordinates** sends the same positions and box sizes to a different
canvas. A 500-pixel box remains 500 pixels on a larger screen.
- **Scale to destination canvas** scales positions and box sizes independently on
each axis. A 1920 × 1080 layout sent to 3840 × 2160 doubles both. A different
canvas ratio changes box proportions; normal cropping follows the resized box,
while explicit fit retains its meaning.
- **Adapt source dimensions to the destination input** preserves the box and
reframes crop for the reported input dimensions. It does not change the physical
input signal or its shared settings. Unsupported input processing still blocks
that destination.
Review the listed conversions and exact changes before sending. Invalid destinations
remain explicitly listed, and conversions do not bypass freshness checks.
## Transfer discrepancy logs
Subpixel and exactly one-pixel conversion differences produce no discrepancy warning
or log. Larger calculated visible-size or Aquilon mask-bound differences are recorded
when a send is attempted, rather than blocking otherwise valid geometry. Impossible
sizes, exhausted crops and unexpected device readback still fail validation.
Logs are stored in `logs/device-transfers.jsonl` beside the existing settings file
(see [Preferences](preferences.md)). One previous file is retained; each file is at most
1 MiB. Records contain requested/calculated pixel values, destination, timestamp,
application version and whether readback verified the send. They do not measure
physical output. Opening a review does not write a log. A log-write failure does
not stop a device transfer. The [log contract](../../interfaces/midra-device-send.md#transfer-discrepancy-log-v1)
describes the fields.
## Use folders as local device layouts
The **Apply to** selector is shared by the status bar, Export menu, and
@ -44,9 +83,12 @@ To prepare several layouts that reuse the same device layers:
Multiple editor layers may link to the same device destination, within or across
folders. Mapping shows a warning listing the other linked layers and their folders.
Sending is disabled when the chosen scope contains overlapping **screen + layer**
destinations, with a list of the conflicts. Choose a conflict-free folder or selection,
or remap/skip rows; links outside that send scope do not block it.
A linked send with invalid or overlapping **screen + layer** destinations opens
**Review device transfer**. It lists every included and skipped layer, its destination
and the reason for skipping. All layers competing for one destination are skipped;
none wins automatically. **Send valid layers** sends only the listed valid destinations.
Cancel to repair mappings or choose a different scope. No send is possible when
all destinations are invalid. Links outside the chosen scope do not block it.
Linked send/load skip unlinked layers. An empty selection or missing folder never
falls back to All. Transfers already started retain the links captured at click time.
These are local geometry layouts, not device preset recalls or source-routing memories.
@ -70,7 +112,10 @@ are explained in the review. Imports are one undoable edit.
Open **Export → Midra mapping & transfer…** even while offline, then use
**Connection settings…** to connect. Mapping and transfer controls appear once
device data is available. Choose editor layers,
device data is available. When more rows or controls extend below the window,
a solid scrollbar stays visible even while the pointer is elsewhere. Scroll to
review all layers; the import list uses the same visible scrollbar behavior.
Choose editor layers,
map each to a Midra layer, select **Preview** or **Program**, and select a container
strategy: **Output-sized** or **Source aspect**. Expand **Exact device changes** to
review sizes, centers, crop values and aspect, then click **Send mapped layers**. The final row groups **Load linked layers**
@ -79,8 +124,12 @@ device); the Load label follows the selected transfer scope.
The button is disabled while a send is in progress. Matching stored values can still be sent to apply staged geometry to hardware.
The source's native dimensions must match the destination's current content.
The target bank is fixed when configured. Sending starts immediately without a stale-state check. Writes are sequential;
partial failures require refreshing, not automatic retries or rollback. Success
The target bank is fixed when configured. Sending checks for changed source,
framing and destination state before writing. Writes are sequential. A rejected
or failed send refreshes the device read-only: if it responds, the connection
stays available with updated state and the send error remains visible. Check the
updated layers before sending again. Failed refreshes mark the device unavailable;
there is no automatic send retry or rollback after partial failures. Success
means all changed fields matched device readback. There are no automatic sends
from edits, imports or undo. Closing the connection window does not cancel a send
already started; wait for its result before loading another project.
@ -89,6 +138,27 @@ See [hardware checks and limitations](../device-check.md) and the
[device exchange contract](../../interfaces/midra-device-send.md). The footer's ONLINE
status reflects the last successful read, not continuous polling.
## Reference picture for offline cropping
In a layer’s **Preview** controls, choose **Load reference picture…** and select a
PNG, JPEG or BMP. The picture replaces that layer’s captured preview and follows
its crop, zoom, fit and mask, just like an input preview. It is **local only**:
Canvas Pilot never sends the picture to a switcher or changes device input routing.
The picture represents the full source frame using the layer’s configured source
format. Set that format to match the intended input; loading a picture does not
change source dimensions or geometry automatically. Capture auto-refresh and
**Follow input** are disabled when loading it. Choosing a physical input again
replaces the local picture with a device capture.
**Input reference pictures**, beneath the fixed reference pictures in the layer
list, lists both local pictures and captured layer previews. Click a row to select
its layer; use the checkbox to hide/show its preview or × to remove it. Fixed
reference pictures remain independent canvas overlays.
Save a `.pilot.json` project to retain pictures and preview visibility offline.
As with captured previews, geometry-only exports do not retain these pictures.
## Capture an input still from Midra
For a layer, open **Layer properties → Preview** (or right-click → **Configure capture…**):
@ -126,8 +196,9 @@ input's image. Disabling the preview hides it and pauses its refreshes.
**Crop guide opacity** defaults to 35% with an image; without an enabled image,
guides remain fully opaque and the slider is disabled. Selection handles stay
fully visible. Layer previews, captured stills and timer settings are saved in the project.
Saved auto-refresh reopens paused: use **Resume auto-refresh** or **Capture still**
to resume. Opening a project does not fetch images. The timer
Saved auto-refresh resumes when the matching device is connected and input snapshots
are available. Opening a project does not start a connection; saved images remain
visible offline. The timer
pauses offline and while the separate capture/import dialog is open. Reduced
snapshot resolution and freshness are controlled by the device. If snapshots
are disabled for an input, enable them in WebRCS and refresh the connection.
@ -152,12 +223,10 @@ is ready. Manual loading has a Cancel button; errors keep the old project.
Recovery autosave pauses while loading, including on exit.
In the opt-in **Layer properties → Source** section, **Editor input** offers Inputs 1–8 separately
from Midra screen/layer destinations. Use **New editor input** for additional
local identities, then **Apply source changes**. Layers sharing an editor input
share its source format and input crop. Assignments are saved in projects and
undoable; they do not change physical input routing.
**Layer properties → Source** opens the shared Input settings window. Physical
input preprocessing affects all consumers; it is not part of a layer send or a
saved project. Reload affected layers after changing it to refresh processed
source dimensions. Layer source relationships remain stored but do not route inputs.
## Aquilon / LivePremier
@ -166,8 +235,9 @@ Cmax. All firmware versions may connect; versions outside 6.2.x display a warnin
that backward compatibility is not guaranteed. The adapter requires compatible
protocol fields and stops with an explicit error when they differ. Older firmware,
especially before 4.x, may therefore fail to connect. Linked systems remain unsupported.
Cmax 6.2.79 is verified on the emulator; other models/firmware have synthetic test
coverage, and physical-output acceptance remains outstanding.
Cmax 6.2.79 has emulator acceptance; RS1 6.2.79 mask testing is recorded in the
[acceptance record](../aquilon-compatibility.md). Other models/firmware have synthetic
test coverage, and physical-output acceptance remains outstanding.
Connect using the same Device connection window.
The device identifies its family automatically. Screens use `S1`, `S2`, …;
auxiliaries use `A1`, `A2`, … and stay distinct in saved mappings. Only enabled
@ -180,11 +250,15 @@ or a changed bank/source before Send requires a refresh, without writing.
Centered live-input framing supports layer crop and zoom. Fractional geometry is
retained in projects; sends round device sizes/centers to whole pixels for WebRCS
compatibility and check the visible-box error within one pixel.
Masks, non-centered fit modes and shared input aspect/crop corrections are
reported explicitly when their visible bounds cannot be imported. Shared input
compatibility. Calculated visible-box errors above one pixel are logged without
blocking the transfer; smaller discrepancies remain silent.
Rectangular masks load and send without resizing the image. Both editor mask
origins are supported; device loads return a Layer-relative mask. A zero mask
explicitly clears destination blanking during a reviewed send. Fully blanked axes
are allowed. Non-centered fit modes, malformed masks and shared input aspect/crop
corrections are reported explicitly when their visible bounds cannot be imported. Shared input
correction controls remain managed in WebRCS for this adapter. Ordinary sends
never route inputs, TAKE, or change shared input processing.
do not TAKE or change shared input processing; routing requires **Change input**.
Aquilon reads only the required properties through AWJ TCP 10606, in batches,
including a consistency check. The tested emulator now downloads about 197 KB
@ -196,4 +270,68 @@ pooled, throttled, opt-in behavior, including inputs above 16. Older firmware,
linked units and other Aquilon models remain unverified. See the
[adapter contract](../../interfaces/device-adapters.md) for tested scope and limits.
Saved device input corrections are optional [inactive proposals](advanced-exchange.md#saved-input-corrections); opening a file never enables or sends them.
Shared device input drafts are session-only; [projects omit them](advanced-exchange.md#saved-input-corrections). Opening a file never changes an input.
### When device state changes before sending
**Device state has changed** lists the changed fields before any screen is sent:
- **Cancel send** keeps your local edits and sends nothing.
- **Send my layout anyway** rebuilds the original mapped send against the refreshed
device state. It overwrites the mapped layout fields and any explicitly staged input selection. Range,
input compatibility and fresh-state checks still apply. A changed device family
or Preview/Program bank requires checking the mapping again instead.
- **Discard local changes and reload** uses a warning color because it replaces
the mapped local layers’ geometry, crop, fit and masks with the device Preview
snapshot shown in the dialog. Other layers stay unchanged; Undo restores your
edits. This action is unavailable for Program or ambiguous multiple destinations
belonging to the same local layer.
If the device changes again before an explicit overwrite, sending can be stopped
again. Changes or failures occurring during a send remain reported as partial-send
errors, with the completed-screen count; they never trigger an automatic retry.
## Select the input to send or preview
In **Layer properties → Source**, select a **Device input**. Enable **Change input**
to route the mapped destination layer to that input on the next explicit **Send**.
Selecting an input alone does not change the device. Leave the checkbox off to
send geometry without changing its source.
In **Preview**, **Follow input** is enabled by default for new controls and captures the input selected in Source.
Enable input preview as usual; automatic refresh remains a separate option.
Following an input does not route it, and changing the selection clears the old
picture before requesting a new capture.
An independently selected preview with a different processed resolution shows an
amber notice in both **Source** (input selection) and **Preview** properties.
The canvas and Preview tab show **Not displaying selected layer input** when
the picture comes from another input. The overlay is blue for a different input,
amber when its resolution differs, and red when its ratio differs. The text also
identifies resolution or ratio mismatches; color is not the only indication. Enable **Follow input**
to match the selected source. These notices do not alter crop, fit or device
routing. Reduced-resolution capture thumbnails do not trigger size warnings;
intentional differences between the layer box and its source are not mismatches.
Discarding local changes in the send conflict dialog also clears these choices for the reloaded layers.
These selections are session-only and reset when a project or connection is
replaced; they are not saved in projects or exchange files. Input switching requires
a valid signal. Midra inputs with applied crop are supported; framing adapts to
the processed input dimensions using the layer’s fit settings. Input aspect
correction and Aquilon shared input crop remain unsupported. Sending to Program can visibly change the live source.
### Live picture in the input crop editor
In **Input settings**, **Capture input (live)** places the captured picture inside
its **applied device crop**. Unknown areas keep the sizing grid. Midra returns an
already-cropped picture; Aquilon retains the full frame with blanked edges. Canvas
Pilot handles these separately so the crop is not applied twice.
Moving the draft crop does not move the captured picture. After **Send changes**,
the preview refreshes against device readback. A missing signal or inconsistent
capture geometry keeps the grid until a matching capture arrives. Disable
**Crop Finder** in WebRCS when using this preview.

View File

@ -12,13 +12,24 @@ Double-click a folder or layer name to rename it. Folder eye and lock icons appl
to every member; Undo restores each member's previous state, including mixed states.
Use the **Create folder** icon to create an empty folder, regardless of selection. Drag a layer onto a folder
name to move it inside, or onto **LAYERS** to return it to the root. Dropping on
name to move it inside, or onto **LAYERS** or the full-width **No folder** drop
area below the list to return it to the root. You can also drag left into the
wide gutter beside any folder child; the gutter accepts drops along the full row,
including the gap below it. Root drop targets highlight cyan while dragging, and
the bottom strip shows **Release to move out of folder**. Dropping on
another layer also changes stacking order and adopts that layer's folder.
Drag folder names above/below another folder to reorder all their layers as one
block. Right-click offers rename, selection, visibility, locking, moving up/down,
and **Ungroup folder** (keeps the layers). A layer's right-click **Move to folder**
menu also offers existing folders, the root, and a new folder. Right-click a selected layer in either the list or viewport to move all selected layers together; right-click an unselected layer to move only that layer.
Use the **Add layer** (+) icon beside the Layers heading, or right-click the
viewport or empty layer-list space and choose **Add layer**. These shortcuts add
and select a layer without opening the manager. Right-click a layer or folder for
**Move up** / **Move down**. Layers inside a folder move among its members; root
layers and populated folders move past adjacent root entries, keeping folder
members together. Up moves toward the front. Boundary actions are disabled.
Folders are local, single-level groups. Explicitly created folders survive empty,
can be renamed or deleted, and are saved with their collapse state. Legacy groups
created only by layer labels still disappear when empty. Empty folders appear
@ -31,6 +42,45 @@ not affect device links or source assignments. All document edits support Undo.
*Use the Layer tab for precise dimensions; the inspector keeps the selected layer in view. The header still uses the former Midra Layout name.*
## Size presets
Open the toolbar's **Size presets** icon to find all size and placement presets.
They work on the selected visible, unlocked layers:
- **Fullscreen:** place every selected layer at the output's top-left and set its
width and height to the full output size. Multiple layers overlap intentionally.
- **Quarter:** with one layer, choose one of nine positions: top/middle/bottom and
left/center/right. The layer is half the output width and half its height.
With two selected layers, choose **Up / Down** halves or **Left / Right** halves.
With three or more, choose **Four quarters**. Selections over four repeat the
quarter positions, so extra layers overlap earlier ones.
- **Tiling:** set **X (columns)** and **Y (rows)**, then **Apply tiling**. Layers fill
cells left to right, then top to bottom. Empty cells remain empty; if there are
more layers than cells, positions repeat and the menu explains the overlap.
- **Portrait / Landscape:** swap each layer's dimensions only when needed for
that orientation. Its top-left position stays unchanged; square layers stay square.
This changes the box dimensions, not the rotation of the source picture.
Placement follows the layer list from top to bottom, including selected members
of collapsed folders. Presets use the output dimensions and preserve fractional
pixels for odd screen sizes or uneven tile divisions. These explicit sizes override
the manual aspect-ratio lock when **Keep proportions** is off.
Enable **Keep proportions** at the top of the preset menu to preserve each layer's
current width-to-height ratio. Fullscreen, all nine quarter positions, **Up / Down**,
**Left / Right**, **Four quarters** and tiling then fit the layer inside its assigned
region and center it, leaving space where needed instead of stretching it. Each
selected layer keeps its own ratio. Portrait and Landscape still explicitly swap
dimensions. The toggle starts off and is retained for the current session only.
Tiling shows separate **X (columns)** and **Y (rows)** labels beside bordered numeric
fields. Counts range from 1 to 256 on each axis and are retained for the session.
Each operation is one Undo step, including any crop adjustment from resizing.
Sources, masks, layer names, folders, stacking and device links remain unchanged;
no device transfer occurs. Finish pending numeric/property edits before applying
a preset. Hover an icon for its name, or enable toolbar icon names in Options.
## Move and edit layers
- Click a layer or its list entry to select it alone. **Shift-click** toggles that
@ -177,3 +227,12 @@ Reference images and Output format at the bottom: these apply to the workspace
rather than the selected layer. Right-clicking empty canvas keeps these options
at the top level. Multiple selection retains its Resize together and alignment
actions; crop/mask resets require one selected layer.
### Cancel an accidental close
When a draft window asks whether to **Apply** or **Discard** changes, choose
**Cancel** to return to the window with your edits intact. Cancel neither applies
nor discards them. This also works for clipboard and device-import reviews,
layer properties, layer renaming and batch names/folders. If a layer-list action
triggered the prompt, Cancel stops that action and keeps the draft open.

View File

@ -5,6 +5,84 @@
Choosing an exchange format? See the [file and clipboard feature matrix](format-matrix.md)
for naming, crop, pictures and editable-settings support.
The toolbar has adjacent **Import** (arrow into a box) and **Export** (arrow out
of a box) icons. They open the same import/export menus available from Menu;
opening a menu does not read or write device values. Hover for the label, or
turn on toolbar icon names in Options.
## Recovering a partly readable project
**Open project** attempts to recover usable layers and valid settings from recognized
Canvas Pilot JSON. A report lists skipped or reset content. Repaired documents open
as **unsaved copies**: inspect them and use Save as to choose a new filename. The
original is unchanged. Invalid JSON, unsupported future versions or files without
usable layers cannot be recovered this way; your current work remains open.
Older local input pre-crops and inactive device-input proposals are no longer
supported. Recovery discards them with a warning, so appearance may change. Use
shared **Input settings…** for device preprocessing, then reload affected layers.
Layer crop, fit and masks remain project settings.
## PDF pages and documents as reference pictures
Choose **Add reference images** from the reference list or Import menu, then
select a picture or supported document. For documents, choose **Artwork** (when
available) or **Layout boxes**, select the page/slide/frame and resolution, inspect the preview,
and click **Add reference**. Repeat to add another page. Closing the dialog
leaves the document unchanged. PDF drops open this dialog directly; other exchange
files normally open geometry review, unless the **Reference image** window is open.
| Source | Artwork reference |
| --- | --- |
| PDF | Built-in page rendering; no external application required |
| SVG | Built-in rendering of artwork, text and embedded images |
| PPTX | Slides converted locally by an installed LibreOffice |
| draw.io / XML | Pages converted locally by an installed draw.io Desktop |
| FIG / FIGCRAFT | Built-in FigCraft artwork rendering in the normal build; best effort for native FIG |
| Illustrator | Artboards converted by the existing optional VectorCraft CLI |
| Geometry JSON / Canvas Pilot HTML | Layout artwork including embedded PNG images; HTML uses the exchange data, not custom CSS/scripts |
| CSV / DXF / DWG | Layout boxes from supported geometry, with labels; not a full CAD drawing renderer |
**Layout boxes** is available for every compiled geometry importer. It draws the
detected rectangles and their labels, fitted to their bounds; it does not reproduce
original artwork. This is useful when a converter is unavailable. For a faithful
reference from an unsupported drawing feature, export PDF or SVG from its editor.
PDF pages render on a white background; SVG transparency is retained. References
preserve proportions by default and contain the rendered PNG, so saving and reopening
a project needs neither the source document nor its converter. These are static
pictures, without editable text, automatic layer detection or playback.
The default longest edge is 1920 px; choose up to 4096 px for detailed artwork.
Input files are limited to 64 MiB, PDFs to 256 pages, and the existing 32-reference /
64 MiB combined image limits still apply. Render only the pages you need. Export an
unlocked copy of password-protected PDFs. Inspect font substitutions and complex
PDF effects in the preview; SVG external linked images are omitted.
For PPTX conversion, install LibreOffice and put `libreoffice` (`soffice.exe` on
Windows) on PATH, or set `CANVAS_PILOT_LIBREOFFICE` to the executable. For draw.io,
use `drawio` (`draw.io.exe` on Windows) or `CANVAS_PILOT_DRAWIO`. Executables beside
Canvas Pilot or in its `bin/` folder are also found. On macOS, the executable may
be inside the installed application's `Contents/MacOS/` directory. Conversion uses
temporary copies and has a 60-second timeout; source files are never overwritten.
These converters are optional and are not bundled. At startup Canvas Pilot looks
for executable files using the configured environment override, its own folder
and `bin/`, PATH, and common macOS/Windows installation folders. An invalid explicit
override is reported rather than silently using another installation. Discovery
does not launch the applications or verify their versions. The same detected path
is used for conversion; runtime failures are still reported.
Open **Application menu → Software integrations…** to see each tool, its status,
path and the features it enables. Missing integrations remain listed there for
setup, but their unavailable actions are hidden: PPTX/draw.io references default to
**Layout boxes** without an Artwork choice, and Illustrator is omitted from file
filters and export choices when VectorCraft is missing. Built-in geometry import
and export remain available for PPTX/draw.io. Restart Canvas Pilot after installing
software or changing an override; discovery is a session snapshot, not a live
connection. No executable paths are saved in the project.
Draw.io Desktop may require a graphical desktop session. The existing VectorCraft setup is described below.
## Paste layer values and import geometry
Check the [clipboard feature matrix](format-matrix.md#clipboard-matrix) for your
@ -13,7 +91,9 @@ application: its file and copy/paste workflows can support different features.
Drop SVG, draw.io/XML, geometry JSON/CSV, DXF/DWG, HTML, PPTX, FIG, FIGCRAFT or Illustrator files into
the window to open the same geometry review as **Import → Geometry file…**.
Native codecs still require their normal build options/dependencies. Filename
extensions are case-insensitive; PNG/JPEG/BMP drops remain reference images.
extensions are case-insensitive; PNG/JPEG/BMP and PDF drops open as references.
While the **Reference image** window is open, supported document drops also open
as references instead of layer geometry.
Multiple geometry files appear in the **File / page / frame / slide** chooser;
choose one document/page to map at a time. Reading runs in the background, and
nothing changes in the layout until Apply. The entire geometry drop is limited
@ -28,8 +108,12 @@ to 16 MiB; a failed document leaves the batch unapplied and reports its filename
no additional file/paste buttons inside the review. Multiple documents/pages
retain their page chooser.
3. Under **Destination layers**, choose **All layers**, **Selected layers**, or
**Folder: …**. Existing selection initially scopes and pre-maps the import;
with no selection, choose destinations individually from All layers. Changing
**Folder: …**. Imports try exact included-item counts against the selection, then all
available layers in its shared folder, then all available layers. Background
items and hidden/locked destinations do not count. Selections spanning folders
skip the folder fallback. Matches map in layer order; review before applying.
If no count matches, the initial scope remains available for manual mapping.
Choosing a scope manually disables automatic scope changes for that review. Changing
the scope never changes canvas selection and preserves mappings still in scope.
Hidden/locked layers are excluded. Each source item has a prominent destination
dropdown and collapsed **Geometry · before / after** details. Uncheck **Include
@ -88,10 +172,12 @@ does not change what Canvas Pilot pastes.
To copy only appearance, uncheck Position and Format. Expand **Appearance** to
choose Crop & fit, Blanking, or both. Source assignments, device mappings and
input settings stay unchanged. Crop & fit requires matching source dimensions
after local input crop; normal crop also needs compatible box proportions. The
review explains mismatches before allowing import. Match the source dimensions,
include Format, or uncheck Crop & fit as appropriate. Blanking works independently
input settings stay unchanged. Crop edges adapt proportionally to the destination
input dimensions. The destination layer’s **Advanced fit** stays selected; the
copied fit mode does not replace it. A normal crop that does not
match the destination box uses **Centered (fit)**, preserving ratio without
stretching. You do not need to match source dimensions or include Format.
Blanking works independently
of source dimensions. A failed batch changes nothing; a successful paste undoes
in one step.
@ -106,7 +192,8 @@ SVG import accepts square-corner rectangles and simple closed rectangular
paths/polygons, including translated/scaled groups and inline styles. It applies
page dimensions and `viewBox` transforms, using CSS units at 96 px/in. Coordinates
are relative to the SVG page; exporting only a selection may lose its original
document position. The SVG is used for bounds, not rendered as a reference image.
document position. This geometry-import action uses bounds. For the complete
SVG artwork, use **Add reference images** instead.
A first full-page rectangle or image is marked as a possible background. Uncheck
**Include full-page background** to exclude it from the count and mapping. This
@ -121,6 +208,20 @@ styles for predictable results. Files are limited to 16 MiB, 256 rectangles plus
64 levels of nesting. SVG imports retain the same outline and position-only
choices as draw.io imports.
### Clipboard detection and fallback
Paste examines the text supplied by the clipboard. Unrecognized text is not
assumed to be draw.io XML. For well-formed HTML supplied as text, it tries a single
embedded draw.io document, then a single embedded SVG if the first candidate fails.
The review identifies the chosen representation and any rejected candidates.
Only the embedded drawing's coordinates are imported; surrounding HTML layout and
CSS are not. Multiple drawings of the same format require exporting a single file.
This does not enumerate native operating-system clipboard formats. PowerPoint
objects copied inside PowerPoint remain unsupported; use **Import geometry** with
the **.pptx** file. Invalid Canvas Pilot data keeps its specific error rather than
silently dropping settings in a fallback.
### Figma SVG clipboard text
The supplied [Figma SVG sample](../../../crates/canvas-pilot/tests/fixtures/figma-rectangles.svg)
@ -235,7 +336,7 @@ and [project save contract](../../interfaces/canvas-pilot.md).
Visual crop mode also provides **Reset crop** beside **Done adjusting crop** in
layer properties. It restores 100% content zoom and centered offsets, keeps the
visible box and source/input crop unchanged, and leaves visual editing active.
visible box and processed source dimensions unchanged, and leaves visual editing active.
The reset is undoable.
The toolbar’s **Viewport options** cog contains **Keep aspect ratio when resizing**
@ -302,7 +403,7 @@ Midra layer lists omit unassigned source slots (`NONE` or empty). Assigned input
Destination choices in **Midra mapping & transfer…** now save immediately on the editor layer and support Undo. Save the project JSON to keep links across sessions. Links include screen and layer IDs and survive refreshes and selection changes. Choose the empty destination on the linked screen to unlink. The direct send button is available beside Midra mapping & transfer and in Export; in **All layers** scope it includes unselected, hidden and locked linked layers, grouped by screen. Its label changes to **Send selected links** or **Send folder links** in those scopes. Midra mapping & transfer… opens mapping configuration for the current scope. Preview/Program and sizing still use the current export options.
Every explicit send now includes WebRCS’s preset apply pulse (`xUpdate` false → true). This applies staged geometry when automatic updates are disabled, including a repeat send where WebRCS already shows the desired values.
Every explicit layer-layout send includes WebRCS’s preset apply pulse (`xUpdate` false → true). This applies staged geometry when automatic updates are disabled, including a repeat send where WebRCS already shows the desired values.
**Send all linked layers** sends immediately using saved links and the current target and sizing settings, without opening the export window. The button shows progress and its tooltip reports completion. Invalid links or send failures open the export window with the error.
@ -373,18 +474,18 @@ mode only (except outline-only layers).
## What the project saves
Project JSON includes source formats, both crop stages, geometry, layer ordering,
Project JSON includes processed source formats, layer crops, geometry, layer ordering,
folders, visibility/locking, pivots, Midra links, reference images, selection,
viewport and positioning settings. It also saves snapping/grid settings, group
resize mode, collapsed folders, capture input assignments, the last captured
stills, guide opacity and refresh settings. Saved stills work offline; automatic
refresh reopens paused until you capture or resume it explicitly.
refresh resumes when the matching device is connected and snapshots are available.
Connection history, startup connection, theme and Program permission remain in
application preferences. Unsaved drafts, undo history, open menus, active editing
gestures and pending device operations are temporary. Transfer scope, target bank,
sizing strategy and the permission to send advanced input edits remain session choices.
Explicitly saved input correction proposals persist, but always reopen inactive.
sizing strategy and shared input-window drafts remain session choices.
Legacy input proposals and local pre-crops are no longer saved.
See [saved input corrections](advanced-exchange.md#saved-input-corrections).
See the [complete persistence audit](../../interfaces/canvas-pilot-persistence-audit.md)
and [versioned project contract](../../interfaces/canvas-pilot.md).
@ -396,7 +497,7 @@ for a comparison of project saves, plain geometry import and snapshot restoratio
In **Export layers**, expand **Canvas Pilot settings** and enable
**Include extra Canvas Pilot parameters (experimental)** to
store the exported layers' source/crop settings, fit modes, masks, saved input proposals, names, folders, links and workspace
store the exported layers' source/crop settings, fit modes, masks, names, folders, links and workspace
setup alongside the geometry. It is available for SVG, draw.io, JSON, CSV, DXF,
HTML, PPTX and FigCraft. Images/capture assignments are excluded from this snapshot; the
background and placeholder options remain separate. DWG, FIG and Illustrator show why the
@ -453,7 +554,9 @@ $env:MIDRA_VECTORCRAFT_CLI = 'C:\Tools\VectorCraft\vectorcraft-cli.exe'
Select **Illustrator (VectorCraft)** in Export layers, or import an `.ai` file
through Geometry file. Conversion is local and temporary; it does not use a cloud
service. A missing converter produces an error without changing the project.
service. Illustrator choices appear only when VectorCraft was detected at startup.
A converter that subsequently disappears or fails produces an error without changing
the project. See **Software integrations…** for detection and setup.
Use SVG if you do not want to install or configure the converter.
Illustrator exchanges layer geometry and optional artwork, not the complete editor project.

View File

@ -45,6 +45,15 @@ See the [advanced feature matrix](advanced-exchange.md) for every saved feature.
See also [conversion examples and losses](conversion-losses.md) before passing files through several editors.
## Document reference pictures
PDF pages and SVG artwork can be rendered directly as reference images. Other
supported documents also have reference import, using built-in artwork rendering,
optional local converters or an explicitly labelled layout-box preview.
See the [reference-picture support table](files.md#pdf-pages-and-documents-as-reference-pictures)
for each format's requirements and limits. This does not add PDF geometry export
or recover editable layers from a PDF.
## File exchange matrix
All eleven exchange formats import and export layer positions and sizes. Geometry
@ -119,7 +128,7 @@ choices. Canvas Pilot copies also offer an **Appearance** group with **Crop & fi
and **Blanking**. Crop edges preserve normal zoom/offsets and all explicit fit
modes; masks retain their Layer/Source reference and proportions. Enable **Rename destination layers** to apply supplied names; it starts unchecked.
Crop & fit requires matching source dimensions after input crop; it never changes
Crop & fit requires matching processed source dimensions; it never changes
source assignments or device mappings. If dimensions differ, match the local source
or uncheck Crop & fit. Blanking can be pasted independently. Older clipboard text
still offers **Crop zoom** when present, without full crop offsets or fit/masks.

View File

@ -16,30 +16,30 @@ Valid output presets and numeric resolution edits apply immediately; invalid dra
leave the output unchanged and are retained for correction.
The same window offers numeric camera zoom relative to fit-to-screen and a
**1:1 display pixels** action; camera changes never modify crop geometry.
Scroll zoom and the Zoom tool retain the full precision camera range. At extreme
zoom, decorative screen titles and reference-hint text are hidden before their
camera-scaled glyphs would slow the renderer; layers, handles, fixed-size layer
labels, pixel guides and placement remain visible and editable.
Select one layer and click its **Layer resolution** card to open **Layer properties**:
1. Enable advanced editing in **Source**, choose a local **Editor input**, then its original **Source format** and native
dimensions. Editor inputs are planning identities, not device routing commands.
2. Set **Input resolution** to the usable size. Typing a custom size centers the
input crop; edit L/R/T/B for asymmetric placement. Crop edges stop at zero
when dragging; negative or non-finite typed/pasted values are not accepted. Native-size changes reset
the draft crop to the full source before review. A custom input retains the
original Source format, e.g. 16:9 native 1920 × 1080 cropped to 1920 × 1000.
3. Set **Layer resolution** to the final visible box. Use the aspect toggle to
1. Use **Source → Open shared input settings…** for physical input preprocessing.
Review and send input changes separately, then reload affected layers. The
former local Editor input/pre-crop controls have been removed.
2. Set **Layer resolution** to the final visible box. Use the aspect toggle to
enter an independent custom width and height. Layer changes apply immediately;
the selected measurement anchor stays fixed. Source/input changes require Apply.
4. Use **Layer crop / zoom & position** for zoom (100–10000%) and X/Y offsets in output pixels.
the selected measurement anchor stays fixed. Device input changes require their own review and send.
3. Use **Layer crop / zoom & position** for zoom (100–10000%) and X/Y offsets in output pixels.
Zoom is bounded to 100–10000%; negative or non-finite entries are rejected.
X/Y offsets remain signed for left/up positioning; they are not crop amounts.
These controls operate on the applied formats and update immediately as edited.
A continuous zoom/offset drag is one Undo step;
**Recenter** preserves zoom; **Reset crop** returns to the minimum centered
cover crop. Invalid typed offsets show the permitted range and do not apply.
5. Click **Adjust layer crop** in the selected layer’s parameters, below its format
4. Click **Adjust layer crop** in the selected layer’s parameters, below its format
summary, or **double-click a layer on the canvas**, to drag or arrow-nudge
content inside the fixed box. The button
highlights while active; double-click again or click **Done adjusting crop** to leave the mode.
highlights while active; press **Enter**, double-click again or click **Done adjusting crop** to leave the mode.
Drags clamp at valid crop boundaries; Escape cancels a drag and leaves this
mode. Wheel zoom still controls the camera. A source-coordinate test pattern
illustrates framing; it is deliberately separate from the screen reference.
@ -49,13 +49,12 @@ Select one layer and click its **Layer resolution** card to open **Layer propert
Grab the faded area to reframe content too; other visible layers covering it
take precedence. Empty space beyond the usable input is not draggable content.
Sources shared by both layers share the input crop. The dialog names affected
layers; each keeps its independent layer crop. Shared changes undo atomically,
and edits affecting a locked layer require it to be unlocked first.
Layers keep independent crops and masks. Physical input preprocessing is shared
by every layer consuming that signal, including layers outside this project.
Moving/alignment preserves crops. Resizing keeps content zoom and the retained
center where possible, automatically shifting the crop when needed to fit the
new size. Source/input changes do the same when applied in Layer properties.
new size. Reloading from the device refreshes processed source dimensions.
No recentering or extra acceptance is needed. Undo restores both size and crop.
**Layer properties → Crop** activates visual crop editing while the tab is open.
Switching to Source/Layer or closing the window turns it off; no extra button is needed.
@ -65,8 +64,8 @@ The standalone inspector and context-menu crop controls remain available.
visible box fixed; **Reset crop** returns to the minimum centered crop.
**Calculated crops / provisional WebRCS mapping** shows input crops in native
pixels, advanced crops in usable-input pixels, combined retained native bounds,
**Calculated crops / provisional WebRCS mapping** shows layer crops in processed-source
pixels, retained bounds,
visible size/center, and projected full-input geometry. These values are not a
verified device recipe: Centered-mode container behavior, crop units/limits and
quantization still require offline firmware verification. No hardware commands
@ -78,6 +77,30 @@ for equations and worked examples.
*The cyan helper frames the content while the visible layer box stays fixed. The header still uses the former Midra Layout name.*
## Crop ratio presets for embedded black borders
In **Layer properties → Crop**, use the **Crop borders to ratio** box: **4:3**,
**16:9** or **16:10**. These presets trim symmetric borders baked into a signal,
such as a 4:3 PowerPoint slide sent inside a 16:9 video resolution. They shrink
the visible layer around its center to the requested ratio and crop its picture
at the same time, rather than stretching the slide. The largest rectangle of
the chosen ratio that fits inside the uncropped layer bounds is retained. Each
click restores those bounds first, so switching ratios replaces the previous crop.
For example, 4:3 on a full 1920×1080 layer removes 240 pixels from each side and
leaves 1440×1080. Conversely, 16:9 on an 800×600 layer removes 75 pixels from the
top and bottom and leaves 800×450. Repeated clicks on the same ratio do not progressively crop the picture.
Right-click selected layers in the viewport or layer list and choose **Crop
presets** to apply the same correction to several layers in one Undo step.
Enable **Crop within existing crop** to keep the old behavior and trim the
current crop further. This session-only toggle is off by default and is shared
between the properties and context menus. Presets do not detect black pixels.
Use manual crop controls for asymmetric borders. Explicit layer-fit modes are retained
and fit the cropped picture into the new box. Shared input settings, source routing
and masks are unchanged. No device command is sent. Finish pending numeric or
property edits before applying a preset.
## Display/export precision and midpoint handles
Geometry in the viewport, inspector and calculation view is shown to the nearest
@ -96,42 +119,22 @@ to both kinds of resize handles.
Apply buttons are muted and disabled when their values already match the layout.
Pending changes make Apply solid purple. This applies to position/size, output
resolution drafts, source/input formats, names/folders, and mapped imports. Each
resolution drafts, names/folders, and mapped imports. Each
section tracks its own values; reverting an edit clears its pending state.
**Source is an advanced section**, disabled until **Edit advanced input settings
and include my edits when sending** is checked. Its device controls mirror the
linked Preview layer's current input and active plug in WebRCS Advanced Input:
content ratio, transform ratio, custom ratio, layer fill, input crop preset and
four pixel crop edges. Usually keep these settings on the Midra. Input crop
runs before dynamic layer crop/zoom without resizing the layer bounding box;
this is device processing, not an editor-only effect. Inputs are shared, so an
input edit can also affect other layers and Program.
**Source** links to the [shared Input settings window](#shared-device-input-settings)
for native device preprocessing. These input-only edits require their own explicit
review and send; a layer-layout send never includes them.
Opening Source, checking the box, or changing a value does not send. Only fields
actually edited are staged for the next explicit Send, and only when that send
includes a destination routed to the same input/plug. Untouched aspect/crop
settings stay as they are on the machine. Unchecking discards staged edits.
The permission and staged device edits are session-only: disconnecting, changing the device
address or loading a project clears them. Source routing is never changed.
Refresh/load after sending to inspect the resulting device content dimensions.
The separately labeled **Editor source model (local geometry)** retains the
existing offline format/input-resolution calculations, also gated by the checkbox.
Its native dimensions are metadata, not device timing commands. Its local input
correction still folds into exported *layer* crop; it does not configure the
shared hardware input. Apply source changes commits this local model, whereas
the device controls above wait for Send.
Layer properties has five tabs: **Source** for native/input resolution and input
crop, **Layer** for the final visible box, **Crop** for content zoom and offset,
**Mapping** for the saved Midra screen/layer link, and **Preview** for capture, timed refresh, preview visibility, guide opacity and the cropped image preview. Editor input identity belongs to the opt-in **Source** tab.
Layer properties has six tabs: **Source** links to shared input settings,
**Layer** edits the visible box, **Crop** edits content framing, **Mask** edits
blanking, **Mapping** edits device destinations, and **Preview** controls capture,
refresh, preview visibility and guide opacity.
The right-click properties entries open their matching tab directly.
Mapping offers device screen/layer selectors when connected, or numeric IDs offline.
Link edits apply locally immediately and support Undo. **Unmap** removes the link,
excluding the layer from linked sends and loads; it does not change the device.
Editor input identity remains a separate source setting requiring Apply.
Switching tabs retains pending Source edits, which require Apply. Layer size and
Layer size and
Crop changes apply immediately; normal zoom/offset drags are one Undo step.
Position/size edits commit on Enter or focus loss, output resolution changes
@ -177,28 +180,34 @@ pixels, apply first; the retained image is centered and clipped to that containe
1:1 preserves pixel scale, Centered preserves proportions with transparent
margins, Fullscreen stretches, and Cropped fills while clipping overflow.
Resize changes the container and preserves these crop edges. For **1:1**, double-click
the layer or choose **Adjust layer crop** to show the crop helper. Drag a side to
trim/restore that source edge; corners adjust two edges independently. The cyan
outline shows the retained image, with the usable source faded behind it. It
never zooms or stretches the image, and ignores aspect lock/pivot scaling.
The retained picture stays centered, so its outline contracts/expands symmetrically
even though only the chosen source crop edge changes. The container stays fixed.
Drag anywhere inside the layer, including empty margins outside the retained
picture, to reposition the crop as a whole. The picture follows the pointer;
opposite crop edges trade pixels, preserving the retained width/height and 1:1
scale. Movement stops at the usable source boundaries. Arrow keys move by one
source pixel; Shift+arrows move by ten. The layer container stays in place.
Use viewport zoom/pan to reach handles outside the screen. Each drag is one Undo
step; Escape cancels an active drag and exits the helper. Numeric crop fields stay
in sync. **Centered** and **Cropped** fit automatically, so their helper button
and context-menu action are disabled and double-click does not open a helper.
Their numeric crop edges remain editable in Crop properties. Fullscreen continues
to use the numeric crop controls. Unchecking
resets to normal centered cover framing. Input/global inheritance is intentionally
omitted. Pending Source edits remain staged and require Apply as usual.
Resize changes the container and preserves these crop edges. Double-click, Enter,
or **Adjust edge crop** opens the advanced helper. Its **green** outline shows the
retained image; the full usable source appears faded behind it. Drag a side to
trim/restore that edge, or a corner to change two edges independently. The image
stays still during the drag, with discarded areas shaded. On release, the chosen
fit recenters/refits the retained image inside the unchanged container. Aspect
lock and pivot scaling do not affect this edge operation.
Midra loads preserve all four explicit modes and open the checkbox automatically.
Use viewport zoom/pan to reach handles outside the screen. Each drag is one Undo
step; Escape cancels it. In 1:1 mode, dragging the picture or using arrow keys also
repositions the crop without changing its retained size (Shift moves ten pixels).
Numeric crop controls remain available in Crop properties.
**Convert to Smart crop**, in the right-click menu and Crop properties, switches
to Canvas Pilot's normal zoom/position algorithm. It preserves an exactly matching
crop; otherwise it resets to centered cover framing, so the picture can change.
**Convert to Edge crop** appears in the same places for a Smart crop. It keeps the
current picture, crop, container and mask exactly as they are, selects Centered fit,
and opens the green edge helper. Undo returns to Smart crop. Unchecking Advanced
layer fit resets to centered cover framing. Pending Source edits still require Apply.
Device loads use Smart crop when the retained picture exactly fills the container
with uniform scaling and the crop is representable by the normal algorithm.
Centered/Cropped fits with rounding differences of up to one output pixel per
image dimension also use Smart crop: a tiny symmetric crop adjustment restores
the exact aspect while preserving the source center and layer container. Larger
letterboxing/overflow differences and stretching retain their advanced fit.
Existing saved projects keep their explicitly chosen modes.
Sends use container dimensions regardless of sizing strategy, and never change
input routing. Aquilon sends reject advanced fit until its adapter supports it.
Projects/recovery preserve the mode. Pixel rounding is approximate pending the
@ -210,8 +219,8 @@ Projects/recovery preserve the mode. Pixel rounding is approximate pending the
- **Layer** (default): edges are measured from the layer boundary and stay
proportional to the layer when resized.
- **Source**: edges are measured from the usable source picture, after local input
cropping but before layer crop/zoom and fit. The magenta guide can extend outside
- **Source**: edges are measured from the usable source picture, after device input
preprocessing but before layer crop/zoom and fit. The magenta guide can extend outside
the layer and follows the picture when panning or zooming. A faded source preview
helps position it. Only the intersection with the visible layer is rendered.
@ -254,16 +263,23 @@ they are never exported or sent to the device. It works with normal crop and eve
- Enter Left/Right/Top/Bottom distances in output pixels.
- The alignment menu aligns the mask window to the selected reference’s edges or center.
- **Center mask** preserves its size; **Reset mask** removes all blanking.
- **Enter** opens crop editing for the selected editable layer, just like
double-click. Press it again to finish crop/mask editing and keep the live changes. When typing in
a numeric field, Enter confirms that value first; press Enter again after leaving
the field to finish. Other unapplied properties use the existing Apply/Discard
review, so finishing cannot silently discard them.
- Undo restores a complete drag; Escape cancels the active drag.
Opposite edges can meet to blank the whole layer, and remain draggable afterwards.
Masking never modifies the crop, fit, image scale or layer bounds. Blank areas
reveal lower layers. A mask over already cropped or transparent pixels has no
visible effect. Mask proportions stay relative to the selected reference. Project files and
embedded snapshots retain masks; plain geometry exports omit them. Midra load/send
supports the resulting blanking for either mode. Loading from Midra returns a
layer-relative mask because the device does not store the editor’s source reference.
Aquilon masking remains unavailable.
embedded snapshots retain masks; plain geometry exports omit them. Midra and Aquilon
load/send support the resulting blanking for either mode. Device loads return a
layer-relative mask because devices do not store the editor’s source reference.
Aquilon supports rectangular blanking with Centered framing; its explicit fit and
Cut & Fill modes are separate limitations. Sending a zero mask clears destination
blanking in the reviewed transfer.
<!-- Screenshot recipe: ../images/capture.md#advanced-guide-captures -->
![Mask tab showing left-edge blanking and a smaller magenta reveal window inside the layer](../images/07-guide-mask.png)
@ -288,8 +304,8 @@ layer cropping or masking. They can correct stretched content, but an arbitrary
ratio can also introduce distortion. Leave Native / Signal Aspect Ratio unless
correction is intentional.
Canvas Pilot already exposes both device selectors under **Source → Edit
advanced input settings**, with Custom ratio encoded in thousandths (0.250–10.000).
Canvas Pilot exposes both device selectors in **Input settings…**, with Custom
ratio displayed as 0.250–10.000:1 and encoded in thousandths.
They are staged device controls, not persistent local image deformation. Merely
opening the controls never writes. A local source resolution is a separate
quantity and should not be changed just to pretend a ratio correction occurred.
@ -301,4 +317,101 @@ proportions and avoid applying a correction twice when loading device-reported
content dimensions. These details need evidence before claiming an exact device
round trip.
Saved device input corrections are optional [inactive proposals](advanced-exchange.md#saved-input-corrections); opening a file never enables or sends them.
Device input drafts are session-only; [project snapshots omit them](advanced-exchange.md#saved-input-corrections). Opening a file never changes an input.
## Shared device input settings
Open **Input settings…** from the application menu, or **Open shared input
settings…** in the layer's Source tab. Choose a physical input independently of
editor layer selection. On Aquilon, **Read input settings** loads that input's
additional controls without downloading the complete device store.
This edits preprocessing shared by every consumer of that input, including
Program and layers outside the project. Nothing is sent while dragging, selecting
an input, capturing an image or opening the window. Use **Send changes** above the editor to apply the edited fields directly, with fresh device
validation and verified readback.
The input selector, **Send changes**, pending-change count and undo/discard/reload
controls stay above the scrolling editor. The larger **Input crop** workspace
contains its own protection toggle and live-capture control. Expand **Crop values
& presets** for exact edge values. Use the **Input processing** category picker
for Aspect, Color, Processing, Keying or LUT; only available categories appear.
Narrow windows stack processing below the crop workspace. **Send changes** is
highlighted when changes are pending; sending remains an explicit action.
- **Keep device values:** each category has this toggle. Check it to discard that
category’s draft edits, disable its controls and leave it untouched when sending.
Crop protection prevents crop edits, but wheel zoom, middle-drag panning,
**View zoom** and **Fit view** remain available. These only change your view;
the captured picture and sizing grid remain at full opacity. Uncheck to edit again.
All categories start protected. Uncheck only the categories you want to edit;
unchanged fields are never sent. Protection is retained when discarding edits,
and all categories return to protected when reloading the input.
- **Input crop:** drag edges/corners or move the retained box. Crop zoom reduces
or expands the retained region around the selected pivot using the **− slider +**
percentage control. The slider spans **100–500%**; click its numeric value to
enter a percentage beyond that range, within device limits. **100%** clears
all crop edges exactly. This does not add a second zoom stage. Numeric edges use native device crop coordinates.
- **View zoom:** changes only the editor view; wheel zooms and middle drag pans.
Reset crop, Undo input edit and Escape during a drag help recover an edit.
- **Aspect**, **Color** and **Processing** expose adapter-specific settings.
Keying and LUT controls appear only when supported/available. Resource allocation,
signal negotiation and HDCP remain in WebRCS.
- **Capture input (live):** refreshes while enabled and this window is open, using
the same interval as automatic layer previews (10 seconds by default, at least
5 seconds). Matching input requests share a capture. Closing the window or
switching the toggle off stops its refresh requests.
Captured pixels appear directly inside the **device's captured crop region**;
unknown pixels retain the sizing grid. Moving the draft crop never moves or
stretches those pixels. After Send, the old capture is cleared while settings
are applied and verified; **Refreshing capture…** remains until a new capture
arrives. Unverified capture geometry shows the grid rather than a distorted image.
Midra’s already-cropped PNG and Aquilon’s full-frame thumbnail are handled
separately, avoiding a second crop. No raw/pre-crop endpoint is confirmed.
Drafts are session-only and are not included in projects or exports. Switching
inputs retains their drafts; changing connection discards them. Reload selected
input replaces its draft with device values. If another controller, signal or plug
changes, refresh and review before sending. After changing input geometry, reload
its affected layers before sending their layout.
**Current Aquilon limitation:** framing transfers still reject inputs with active
shared crop or aspect correction. The input editor can edit those settings, but
reloading does not bypass that restriction. Correct conversion of those processed
inputs remains pending; the removal of local pre-crop does not claim that support.
The old local source pre-crop model and saved input proposals have been removed.
Projects retain processed source dimensions and independent layer framing; legacy
native projects can be opened with a reported best-effort recovery.
Enabling **Enable input preview** in the right-click menu or Preview properties
requests a fresh still for the configured input immediately. It does not enable
recurring auto-refresh. A capture already in progress or the five-second request
cooldown can defer that request; no device request is made for a local picture or
when no capture input is configured.
### Captured picture proportions
Input captures and local reference pictures fit centered inside the source format
without changing their ratio. Midra captures already include the input crop; they
are not stretched back to the uncropped signal size. The layer’s crop, zoom, fit
and mask then apply normally. **Centered (fit)** preserves proportions;
**Fullscreen (stretch)** still deliberately stretches. This preview does not
change source dimensions or device input settings.
### Switching to a different input size
Selecting a physical input in Source properties or a different capture input in
Preview adapts that layer’s source dimensions to the valid signal. Its position
and outer size stay fixed. Normal crop mode retains zoom and normalized focus
(clamped at the new image edges); advanced fit retains proportional crop edges.
Other layers keep their source dimensions, even if they previously shared the
same editor source. Undo restores the previous framing. Input routing remains
opt-in through **Change input**, applied only on Send.
Explicit input-switch sends also adapt framing when a saved source size differs.
Midra inputs with applied crop are supported once crop controls and processed
image dimensions agree. Input crop is already included in those dimensions;
layer crop and fit apply afterward. Input aspect correction and Aquilon shared
input crop retain their existing transfer restrictions.

View File

@ -25,6 +25,18 @@ These packs reuse the fonts already bundled with Canvas Pilot. Version 1 and 2 p
contain translations only: they neither install fonts nor reduce the current
application download size. Ukrainian uses the existing Cyrillic coverage.
Installed packs appear in a compact, searchable list. Search by pack ID, language
name, native name or locale code; **Clear** restores the full list. Each row shows
the language count and revision, with a dot marking the pack currently in use.
Only the selected pack's contents are shown, beside the list on wide windows or
below it on narrow windows. Both lists stay bounded and scroll independently.
Click a language in the selected pack to preview it with the same 20-second
confirmation and rollback as the main language picker. **Remove pack…** stays
above the contents and still asks for confirmation. Newly installed or updated packs are selected automatically.
Search and selection remain
separate from the theme manager and are remembered only during the session.
## Make your own pack
Download these three editable example files into the same folder:

View File

@ -86,6 +86,8 @@ Open **Menu → Open all settings… → Appearance**:
**50% to 200%**. Canvas artwork and fixed-size labels follow interface scale only.
- **Use high contrast:** select a black-based theme with white text, bright accents
and stronger control borders. It also appears as **High Contrast** in the theme browser.
Click it again while active to return to your previous theme. This also works in
the recent-theme menu; if there is no previous theme, it returns to Midra Dark.
Scale values update while dragging, but resizing applies only after releasing
the pointer. Typed values apply after finishing text entry. Preferences are
@ -108,11 +110,15 @@ used themes, newest first. **More themes…** opens the complete picker with col
swatches: Midra Dark plus all 18 themes from the SOTV song-database theme folder.
A fresh installation lists only Midra Dark until other themes are selected.
Selecting a theme updates the UI and viewport immediately and saves the recent
history across restarts. Reusing a theme moves it to the top without duplicates.
history across restarts. The picker stays open so you can try several themes;
close it with its window close button when finished. Reusing a theme moves it to
the top without duplicates.
Closing the picker without choosing leaves the theme and history unchanged.
Use **Theme packs** to install additional palettes; see [Add a theme pack](theme-packs.md)
for Tokyo Night, Catppuccin, Detroit: Become Human and Vivid World examples.
The viewport, grid, layer boxes and source test patterns use the selected palette;
selected layers remain gold (darker gold for contrast in light themes). Imported
selected layers use the palette’s selection accent. Imported
reference images retain their colors. Theme and history survive opening projects
and are not included in project JSON or geometry exports.
@ -165,6 +171,7 @@ Open **Menu → Open all settings…**, **Options → Open all settings…**, th
**Open all settings…** entry, or **Ctrl/Cmd+,**. The window groups the available controls:
- **Appearance:** themes, recent choices, icon captions and source-coordinate preview.
- **Theme packs:** install/update ZIP palettes, try their themes and remove packs.
- **Editing:** aspect-ratio lock, movement snapping and a keyboard/mouse reference.
- **Reference images:** import and access to the current project's image settings.
- **Files & settings:** the settings-file path, copy-path action and restore defaults.

View File

@ -0,0 +1,110 @@
# Add a theme pack
Theme packs add palettes without rebuilding Canvas Pilot. They change the app,
viewport and source-coordinate helper colors; they do not change projects,
device transfers, imported pictures, fonts or interface size.
## Install and try the collections
Download a ZIP, leave it zipped, then open **Settings → Theme packs → Install theme
pack…**. Select a pack, then click one of its themes to try it immediately. It also
appears in **More themes…** and recent themes. The picker stays open while you
try alternatives. Selecting **High Contrast** twice returns to your last theme,
including an installed one.
Choose either collection, or install both:
- [Video-game themes](../../theme-packs/video-game-themes.zip): **6 themes** —
Deep Rock Galactic, Detroit: Become Human, Dispatch, Helldivers, Ravenswatch
and Vivid World.
- [Classic themes](../../theme-packs/classic-themes.zip): **11 themes** —
Catppuccin Mocha, Dracula, GitHub Dark/Light, Gruvbox Dark, Monokai, Nord,
One Dark, Solarized Dark/Light and Tokyo Night.
Each ZIP is one normal theme pack. Select **video-game-themes** or **classic-themes**
in the manager to try its palettes. Removal or replacement applies to that whole
collection. Individual downloads below remain available; installing both an
individual pack and its collection keeps separate copies.
### Video-game themes
| Pack | Palette | Editable manifest |
| --- | --- | --- |
| [Detroit: Become Human](../../theme-packs/detroit-become-human.zip) | Deep blue, pale text and cyan android-inspired accents | [manifest.json](../../theme-packs/detroit-become-human/manifest.json) |
| [Ravenswatch](../../theme-packs/ravenswatch.zip) | Midnight blue, ivory and crimson | [manifest.json](../../theme-packs/ravenswatch/manifest.json) |
| [Vivid World](../../theme-packs/vivid-world.zip) | Midnight navy, violet, pink and cyan crystal accents | [manifest.json](../../theme-packs/vivid-world/manifest.json) |
| [Deep Rock Galactic](../../theme-packs/deep-rock-galactic.zip) | Dark, gold/molten-orange accents | [manifest.json](../../theme-packs/deep-rock-galactic/manifest.json) |
| [Dispatch](../../theme-packs/dispatch.zip) | Dark, yellow/cyan accents | [manifest.json](../../theme-packs/dispatch/manifest.json) |
| [Helldivers](../../theme-packs/helldivers.zip) | Dark | [manifest.json](../../theme-packs/helldivers/manifest.json) |
### Classic themes
| Pack | Palette | Editable manifest |
| --- | --- | --- |
| [Tokyo Night](../../theme-packs/tokyo-night.zip) | Dark blue with cool cyan accents | [manifest.json](../../theme-packs/tokyo-night/manifest.json) |
| [Catppuccin Mocha](../../theme-packs/catppuccin.zip) | Soft charcoal and pastel accents | [manifest.json](../../theme-packs/catppuccin/manifest.json) |
| [Dracula](../../theme-packs/dracula.zip) | Dark | [manifest.json](../../theme-packs/dracula/manifest.json) |
| [GitHub Dark](../../theme-packs/github-dark.zip) | Dark | [manifest.json](../../theme-packs/github-dark/manifest.json) |
| [GitHub Light](../../theme-packs/github-light.zip) | Light | [manifest.json](../../theme-packs/github-light/manifest.json) |
| [Gruvbox Dark](../../theme-packs/gruvbox-dark.zip) | Dark | [manifest.json](../../theme-packs/gruvbox-dark/manifest.json) |
| [Monokai](../../theme-packs/monokai.zip) | Dark | [manifest.json](../../theme-packs/monokai/manifest.json) |
| [Nord](../../theme-packs/nord.zip) | Dark | [manifest.json](../../theme-packs/nord/manifest.json) |
| [One Dark](../../theme-packs/one-dark.zip) | Dark | [manifest.json](../../theme-packs/one-dark/manifest.json) |
| [Solarized Dark](../../theme-packs/solarized-dark.zip) | Dark | [manifest.json](../../theme-packs/solarized-dark/manifest.json) |
| [Solarized Light](../../theme-packs/solarized-light.zip) | Light | [manifest.json](../../theme-packs/solarized-light/manifest.json) |
Tokyo Night adapts the [upstream palette](https://github.com/folke/tokyonight.nvim),
and Catppuccin uses [Mocha colors](https://catppuccin.com/palette/). Their license
notices travel inside the ZIP and can be viewed under **Attribution and licenses**.
The Detroit, Vivid World, Ravenswatch, Dispatch, Helldivers and Deep Rock Galactic themes are
original, unofficial color interpretations;
they include no game artwork, fonts or code and are not endorsed by the games' owners.
### Moving from the old combined pack
The two collections replace the former `extra-themes.zip` download and have new
pack IDs. Install the desired collections, select a theme from one of them, then
remove **extra-themes** in Settings if you no longer need its duplicate entries.
Existing installations and saved choices are not renamed or deleted automatically.
Removing a pack while its theme is active falls back to Midra Dark. Standalone
packs, including older Minecraft installations, remain user-managed.
## Manage packs
The manager uses a compact, searchable pack list and shows the contents of only
one selected pack. Search by pack ID or theme name; **Clear** restores the full
list. Rows show the theme count and revision, with a dot marking packs currently
in use. Large collections scroll within the list instead of stretching Settings.
Select a pack to see its theme names, swatches, attribution and
**Remove pack…** action. The contents and license text scroll independently;
removal stays above them. On narrower windows, details appear below the list.
Newly installed or updated packs are selected automatically.
Search and selection are remembered during the session, separately from language
packs. Theme changes save immediately and survive restart.
Install a newer revision of the same pack to update it immediately. Equal or older
revisions ask before replacing the installed copy. Updating an active theme refreshes
its colors. Removing a pack asks for confirmation; if it contains the active theme,
Canvas Pilot returns to Midra Dark. The downloaded ZIP is kept for reinstalling.
If a pack disappears outside the app, Canvas Pilot keeps your saved choice but
uses Midra Dark and marks the theme unavailable. Reinstalling that pack restores
its colors. Invalid packs are reported and skipped; they do not prevent startup.
## Make your own
Start with one of the editable manifests above. Change the pack `id`, each theme's
`id` and `name`, and its `colors`; keep the required fields. Choose `light: true`
for a light palette or `false` for a dark one. Every color is opaque `#RRGGBB`.
Put the file at the ZIP root as `manifest.json`, with no folder or other files.
A pack may contain up to 16 themes. Increase its positive `revision` for updates.
Use your own pack ID when distributing a variant. Retain relevant upstream notices
when adapting licensed palettes. Check primary and secondary text on every surface,
selection fills and both checkerboard tile colors. Light/dark mode does not fix
poorly contrasted colors automatically.
The [theme-pack contract](../../interfaces/theme-packs.md) lists all palette roles,
validation limits, settings compatibility and round-trip behavior. Repository
contributors regenerate the individual ZIPs and both collections with `python3 scripts/build-theme-packs.py`.

View File

@ -1,6 +1,8 @@
# Midra layer fit precision: engineering follow-up
Status: stretch goal, not a prerequisite for using explicit layer fit. The operator
Status: **done for now**, closed for current scope on 2026-11-18. The questions
below are retained for a possible future investigation, not an active stretch
goal. Closure does not establish a verified firmware raster model. The operator
cannot measure subpixel output with their available equipment. API readback alone
cannot establish how the scaler renders pixels. Ask an Analog Way firmware or
video-processing engineer for the following rules, ideally with reference results

Some files were not shown because too many files have changed in this diff Show More