mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge upstream main into PR #5224
Keep both sets of progress notes and preserve the automatic source merge. Co-authored-by: GPT-6 <[email protected]>
This commit is contained in:
commit
8cc08cdd52
109 files changed
+2827
-201
No files matched your search
@@ -131,7 +131,6 @@ Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still
|
||||
- `../craftrules/release/playbook.md`: how every storytold app builds signed release binaries (the canonical recipe; `docs/release-playbook.md` just points there); `docs/releasing.md` is PhotoCraft's specifics.
|
||||
- `plan/` (local, gitignored): research, parity plan, execution plan, estimates.
|
||||
- `log/` (local, gitignored): the dev log.
|
||||
-
|
||||
|
||||
## 8. Keeping the native format complete
|
||||
|
||||
|
||||
Generated
+1225
-17
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -38,7 +38,7 @@ photocraft-testkit = { path = "crates/testkit" }
|
||||
photocraft-tablet = { path = "crates/tablet" }
|
||||
|
||||
# external
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "d991bf6792f8ade99c51358bf3c1d902c8cd96b5" }
|
||||
craft-print = { git = "https://github.com/storytold/craft-libs", rev = "3d37da389a3618ab9b76109da11416e9ca4ea719" }
|
||||
thiserror = "2"
|
||||
serde = { version = "1", features = ["derive", "rc"] }
|
||||
serde_json = "1"
|
||||
|
||||
@@ -187,7 +187,7 @@ Every screenshot here is the real app at work on public-domain art, rendered off
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<h4>🗃️ Layers, done properly</h4>
|
||||
Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 Photoshop blend modes plus six Paint.NET variants, opacity and fill, locks, colour labels, layer filters, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.
|
||||
Groups, clipping masks, pixel and vector masks, fill layers (solid, gradient and pattern), adjustment layers, live smart objects with smart filters and lossless transforms and warps, multi-layer selection with align, distribute and link, alpha channels and Quick Mask, 27 Photoshop blend modes plus six Paint.NET variants, opacity and fill, locks, colour labels, a layer kind filter, merge, flatten, rasterize, Layer via Copy/Cut, Paste Into.
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
|
||||
+4
-3
@@ -2,7 +2,7 @@
|
||||
|
||||
**Stage: alpha** · next: beta, ~30 points (ready for real work ~45% → ~75%, with reliable PSD) and ~1,100–1,800 h away
|
||||
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-11 · **Change:** minor (toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-11 · **Last updated:** 2026-10-13 · **Change:** minor (oracle floor 145 of 258 and 953 open issues, as in gaps.md and on GitHub; toolbox count 56 of 68, 12 missing) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
PhotoCraft's one-page summary of how close it is to Adobe Photoshop 2026 (27.11.0, measured from
|
||||
the installed app on 2026-10-10) at version 0.6.0. Detail: [target-app parity](docs/target-app-parity.md)
|
||||
@@ -40,7 +40,7 @@ the one above. About 80% parallelizes (independent crates and command modules);
|
||||
architecture and the PSD writer are the serial parts.
|
||||
|
||||
**Why alpha.** Core workflows (open, layer, select, paint, adjust, filter, type, save) work end to
|
||||
end, and breadth is high, but users of 0.5/0.6 have 579 open issues, 22 of 25 performance budgets
|
||||
end, and breadth is high, but 953 issues are open (2026-10-13), 22 of 25 performance budgets
|
||||
are missed, and PSDs we write are not yet reliably accepted by Photoshop (#1281, #2469). Beta
|
||||
needs ~75% ready and no blocking PSD gap. The [alpha gate](docs/roadmap.md#alpha-gate) passes: all six core workflows
|
||||
(retouch, composite, cut-out, design, paint, PSD exchange) complete end to end and save and reopen;
|
||||
@@ -110,7 +110,7 @@ Also shipped: Traditional Chinese, Russian, Ukrainian, Czech, Polish, Greek, Dut
|
||||
|
||||
| Rank | Milestone | Estimate |
|
||||
|---|---|---:|
|
||||
| 1 | PSD that Photoshop trusts: Save As corruption, Photoshop re-open check, Photoshop-oracle floor 133 → 200+ of 256 | 150–250 h |
|
||||
| 1 | PSD that Photoshop trusts: Save As corruption, Photoshop re-open check, Photoshop-oracle floor 145 → 200+ of 258 | 150–250 h |
|
||||
| 2 | Performance budgets: the 22 over-budget scenarios and the 150-layer GPU crash | 200–350 h |
|
||||
| 3 | User bug backlog to under 100 open | 250–400 h |
|
||||
| 4 | Brush and transform feel (brush-parity, ui-parity rows) | 160–290 h |
|
||||
@@ -135,6 +135,7 @@ Detail and the next releases: [docs/roadmap.md](docs/roadmap.md).
|
||||
|
||||
| Date | Change | Summary |
|
||||
|---|---|---|
|
||||
| 2026-10-13 | minor | Focus item 1 quoted the oracle floor as 133 of 256; it is 145 of 258 (`crates/io/tests/corpus.rs`, gaps.md G1). Open issues 579 → 953 (2026-10-13) |
|
||||
| 2026-10-11 | minor | Toolbox count 56 of 68 (12 missing) with the Convert Point tool (#3204) |
|
||||
| 2026-10-10 | minor | Readiness by audience with hours per tier |
|
||||
| 2026-10-10 | minor | Mainstream-practitioner and essentials-user numbers added |
|
||||
|
||||
+11
-3
@@ -600,6 +600,13 @@ impl FilterParams {
|
||||
self.halo() == Halo::Bounds
|
||||
}
|
||||
|
||||
/// Whether the filter renders new pixels without reading the layer's own (Fibers): it fills
|
||||
/// the reference bounds even where the layer is transparent, as Photoshop's does on an
|
||||
/// empty layer, while still reading no neighbourhood.
|
||||
pub fn renders_from_nothing(&self) -> bool {
|
||||
matches!(self, FilterParams::Fibers { .. })
|
||||
}
|
||||
|
||||
/// Human-readable name.
|
||||
pub fn label(&self) -> &'static str {
|
||||
match self {
|
||||
@@ -905,12 +912,13 @@ pub fn kernel(params: &FilterParams, src: &Image, out: Rect, ctx: &Ctx) -> Vec<f
|
||||
pub const TILE: i32 = 256;
|
||||
|
||||
/// The area a filter writes for a layer whose pixels cover `content`:
|
||||
/// global filters write the reference bounds; others the content grown by
|
||||
/// the halo (blurs spread into transparent areas). Clipped to the
|
||||
/// selection's bounds when there is one.
|
||||
/// global filters and renders that ignore the layer's pixels (Fibers) write the reference
|
||||
/// bounds; others the content grown by the halo (blurs spread into transparent areas).
|
||||
/// Clipped to the selection's bounds when there is one.
|
||||
pub fn output_area(params: &FilterParams, content: Rect, bounds: Rect, selection_bounds: Option<Rect>) -> Rect {
|
||||
let mut area = match params.halo_for(bounds) {
|
||||
Halo::Bounds => bounds,
|
||||
Halo::Radius(_) if params.renders_from_nothing() => bounds,
|
||||
Halo::Radius(r) => {
|
||||
if content.is_empty() {
|
||||
Rect::EMPTY
|
||||
|
||||
@@ -682,18 +682,23 @@ fn hue_chroma([r, g, b]: [f32; 3]) -> (f32, f32) {
|
||||
|
||||
/// Color Range › Select: Reds, Yellows, Greens, Cyans, Blues or Magentas (`center` = 0, 60,
|
||||
/// 120, 180, 240, 300°). A pixel belongs to a family by how close its hue is (full at the
|
||||
/// family's hue, none 60° away, so an orange is half red, half yellow) times its chroma, so
|
||||
/// neutrals are never selected and muted colours only partly.
|
||||
/// family's hue, none 60° away, so an orange is half red, half yellow) times its chroma
|
||||
/// (max − min), so neutrals are never selected and muted colours only partly. Darker colours
|
||||
/// weigh more, by `2 − max`: measured against Photoshop 2025's presets on 126 colours each for
|
||||
/// Reds, Yellows and Blues (hue ±40°, saturation 5..100 %, brightness 33..100 %), this matches
|
||||
/// its selection to within one level, where chroma alone fell up to 61 levels short (#5243).
|
||||
pub fn hue_range(px: &[[f32; 4]], center: f32) -> Vec<f32> {
|
||||
px.iter()
|
||||
.map(|&[r, g, b, a]| {
|
||||
if a <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let (h, chroma) = hue_chroma([r, g, b].map(|v| v.clamp(0.0, 1.0)));
|
||||
let rgb = [r, g, b].map(|v| v.clamp(0.0, 1.0));
|
||||
let (h, chroma) = hue_chroma(rgb);
|
||||
let max = rgb[0].max(rgb[1]).max(rgb[2]);
|
||||
let dh = (h - center).rem_euclid(360.0);
|
||||
let dh = dh.min(360.0 - dh);
|
||||
((1.0 - dh / 60.0).clamp(0.0, 1.0) * chroma).clamp(0.0, 1.0)
|
||||
((1.0 - dh / 60.0).clamp(0.0, 1.0) * chroma * (2.0 - max)).clamp(0.0, 1.0)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -1180,6 +1185,17 @@ mod tests {
|
||||
assert!((hue_range(&[[1.0, 0.0, 0.5, 1.0]], 300.0)[0] - 0.5).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_families_weigh_dark_colours_like_photoshop() {
|
||||
// Photoshop 2025's Blues on an 8-bit sRGB document (selection levels 0..255, #5243): the
|
||||
// muted navy #3d3f54, a dark blue (0, 0, 84) and a mid blue (61, 61, 153).
|
||||
let c = |r: u8, g: u8, b: u8| [f32::from(r) / 255.0, f32::from(g) / 255.0, f32::from(b) / 255.0, 1.0];
|
||||
let blues = hue_range(&[c(0x3d, 0x3f, 0x54), c(0, 0, 84), c(61, 61, 153)], 240.0);
|
||||
for (got, want) in blues.iter().zip([35.0, 140.0, 129.0]) {
|
||||
assert!((got * 255.0 - want).abs() <= 1.0, "{} vs Photoshop {want}", got * 255.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tonal_ranges() {
|
||||
let g = |v: f32| [v / 255.0, v / 255.0, v / 255.0, 1.0];
|
||||
|
||||
@@ -446,6 +446,10 @@ fn halos_and_output_area() {
|
||||
assert_eq!(output_area(&FilterParams::Twirl { angle: 1.0 }, content, R, None), R);
|
||||
assert_eq!(output_area(&FilterParams::BoxBlur { radius: 1.0 }, content, R, Some(Rect::new(0, 0, 12, 12))), Rect::new(8, 8, 12, 12));
|
||||
assert!(output_area(&FilterParams::Invert, Rect::EMPTY, R, None).is_empty());
|
||||
// Fibers renders without reading the layer: an empty layer still fills the bounds (#5241).
|
||||
let fibers = FilterParams::Fibers { variance: 16.0, strength: 4.0, seed: 0, foreground: [0.0; 4], background: [1.0; 4] };
|
||||
assert_eq!(output_area(&fibers, Rect::EMPTY, R, None), R);
|
||||
assert_eq!(output_area(&fibers, content, R, Some(Rect::new(0, 0, 12, 12))), Rect::new(0, 0, 12, 12));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -166,7 +166,7 @@ async fn agent_completes_ten_scripted_tasks() {
|
||||
let outside = pixel(&c, 1, 1).await;
|
||||
assert!(inside[0] > 0.99 && inside[1] < 0.01, "task 5: centre is red {inside:?}");
|
||||
assert!(outside[0] < 0.1, "task 5: corner shows the photo {outside:?}");
|
||||
run(&c, "select.deselect", json!({})).await;
|
||||
assert_eq!(inspect(&c).await["hasSelection"], false, "task 5: the selection became the mask");
|
||||
|
||||
// 6. Save a selection to a channel and load it back.
|
||||
run(&c, "select.rect", json!({"x": 4, "y": 6, "width": 20, "height": 10})).await;
|
||||
@@ -413,7 +413,7 @@ async fn agent_completes_ten_more_scripted_tasks() {
|
||||
assert_eq!(top_layer(&doc)["hasMask"], true, "task 17");
|
||||
let boundary = pixel(&c, 20, 40).await;
|
||||
assert!(boundary[3] > 0.05 && boundary[3] < 0.95, "task 17: the feathered edge keeps partial alpha {boundary:?}");
|
||||
run(&c, "select.deselect", json!({})).await;
|
||||
assert_eq!(doc["hasSelection"], false, "task 17: the selection became the mask");
|
||||
|
||||
// 18. Expand a selection and read its bounds back.
|
||||
run(&c, "select.rect", json!({"x": 20, "y": 20, "width": 20, "height": 20})).await;
|
||||
|
||||
@@ -13,7 +13,8 @@
|
||||
//! Interior effects are painted relative to the layer's shape and then take the shape's alpha
|
||||
//! (an overlay recolours a half-transparent edge without adding coverage). The outside parts
|
||||
//! of strokes blend onto the backdrop with their own modes, an upper stroke covering the
|
||||
//! lower ones. Drop shadows are knocked out only through see-through fill.
|
||||
//! lower ones. Drop shadows are knocked out through see-through fill, and beneath the whole shape
|
||||
//! when the layer's mode lets what's under it show through (see [`shadow_see_through`]).
|
||||
//!
|
||||
//! Shapes come from the layer's alpha (after its mask). A stroke's outer edge, and precise glows /
|
||||
//! chiselled bevels, use an exact Euclidean transform: a 5 × 5 chamfer's level sets are polygons,
|
||||
@@ -1850,6 +1851,16 @@ fn knock_out_exterior(map: &mut Map, shape: &Map, fill_opacity: f32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How far the layer lets a knocked-out drop shadow show beneath its own shape (Layer Knocks Out
|
||||
/// Drop Shadow), 0 = covered, 1 = knocked out wholly. In a normal mode an opaque layer covers the
|
||||
/// shadow anyway, so only see-through fill knocks it out (and anti-aliased edges are not
|
||||
/// attenuated twice). In any other mode the layer blends with what's beneath it, shadow and all:
|
||||
/// an Exclusion or Difference layer would invert it, Multiply darken by it, Screen show it as
|
||||
/// grey. Photoshop keeps it out from under the shape, so here it's knocked out wholly.
|
||||
pub fn shadow_see_through(layer: &Layer) -> f32 {
|
||||
if matches!(layer.blend, BlendMode::Normal | BlendMode::Dissolve | BlendMode::PassThrough) { 1.0 - layer.fill_opacity.clamp(0.0, 1.0) } else { 1.0 }
|
||||
}
|
||||
|
||||
/// Blend Interior Effects as Group off (Photoshop's default): the layer's mode applies to its
|
||||
/// own pixels only, and the interior effects paint over the blended result. The layer is merged
|
||||
/// into the backdrop before they paint, so an Overlay colour overlay on a black Color-mode layer
|
||||
@@ -1916,10 +1927,10 @@ pub(crate) fn composite_with_effects_prepared(
|
||||
if let Effect::DropShadow(s) = e {
|
||||
let mut m = fx(i, 0);
|
||||
if s.knocks_out {
|
||||
// The layer hides the shadow beneath it only where its fill is see-through: at
|
||||
// 100 % fill the layer covers it anyway (and anti-aliased edges are not
|
||||
// attenuated twice), at 0 % the shape shows the bare backdrop.
|
||||
knock_out_exterior(&mut m, &shape, layer.fill_opacity);
|
||||
// The layer hides the shadow beneath it where its fill is see-through (at 100 %
|
||||
// fill in a normal mode it covers it anyway; at 0 % the shape shows the bare
|
||||
// backdrop), and wholly in a mode that blends with it ([`shadow_see_through`]).
|
||||
knock_out_exterior(&mut m, &shape, 1.0 - shadow_see_through(layer));
|
||||
}
|
||||
paint_color(&mut work, &m, rgb(&s.color), s.common.blend, s.common.opacity);
|
||||
}
|
||||
|
||||
@@ -1473,6 +1473,36 @@ fn shadow_knockout_needs_see_through_fill() {
|
||||
assert!(close4(on, px(&base, 10, 20)), "{on:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_knockout_beneath_a_layer_in_a_blending_mode() {
|
||||
// Layer Knocks Out Drop Shadow keeps the shadow out from under the layer's shape. In Normal
|
||||
// mode an opaque layer covers it anyway; in a mode that blends with what's beneath, the shadow
|
||||
// would show through: under a white Exclusion square on white, it read as white (white over
|
||||
// the black shadow) instead of black (white over white), so a logo's Exclusion bar with a
|
||||
// drop shadow came out blank. A red Multiply square came out black instead of red.
|
||||
for (blend, colour, inside, depth) in [
|
||||
(photocraft_color::BlendMode::Exclusion, [1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]),
|
||||
(photocraft_color::BlendMode::Multiply, [1.0, 0.0, 0.0, 1.0], [1.0, 0.0, 0.0, 1.0]),
|
||||
]
|
||||
.into_iter()
|
||||
.flat_map(|c| SampleType::ALL.map(|depth| (c, depth)))
|
||||
.map(|((b, c, i), depth)| (b, c, i, depth))
|
||||
{
|
||||
let mut d = Document::new("t", Size::new(40, 40), ColorMode::Rgb, depth);
|
||||
d.layers.push(solid_layer("bg", Rect::new(0, 0, 40, 40), [1.0; 4]));
|
||||
let mut l = solid_layer("sq", Rect::new(10, 10, 30, 30), colour);
|
||||
l.blend = blend;
|
||||
l.effects.items = vec![Effect::DropShadow(shadow(0.0, 90.0))];
|
||||
d.layers.push(l);
|
||||
assert!(close4(px(&d, 20, 20), inside), "{blend:?} {depth:?}: {:?}", px(&d, 20, 20));
|
||||
// Not knocked out, the shadow shows through the blend, as in Photoshop with the box unticked.
|
||||
if let Effect::DropShadow(s) = &mut d.layers[1].effects.items[0] {
|
||||
s.knocks_out = false;
|
||||
}
|
||||
assert!(!close4(px(&d, 20, 20), inside), "{blend:?} {depth:?} without knockout: {:?}", px(&d, 20, 20));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_pattern_overlay_anchors_at_the_effects_reference_point() {
|
||||
use photocraft_doc::pattern::Pattern;
|
||||
|
||||
@@ -353,7 +353,6 @@ fn invert_with_the_mask_targeted_inverts_the_mask() {
|
||||
let mut s = session(depth, "rgb");
|
||||
s.execute("select.rect", json!({"x": 24, "y": 0, "width": 24, "height": 32})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let (pixels, off_canvas) = (rgba(&s, 3, 3), mask_at(&s, -500, 3));
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute("image.adjustments.invert", json!({"target": "mask"})).unwrap();
|
||||
@@ -372,6 +371,31 @@ fn invert_with_the_mask_targeted_inverts_the_mask() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop: a mask made from the selection (Reveal Selection, the Layers panel's mask button)
|
||||
/// takes the selection with it, as Hide Selection does. So ⌘I on the new mask right away inverts
|
||||
/// all of it; with the selection kept it inverted only the inside, leaving the mask all black.
|
||||
/// Undo brings the selection back with the mask gone, in one step.
|
||||
#[test]
|
||||
fn reveal_selection_drops_the_selection_so_invert_flips_the_whole_mask() {
|
||||
for depth in DEPTHS {
|
||||
let mut s = session(depth, "rgb");
|
||||
s.execute("select.rect", json!({"x": 24, "y": 0, "width": 24, "height": 32})).unwrap();
|
||||
let selection = s.active().unwrap().doc.selection.clone();
|
||||
let steps = s.active().unwrap().history.past_len();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.selection.is_none(), "depth {depth}: the selection became the mask");
|
||||
assert_eq!(s.active().unwrap().history.past_len(), steps + 1, "one step");
|
||||
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, 30, 3)), (0.0, 1.0));
|
||||
s.execute("image.adjustments.invert", json!({"target": "mask"})).unwrap();
|
||||
assert_eq!((mask_at(&s, 3, 3), mask_at(&s, 30, 3)), (1.0, 0.0), "depth {depth}: inside and outside both flip");
|
||||
s.undo();
|
||||
s.undo();
|
||||
let st = s.active().unwrap();
|
||||
assert_eq!(st.doc.selection, selection, "undo restores the selection");
|
||||
assert!(st.doc.layer(st.active_layer.unwrap()).unwrap().mask.is_none(), "and removes the mask");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Image › Adjustments as smart filters (FILE-215-4) ----------
|
||||
|
||||
/// A painted pixel layer converted to a smart object, over the painted Background.
|
||||
@@ -492,7 +516,6 @@ fn a_targeted_mask_enables_editing_it_on_any_layer() {
|
||||
s.execute("layer.delete", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 24, "y": 0, "width": 24, "height": 32})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let pixels = rgba(&s, 23, 3);
|
||||
s.execute("filter.blur.gaussianBlur", json!({"radius": 3, "target": "mask"})).unwrap();
|
||||
assert!(mask_at(&s, 23, 3) > 0.0 && mask_at(&s, 23, 3) < 1.0, "the mask's edge is blurred");
|
||||
|
||||
@@ -381,7 +381,7 @@ mod tests {
|
||||
let m = r["aligned"][0]["matrix"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect::<Vec<_>>();
|
||||
assert!((m[2] + 6.0).abs() < 1.0 && (m[5] + 5.0).abs() < 1.0, "{r}");
|
||||
assert!(s.execute("edit.autoAlignLayers", json!({"projection": "sideways"})).is_err());
|
||||
assert!(s.execute("edit.autoAlignLayers", json!({"reference": 9999})).is_err());
|
||||
assert!(s.execute("edit.autoAlignLayers", json!({"reference": u64::MAX})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -50,7 +50,7 @@ fn browse_runs_a_script_file() {
|
||||
assert_eq!((d.size.width, d.size.height), (20, 30));
|
||||
assert!(s.execute("file.scripts.browse", json!({"script": "no.such.command"})).is_err());
|
||||
// A failing step stops the script and is reported.
|
||||
let r = s.execute("file.scripts.browse", json!({"steps": [["layer.delete", {"layer": 999_999}], ["image.imageRotation.90cw", {}]]})).unwrap();
|
||||
let r = s.execute("file.scripts.browse", json!({"steps": [["layer.delete", {"layer": u64::MAX}], ["image.imageRotation.90cw", {}]]})).unwrap();
|
||||
assert_eq!(r["results"].as_array().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
@@ -348,7 +348,7 @@ fn a_failed_step_inside_a_called_action_fails_scripts_and_batch() {
|
||||
});
|
||||
s.actions.list.push(Action {
|
||||
name: "Bad".into(),
|
||||
steps: vec![("layer.delete".into(), json!({"layer": 999_999}))],
|
||||
steps: vec![("layer.delete".into(), json!({"layer": u64::MAX}))],
|
||||
disabled: Default::default(),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
@@ -144,6 +144,32 @@ mod tests {
|
||||
(s, [bg, a, b])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opacity_fill_or_a_blend_mode_turn_the_background_into_a_layer() {
|
||||
// Like Photoshop: the Background takes none of them, so it becomes "Layer 0" first.
|
||||
for (key, value) in [("opacity", json!(0.5)), ("fill", json!(0.5)), ("blend", json!("Multiply"))] {
|
||||
let (mut s, [bg, ..]) = with_background();
|
||||
s.execute("layer.setProps", json!({"layer": bg.0, key: value})).unwrap();
|
||||
let l = doc(&s).layer(bg).unwrap();
|
||||
assert!(!doc(&s).is_background(bg) && l.name == "Layer 0", "{key}");
|
||||
assert!(l.opacity < 1.0 || l.fill_opacity < 1.0 || l.blend == photocraft_color::BlendMode::Multiply, "{key}: applied");
|
||||
}
|
||||
// Values that leave its look alone keep it the Background.
|
||||
let (mut s, [bg, ..]) = with_background();
|
||||
s.execute("layer.setProps", json!({"layer": bg.0, "opacity": 1.0, "fill": 1.0, "blend": "Normal", "visible": false})).unwrap();
|
||||
assert!(doc(&s).is_background(bg));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_and_mask_output_to_a_layer_mask_turns_the_background_into_a_layer() {
|
||||
let (mut s, [bg, ..]) = with_background();
|
||||
s.execute("layer.select", json!({"layer": bg.0})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 2, "y": 2, "width": 6, "height": 6})).unwrap();
|
||||
s.execute("select.refineEdge", json!({"output": "layerMask"})).unwrap();
|
||||
let l = doc(&s).layer(bg).unwrap();
|
||||
assert!(l.mask.is_some() && !doc(&s).is_background(bg) && l.name == "Layer 0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn makes_the_layer_the_background_at_the_bottom() {
|
||||
for depth in [8, 16, 32] {
|
||||
@@ -207,7 +233,7 @@ mod tests {
|
||||
assert!(s.execute(CMD, json!({"layer": bg.0})).is_err());
|
||||
// Bad params.
|
||||
let (mut s, [_, a, _]) = session(8);
|
||||
for p in [json!({"layer": "A"}), json!({"layer": -1}), json!({"layer": 1.5}), json!({"layer": 99999}), json!({"layer": [a.0]})] {
|
||||
for p in [json!({"layer": "A"}), json!({"layer": -1}), json!({"layer": 1.5}), json!({"layer": u64::MAX}), json!({"layer": [a.0]})] {
|
||||
assert!(s.execute(CMD, p.clone()).is_err(), "{p}");
|
||||
}
|
||||
assert!(doc(&s).background().is_none());
|
||||
|
||||
@@ -59,15 +59,16 @@ pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {
|
||||
return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
|
||||
}
|
||||
let fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, true);
|
||||
let values = src.read_region(area);
|
||||
let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1)));
|
||||
let mut px = Vec::with_capacity(values.len() / n * 2);
|
||||
let values = crate::allocation::read_region(src, area, "copying a channel")?;
|
||||
let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?;
|
||||
let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?;
|
||||
let mut px = crate::allocation::capacity(len, "copying a channel")?;
|
||||
for (i, p) in values.chunks_exact(n).enumerate() {
|
||||
px.push(p.get(k).copied().unwrap_or(0.0));
|
||||
px.push(cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)));
|
||||
}
|
||||
let mut surface = Surface::new(fmt);
|
||||
surface.write_region(area, &px);
|
||||
surface.try_write_region(area, &px)?;
|
||||
surface.prune();
|
||||
let bounds = surface.content_bounds();
|
||||
if bounds.is_empty() {
|
||||
|
||||
@@ -163,3 +163,22 @@ fn clearing_a_channel_reports_allocation_failure_without_editing() {
|
||||
assert_eq!(s.active().unwrap().history.entries(), history);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_copy_allocation_failure_keeps_clipboard_and_document() {
|
||||
for depth in [8, 16, 32] {
|
||||
let mut s = session(depth);
|
||||
s.execute("edit.copy", json!({})).unwrap();
|
||||
s.execute("channel.target", json!({"channel": "red"})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let clip = s.clipboard.as_ref().unwrap().surface.clone();
|
||||
let history = s.active().unwrap().history.entries();
|
||||
crate::allocation::fail_next_for_test();
|
||||
let result = copy(&mut s);
|
||||
let _ = crate::allocation::capacity::<u8>(0, "reset failpoint");
|
||||
assert!(result.is_err());
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
assert_eq!(s.active().unwrap().history.entries(), history);
|
||||
assert_eq!(s.clipboard.as_ref().unwrap().surface, clip);
|
||||
}
|
||||
}
|
||||
@@ -681,6 +681,16 @@ fn build() -> Vec<CommandSpec> {
|
||||
has_layer,
|
||||
|s, p| {
|
||||
let id = layer_param(s, p)?;
|
||||
// Opacity and Fill are fractions here, while the Layer Style commands take
|
||||
// percentages: a value outside 0..1 is refused, never clamped to 100 % (#5242).
|
||||
let unit = |key: &str| -> Result<Option<f32>> {
|
||||
let Some(v) = p.get(key) else { return Ok(None) };
|
||||
match v.as_f64() {
|
||||
Some(x) if (0.0..=1.0).contains(&x) => Ok(Some(x as f32)),
|
||||
_ => Err(bad("layer.setProps", format!("{key} must be a number in 0..1 (1 = 100 %), got {v}"))),
|
||||
}
|
||||
};
|
||||
let (opacity, fill) = (unit("opacity")?, unit("fill")?);
|
||||
let only_visibility =
|
||||
p.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "visible" | "coalesce")));
|
||||
let label = if only_visibility { "Layer Visibility" } else { "Layer Properties" };
|
||||
@@ -688,6 +698,13 @@ fn build() -> Vec<CommandSpec> {
|
||||
// Clipping and channel changes reach the layers around it: recomposite everything.
|
||||
let local = p.get("clipped").is_none() && p.get("channels").is_none();
|
||||
s.edit(label, |doc, _| {
|
||||
// The Background has no opacity, fill or blend mode: like Photoshop, setting
|
||||
// one that changes its look turns it into a normal layer ("Layer 0") first.
|
||||
let num = |k: &str| p.get(k).and_then(Value::as_f64).is_some_and(|v| v < 1.0);
|
||||
let blends = p.get("blend").and_then(Value::as_str).and_then(blend_from_str).is_some_and(|b| b != photocraft_color::BlendMode::Normal);
|
||||
if num("opacity") || num("fill") || blends {
|
||||
crate::extra_cmds::background_to_layer(doc, id);
|
||||
}
|
||||
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
|
||||
if let Some(v) = p.get("name").and_then(Value::as_str) {
|
||||
l.name = v.to_string();
|
||||
@@ -695,11 +712,11 @@ fn build() -> Vec<CommandSpec> {
|
||||
if let Some(v) = p.get("visible").and_then(Value::as_bool) {
|
||||
l.visible = v;
|
||||
}
|
||||
if let Some(v) = p.get("opacity").and_then(Value::as_f64) {
|
||||
l.opacity = (v as f32).clamp(0.0, 1.0);
|
||||
if let Some(v) = opacity {
|
||||
l.opacity = v;
|
||||
}
|
||||
if let Some(v) = p.get("fill").and_then(Value::as_f64) {
|
||||
l.fill_opacity = (v as f32).clamp(0.0, 1.0);
|
||||
if let Some(v) = fill {
|
||||
l.fill_opacity = v;
|
||||
}
|
||||
if let Some(v) = p.get("blend").and_then(Value::as_str) {
|
||||
l.blend = blend_from_str(v).ok_or_else(|| bad("layer.setProps", format!("unknown blend mode `{v}`")))?;
|
||||
@@ -788,7 +805,10 @@ fn build() -> Vec<CommandSpec> {
|
||||
|s, p| {
|
||||
let sel = s.active().and_then(|d| d.doc.selection.clone()).ok_or(EngineError::Other("no selection".into()))?;
|
||||
let mask = LayerMask { surface: sel, ..LayerMask::reveal_all() };
|
||||
set_mask(s, p, "Add Layer Mask", Some(mask))
|
||||
// The selection becomes the mask, so Photoshop drops it (as Hide Selection does): a
|
||||
// following Invert (⌘I) on the targeted mask then inverts all of it, not just the
|
||||
// part inside the old selection. Same undo step as the mask.
|
||||
set_mask_and_deselect(s, p, "Add Layer Mask", mask)
|
||||
}
|
||||
),
|
||||
cmd!("layer.layerMask.delete", "Delete", ["Layer", "Layer Mask"], None, r##"{"layer":id?}"##, has_layer, |s, p| set_mask(
|
||||
@@ -1427,6 +1447,15 @@ fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {
|
||||
/// Add (`Some`) or remove (`None`) a layer mask. Adding acts on every selected layer that can take
|
||||
/// one ([`crate::layer_multi_cmds::mask_targets`]), in one history step.
|
||||
fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask>) -> Result<Value> {
|
||||
set_mask_with(s, p, label, mask, false)
|
||||
}
|
||||
|
||||
/// [`set_mask`] that also drops the selection the mask was made from, in the same history step.
|
||||
fn set_mask_and_deselect(s: &mut Session, p: &Value, label: &str, mask: LayerMask) -> Result<Value> {
|
||||
set_mask_with(s, p, label, Some(mask), true)
|
||||
}
|
||||
|
||||
fn set_mask_with(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask>, deselect: bool) -> Result<Value> {
|
||||
let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] };
|
||||
s.edit(label, |doc, _| {
|
||||
let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?;
|
||||
@@ -1436,6 +1465,9 @@ fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask>) ->
|
||||
}
|
||||
doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.mask = mask.clone();
|
||||
}
|
||||
if deselect {
|
||||
doc.selection = None;
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(Value::Null)
|
||||
@@ -1547,3 +1579,30 @@ mod registry_tests {
|
||||
assert_eq!(registry.specs.len(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod set_props_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn opacity_and_fill_outside_zero_to_one_are_refused_not_clamped() {
|
||||
// #5242: `55` (a percentage, as the Layer Style commands take) used to become 100 %.
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("layer.setProps", json!({"opacity": 0.55, "fill": 0.4})).unwrap();
|
||||
let layer = |s: &Session| {
|
||||
let d = s.active().unwrap();
|
||||
let l = d.doc.layer(d.active_layer.unwrap()).unwrap();
|
||||
(l.opacity, l.fill_opacity)
|
||||
};
|
||||
assert_eq!(layer(&s), (0.55, 0.4));
|
||||
for bad in [json!({"opacity": 55}), json!({"opacity": -0.1}), json!({"fill": 1.5}), json!({"opacity": "50%"}), json!({"opacity": 0.5, "fill": 40})] {
|
||||
let e = s.execute("layer.setProps", bad.clone()).unwrap_err().to_string();
|
||||
assert!(e.contains("0..1"), "{bad}: {e}");
|
||||
assert_eq!(layer(&s), (0.55, 0.4), "{bad} left the layer alone");
|
||||
}
|
||||
s.execute("layer.setProps", json!({"opacity": 0, "fill": 1})).unwrap();
|
||||
assert_eq!(layer(&s), (0.0, 1.0));
|
||||
}
|
||||
}
|
||||
@@ -254,7 +254,7 @@ mod tests {
|
||||
|
||||
let (mut s, _) = disc(8);
|
||||
let before = s.active().unwrap().revision;
|
||||
assert!(s.execute(CMD, json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute(CMD, json!({"layer": u64::MAX})).is_err());
|
||||
// A `layer` string names a layer; one that isn't there is an error, not the active layer.
|
||||
assert!(s.execute(CMD, json!({"layer": "x"})).is_err());
|
||||
assert_eq!(s.active().unwrap().revision, before);
|
||||
|
||||
@@ -495,9 +495,12 @@ fn new_from_clipboard(s: &mut Session) -> Result<Value> {
|
||||
if w == 0 || h == 0 {
|
||||
return Err(EngineError::Other("the clipboard image has no size".into()));
|
||||
}
|
||||
let (Some(dx), Some(dy)) = (b.x0.checked_neg(), b.y0.checked_neg()) else {
|
||||
return Err(EngineError::Other("the clipboard origin is outside the coordinate range for a new document".into()));
|
||||
};
|
||||
let fmt = clip.surface.format();
|
||||
let target = PixelFormat::new(fmt.mode, fmt.sample, true);
|
||||
let moved = if b.x0 == 0 && b.y0 == 0 { clip.surface } else { photocraft_algo::resample::translate_surface(&clip.surface, -b.x0, -b.y0) };
|
||||
let moved = if dx == 0 && dy == 0 { clip.surface } else { photocraft_algo::resample::translate_surface(&clip.surface, dx, dy) };
|
||||
let mut doc = Document::new("Untitled", photocraft_geom::Size::new(w, h), fmt.mode, fmt.sample);
|
||||
if let Some(r) = clip.resolution.filter(|r| r.is_finite() && *r > 0.0) {
|
||||
doc.resolution_dpi = r;
|
||||
@@ -1044,6 +1047,19 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_clipboard_document_rejects_an_unrepresentable_origin() {
|
||||
let mut s = Session::new();
|
||||
let mut surface = Surface::new(PixelFormat::RGBA8);
|
||||
surface.write_pixel(i32::MIN, 0, &[1.0, 0.0, 0.0, 1.0]);
|
||||
s.clipboard = Some(Clip { surface, bounds: Rect::from_xywh(i32::MIN, 0, 1, 1), layers: None, resolution: None });
|
||||
let result = new_from_clipboard(&mut s);
|
||||
assert!(result.unwrap_err().to_string().contains("clipboard origin"));
|
||||
assert!(s.execute("file.newFromClipboard", json!({})).is_err());
|
||||
assert!(s.documents().is_empty());
|
||||
assert_eq!(s.clipboard.as_ref().unwrap().surface.rgba(i32::MIN, 0), [1.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn injected_clear_buffer_failure_leaves_the_document_unchanged() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1549,7 +1549,7 @@ mod tests {
|
||||
// Layer 1 is already the only visible layer: ⌥-clicking it shows everything.
|
||||
assert_eq!(s.execute("layer.showOnly", json!({})).unwrap()["shownAlone"], false);
|
||||
assert!(doc(&s).layers.iter().all(|l| l.visible));
|
||||
assert!(s.execute("layer.showOnly", json!({"layer": 9999})).is_err());
|
||||
assert!(s.execute("layer.showOnly", json!({"layer": u64::MAX})).is_err());
|
||||
assert!(Session::new().execute("layer.showOnly", json!({})).is_err());
|
||||
}
|
||||
|
||||
@@ -1624,7 +1624,7 @@ mod tests {
|
||||
let bg_locks = doc(&s).layer(bg).unwrap().locks;
|
||||
assert!(s.execute("layer.toggleLockTransparency", json!({"layer": bg.0})).is_err());
|
||||
assert_eq!(doc(&s).layer(bg).unwrap().locks, bg_locks, "the Background is left alone");
|
||||
assert!(s.execute("layer.toggleLockTransparency", json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute("layer.toggleLockTransparency", json!({"layer": u64::MAX})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -586,7 +586,6 @@ fn flatten_all_layer_effects_and_masks() {
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
s.execute("select.inverse", json!({})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
assert!(composite(&s, 15, 15)[1] > 0.99 && composite(&s, 15, 15)[0] > 0.99, "white shows through the mask");
|
||||
let r = s.execute("file.scripts.flattenAllMasks", json!({})).unwrap();
|
||||
assert_eq!(r["flattened"], 1);
|
||||
@@ -633,7 +632,6 @@ fn flatten_all_layer_effects_keeps_masks() {
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 40})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
// Layer 2: a red square at the bottom-right with the same overlay and a *disabled* mask.
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 30, "y": 30, "width": 8, "height": 8})).unwrap();
|
||||
@@ -652,7 +650,6 @@ fn flatten_all_layer_effects_keeps_masks() {
|
||||
.unwrap();
|
||||
s.execute("select.rect", json!({"x": 34, "y": 34, "width": 2, "height": 2})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.edit("disable", |doc, _| {
|
||||
if let Some(m) = doc.layer_mut(id2).and_then(|l| l.mask.as_mut()) {
|
||||
m.enabled = false;
|
||||
|
||||
@@ -264,7 +264,7 @@ mod tests {
|
||||
for id in IDS {
|
||||
assert!(s.execute(id, json!([1, 2])).is_err(), "{id}");
|
||||
assert!(s.execute(id, json!("x")).is_err(), "{id}");
|
||||
assert!(s.execute(id, json!({"layer": 99_999})).is_err(), "{id}");
|
||||
assert!(s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}");
|
||||
assert!(s.execute(id, json!({"target": {"channel": 42}})).is_err(), "{id}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,7 +460,6 @@ mod tests {
|
||||
if reveal_selection {
|
||||
s.execute("select.all", json!({})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
} else {
|
||||
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
}
|
||||
|
||||
@@ -164,6 +164,27 @@ fn colour_filters_use_and_record_tool_colours() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fibers_fill_an_empty_layer() {
|
||||
// #5241: Fibers renders from the colours, not the layer's pixels, so an empty layer fills
|
||||
// like in Photoshop (and can be transformed afterwards).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 48, "height": 32})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("filter.render.fibers", json!({"seed": 3})).unwrap();
|
||||
let px = pixels(&s);
|
||||
assert!(px.as_chunks::<4>().0.iter().all(|p| p[3] == 1.0), "every pixel is rendered opaque");
|
||||
s.execute("edit.transform.flipHorizontal", json!({})).unwrap();
|
||||
|
||||
// With a selection only the selection fills.
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 4, "y": 4, "width": 10, "height": 6})).unwrap();
|
||||
s.execute("filter.render.fibers", json!({"seed": 3})).unwrap();
|
||||
let d = s.active().unwrap();
|
||||
let surf = d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap();
|
||||
assert_eq!(surf.content_bounds(), Rect::new(4, 4, 14, 10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displace_reads_another_document() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -118,7 +118,7 @@ mod tests {
|
||||
let bg = s.active().unwrap().doc.layers[0].id.0;
|
||||
for p in [
|
||||
json!({"layer": bg}),
|
||||
json!({"layer": 9999}),
|
||||
json!({"layer": u64::MAX}),
|
||||
json!({"layer": "x"}),
|
||||
json!({"layer": -1}),
|
||||
json!({"expanded": "yes", "all": true}),
|
||||
|
||||
@@ -161,7 +161,7 @@ mod tests {
|
||||
let before = state(&s, a);
|
||||
for p in [
|
||||
json!({"layer": bg}),
|
||||
json!({"layer": 9999}),
|
||||
json!({"layer": u64::MAX}),
|
||||
json!({"layer": "x"}),
|
||||
json!({"layer": -1}),
|
||||
json!({"layer": a, "index": 2}),
|
||||
|
||||
@@ -273,7 +273,7 @@ fn commands_fail_gracefully() {
|
||||
// A zero-length drag still makes a valid gradient.
|
||||
s.execute(CREATE, json!({"from": [3, 3], "to": [3, 3]})).unwrap();
|
||||
for p in [
|
||||
json!({"layer": 999_999}),
|
||||
json!({"layer": u64::MAX}),
|
||||
json!({"from": [0]}),
|
||||
json!({"to": [1e30, 0]}),
|
||||
json!({"angle": "x"}),
|
||||
|
||||
@@ -142,7 +142,7 @@ mod tests {
|
||||
let bg = s.active().unwrap().doc.layers[0].id.0;
|
||||
for p in [
|
||||
json!({"layer": bg}),
|
||||
json!({"layer": 9999}),
|
||||
json!({"layer": u64::MAX}),
|
||||
json!({"layer": "x"}),
|
||||
json!({"layer": -1}),
|
||||
json!({"expanded": "yes", "all": true}),
|
||||
|
||||
@@ -130,7 +130,7 @@ fn bad_params_and_states_fail_without_changing_anything() {
|
||||
json!({"document": -1}),
|
||||
json!({"document": "1"}),
|
||||
json!({"document": 1, "source": 9}),
|
||||
json!({"document": 1, "layers": [999_999]}),
|
||||
json!({"document": 1, "layers": [u64::MAX]}),
|
||||
json!({"document": 1, "layers": "all"}),
|
||||
json!({"document": 1, "layers": []}),
|
||||
json!({"document": 1, "at": [1.0]}),
|
||||
@@ -314,7 +314,7 @@ fn duplicate_destinations_that_are_not_new_fail_cleanly() {
|
||||
json!({"document": []}),
|
||||
json!({"document": {}}),
|
||||
json!({"document": "other"}),
|
||||
json!({"document": "new", "layer": 999_999}),
|
||||
json!({"document": "new", "layer": u64::MAX}),
|
||||
] {
|
||||
let before = (doc(&s, 0).clone(), s.documents().len(), s.active_index());
|
||||
let err = s.execute("layer.duplicate", p.clone()).unwrap_err().to_string();
|
||||
|
||||
@@ -588,7 +588,7 @@ fn transfer_effects_moves_or_copies_between_layers() {
|
||||
for bad in [
|
||||
json!({"from": a.0, "to": a.0}),
|
||||
json!({"from": a.0}),
|
||||
json!({"from": a.0, "to": 9999}),
|
||||
json!({"from": a.0, "to": u64::MAX}),
|
||||
json!({"from": a.0, "to": b.0, "effect": 7}),
|
||||
json!({"from": a.0, "to": b.0, "effect": -1}),
|
||||
json!({"from": b.0, "to": a.0}),
|
||||
|
||||
@@ -1625,8 +1625,8 @@ mod tests {
|
||||
let all = doc(&s).bounds();
|
||||
assert!(damage(&s).is_none_or(|r| r.contains_rect(&all)), "{:?}", damage(&s));
|
||||
// Bad params still fail cleanly.
|
||||
assert!(s.execute("layer.setProps", json!({"layer": 999_999, "visible": true})).is_err());
|
||||
assert!(s.execute("layer.translate", json!({"layer": 999_999, "dx": 1})).is_err());
|
||||
assert!(s.execute("layer.setProps", json!({"layer": u64::MAX, "visible": true})).is_err());
|
||||
assert!(s.execute("layer.translate", json!({"layer": u64::MAX, "dx": 1})).is_err());
|
||||
}
|
||||
|
||||
/// #1771: a new empty layer or group changes no pixels, so it (and undoing or redoing it)
|
||||
@@ -1805,7 +1805,7 @@ mod tests {
|
||||
let mut locked = (*before).clone();
|
||||
locked.layer_mut(a).unwrap().locks.position = true;
|
||||
assert!(moved(&locked, &ids, 1, 1).is_err());
|
||||
assert!(moved(&before, &[LayerId(999_999)], 1, 1).is_err());
|
||||
assert!(moved(&before, &[LayerId(u64::MAX)], 1, 1).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1894,7 +1894,7 @@ mod tests {
|
||||
assert_eq!(s.active().unwrap().doc.layer(a).unwrap().name, "x");
|
||||
s.execute("layer.showLayers", json!({"layer": a.0})).unwrap();
|
||||
assert!(s.active().unwrap().doc.layer(a).unwrap().visible);
|
||||
assert!(s.execute("layer.hideLayers", json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute("layer.hideLayers", json!({"layer": u64::MAX})).is_err());
|
||||
assert!(s.execute("layer.hideLayers", json!({})).is_err());
|
||||
assert!(!s.is_enabled("layer.align.topEdges"));
|
||||
}
|
||||
|
||||
@@ -1206,7 +1206,7 @@ mod tests {
|
||||
let layer = s.active().unwrap().active_layer.unwrap().0;
|
||||
s.execute("layer.layerStyle.clear", json!({"layer": layer, "effect": 0})).unwrap();
|
||||
assert!(matches!(effects(&s)[..], [Effect::ColorOverlay { .. }]));
|
||||
for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": 999_999})] {
|
||||
for bad in [json!({"effect": 5}), json!({"effect": -1}), json!({"effect": "x"}), json!({"effect": 0, "layer": u64::MAX})] {
|
||||
assert!(s.execute("layer.layerStyle.clear", bad).is_err());
|
||||
}
|
||||
assert_eq!(effects(&s).len(), 1, "bad params change nothing");
|
||||
|
||||
@@ -10,7 +10,6 @@ fn session() -> (Session, u64, u64) {
|
||||
s.execute("edit.fill", json!({"contents": "color", "color": "#ff0000"})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 20, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let st = s.active_mut().unwrap();
|
||||
st.saved_revision = st.revision;
|
||||
(s, masked, bg)
|
||||
@@ -96,7 +95,7 @@ fn bad_params_and_no_mask_fail_gracefully() {
|
||||
for p in [
|
||||
json!({"layer": bg, "mode": "gray"}),
|
||||
json!({"layer": bg}),
|
||||
json!({"layer": 999_999, "mode": "gray"}),
|
||||
json!({"layer": u64::MAX, "mode": "gray"}),
|
||||
json!({"layer": "x"}),
|
||||
json!({"layer": -1}),
|
||||
json!({"mode": 3}),
|
||||
|
||||
@@ -225,7 +225,7 @@ mod tests {
|
||||
json!([1, 2]),
|
||||
json!({"layer": -1}),
|
||||
json!({"layer": "x"}),
|
||||
json!({"layer": 999_999}),
|
||||
json!({"layer": u64::MAX}),
|
||||
json!({"document": 999_999}),
|
||||
json!({"pattern": "nope"}),
|
||||
json!({"pattern": ""}),
|
||||
|
||||
@@ -1553,7 +1553,8 @@ impl Session {
|
||||
}
|
||||
};
|
||||
interface.insert("appearanceMode".into(), json!(mode));
|
||||
interface.insert(slot.into(), json!(theme.name()));
|
||||
// A partially migrated file may already contain a newer theme selection (#5139).
|
||||
interface.entry(slot).or_insert_with(|| json!(theme.name()));
|
||||
}
|
||||
let color = v.as_object_mut().and_then(|m| m.remove("colorSettings"));
|
||||
let presets = v.as_object_mut().and_then(|m| m.remove("presets"));
|
||||
|
||||
@@ -67,6 +67,17 @@ fn appearance_defaults_and_legacy_theme_migrate() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_theme_migration_preserves_saved_theme_slots() {
|
||||
for (legacy, slot, saved) in [("proMedium", "darkTheme", "solarizedDark"), ("studioLight", "lightTheme", "adwaita")] {
|
||||
let mut interface = json!({"theme": legacy});
|
||||
interface[slot] = json!(saved);
|
||||
let mut session = Session::new();
|
||||
session.load_prefs_json(&json!({"interface": interface}).to_string()).unwrap();
|
||||
assert_eq!(session.prefs_value()["interface"][slot], saved, "explicit {slot} survives migration");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appearance_choices_validate_and_legacy_theme_still_selects() {
|
||||
let mut s = Session::new();
|
||||
|
||||
+154
-10
@@ -14,6 +14,8 @@
|
||||
|
||||
use std::io::Write as _;
|
||||
|
||||
mod windows_marks;
|
||||
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_doc::{Document, LayerContent, SmartSource};
|
||||
use serde_json::{Value, json};
|
||||
@@ -388,6 +390,21 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
|
||||
let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999) as u32;
|
||||
let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
|
||||
// Shared RGB transport handles compatible Windows pages; PDF-only content retains its route.
|
||||
// Sending follows the shared command contract; fuzz tests explicitly request dryRun.
|
||||
// The worker returns its result before repeat settings and hooks are applied once.
|
||||
let handling = p.get("colorHandling").and_then(Value::as_str).unwrap_or("printerManages");
|
||||
if cfg!(windows) && send && !dry && output.is_none() && native_rgb_compatible(&page, handling) {
|
||||
require_printing_enabled()?;
|
||||
let printed = print_windows(&page, p, &doc.name, copies)?;
|
||||
return Ok(json!({
|
||||
"pdf": Value::Null, "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0,
|
||||
"copies": copies, "command": Value::Null, "sent": true, "spooler": printed, "color": color,
|
||||
}));
|
||||
}
|
||||
if cfg!(windows) && send && !dry && output.is_none() && printer_settings(p)?.is_some() {
|
||||
return Err(other("the selected color profile or page text requires PDF printing. Save as PDF, or clear Print Settings to use PDF printing."));
|
||||
}
|
||||
let pdf = print_pdf(&page);
|
||||
let job = craft_print::Job {
|
||||
printer: p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string),
|
||||
@@ -409,13 +426,7 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result<Value> {
|
||||
let mut sent = false;
|
||||
let mut spool = Value::Null;
|
||||
if send && !dry {
|
||||
// The last line of defence: a test or fuzz run must never print a page (`dryRun` still
|
||||
// renders and reports the command).
|
||||
if printing_disabled() {
|
||||
return Err(other(
|
||||
"printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true",
|
||||
));
|
||||
}
|
||||
require_printing_enabled()?;
|
||||
spool = json!(craft_print::submit(&pdf, &job).map_err(other)?);
|
||||
sent = true;
|
||||
}
|
||||
@@ -424,6 +435,15 @@ fn render_and_spool(doc: &Document, p: &Value, cmd: &str) -> Result<Value> {
|
||||
)
|
||||
}
|
||||
|
||||
/// Keep CMYK output profiles and page text on the existing PDF composition path. GDI currently
|
||||
/// draws RGB/gray and vector marks only; it must never silently omit requested page content.
|
||||
fn native_rgb_compatible(page: &PrintPage, handling: &str) -> bool {
|
||||
matches!(page.image.channels, 1 | 3)
|
||||
&& (page.image.icc.is_none() || matches!(handling, "photocraftManages" | "photoshopManages" | "noColorManagement"))
|
||||
&& page.description.as_deref().is_none_or(str::is_empty)
|
||||
&& page.label.as_deref().is_none_or(str::is_empty)
|
||||
}
|
||||
|
||||
/// Print One Copy repeats these.
|
||||
fn remember_print(s: &mut Session, p: &Value) {
|
||||
let mut remembered = p.clone();
|
||||
@@ -436,6 +456,101 @@ fn remember_print(s: &mut Session, p: &Value) {
|
||||
s.file_menu.last_print = Some(remembered);
|
||||
}
|
||||
|
||||
/// The `printer` parameter, or the system's default printer.
|
||||
fn printer_name(p: &Value) -> Result<String> {
|
||||
if let Some(name) = p.get("printer").and_then(Value::as_str).filter(|v| !v.trim().is_empty()) {
|
||||
return Ok(name.to_string());
|
||||
}
|
||||
craft_print::rgb::default_printer().map_err(other)?.ok_or_else(|| other("no printer chosen and no default printer is set"))
|
||||
}
|
||||
|
||||
/// The driver settings chosen with Print Settings… (`printerSettings`, hex), when any.
|
||||
fn printer_settings(p: &Value) -> Result<Option<craft_print::rgb::DevMode>> {
|
||||
match p.get("printerSettings").and_then(Value::as_str).filter(|v| !v.is_empty()) {
|
||||
Some(hex) => craft_print::rgb::DevMode::from_hex(hex).map(Some).map_err(|e| bad("file.print", e.to_string())),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// The page's image as 8-bit RGB rows (gray expanded), mirrored for Emulsion Down.
|
||||
pub fn page_rgb(page: &PrintPage) -> Result<Vec<u8>> {
|
||||
let img = &page.image;
|
||||
let (w, h) = (img.width as usize, img.height as usize);
|
||||
let mut rgb = match img.channels {
|
||||
3 => img.data.clone(),
|
||||
1 => img.data.iter().flat_map(|g| [*g, *g, *g]).collect(),
|
||||
_ => return Err(other("this printer profile is CMYK; Windows printers take RGB, so choose the printer's own (RGB) profile")),
|
||||
};
|
||||
let row = w.checked_mul(3).ok_or_else(|| other("print image is too large"))?;
|
||||
if row == 0 || row.checked_mul(h) != Some(rgb.len()) {
|
||||
return Err(other("nothing to print"));
|
||||
}
|
||||
if page.emulsion_down {
|
||||
for row in rgb.chunks_exact_mut(row) {
|
||||
row.as_chunks_mut::<3>().0.reverse();
|
||||
}
|
||||
}
|
||||
Ok(rgb)
|
||||
}
|
||||
|
||||
/// The image box with its origin at the sheet's top-left (GDI's), mirrored for Emulsion Down.
|
||||
pub fn page_rect_top_left(page: &PrintPage) -> (f64, f64, f64, f64) {
|
||||
let (pw, ph) = page.paper;
|
||||
let (x, y, w, h) = page.rect;
|
||||
let x = if page.emulsion_down { pw - x - w } else { x };
|
||||
(x, ph - y - h, w, h)
|
||||
}
|
||||
|
||||
/// Prints `page` on a Windows printer. Corner/centre crop and registration marks are drawn with
|
||||
/// GDI vector calls, matching the PDF path's geometry; description and label text are still
|
||||
/// PDF-only (no font/text layout in the GDI path yet).
|
||||
fn print_windows(page: &PrintPage, p: &Value, title: &str, copies: u32) -> Result<Value> {
|
||||
let printer = printer_name(p)?;
|
||||
let settings = printer_settings(p)?;
|
||||
let device_page = craft_print::rgb::page(&printer, settings.as_ref()).map_err(other)?;
|
||||
if (device_page.paper.0 - page.paper.0).abs() > 2.0 || (device_page.paper.1 - page.paper.1).abs() > 2.0 {
|
||||
return Err(other("the driver paper or orientation differs from the print layout; choose the matching paper in Print Settings before printing"));
|
||||
}
|
||||
let rgb = page_rgb(page)?;
|
||||
let image = craft_print::rgb::RgbImage { width: page.image.width, height: page.image.height, data: &rgb };
|
||||
let rect = page_rect_top_left(page);
|
||||
let primitives = windows_marks::primitives(page.marks, rect);
|
||||
let color_policy = match p.get("colorHandling").and_then(Value::as_str) {
|
||||
Some("photocraftManages" | "photoshopManages") => craft_print::rgb::ColorPolicy::ApplicationManaged,
|
||||
Some("noColorManagement") => craft_print::rgb::ColorPolicy::Unmanaged,
|
||||
_ => craft_print::rgb::ColorPolicy::DriverManaged,
|
||||
};
|
||||
let job = craft_print::rgb::Job {
|
||||
printer: &printer,
|
||||
settings: settings.as_ref(),
|
||||
title,
|
||||
output_file: None,
|
||||
copies: copies.clamp(1, 999),
|
||||
color_policy,
|
||||
primitives: &primitives,
|
||||
};
|
||||
let done = craft_print::rgb::print(&job, &image, rect).map_err(other)?;
|
||||
Ok(
|
||||
json!({"printer": printer, "dpi": [done.dpi.0, done.dpi.1], "deviceRect": [done.device_rect.0, done.device_rect.1, done.device_rect.2, done.device_rect.3]}),
|
||||
)
|
||||
}
|
||||
|
||||
fn printers(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
match craft_print::rgb::printers() {
|
||||
Ok(list) => Ok(json!({"supported": true, "printers": list.iter().map(|p| json!({"name": p.name, "default": p.default})).collect::<Vec<_>>()})),
|
||||
Err(craft_print::rgb::PrintError::Unsupported) => Ok(json!({"supported": false, "printers": []})),
|
||||
Err(e) => Err(other(e)),
|
||||
}
|
||||
}
|
||||
|
||||
fn printer_page(_: &mut Session, p: &Value) -> Result<Value> {
|
||||
let printer = printer_name(p)?;
|
||||
let pg = craft_print::rgb::page(&printer, printer_settings(p)?.as_ref()).map_err(other)?;
|
||||
Ok(
|
||||
json!({"printer": printer, "paper": [pg.paper.0, pg.paper.1], "printable": [pg.printable.0, pg.printable.1, pg.printable.2, pg.printable.3], "dpi": [pg.dpi.0, pg.dpi.1]}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Set once by test harnesses (the panic hunt) so no command in the process can reach a printer.
|
||||
static PRINTING_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
|
||||
@@ -450,9 +565,17 @@ pub fn printing_disabled() -> bool {
|
||||
PRINTING_DISABLED.load(std::sync::atomic::Ordering::Relaxed) || std::env::var_os("PHOTOCRAFT_NO_PRINT").is_some_and(|v| !v.is_empty() && v != "0")
|
||||
}
|
||||
|
||||
fn require_printing_enabled() -> Result<()> {
|
||||
if printing_disabled() {
|
||||
Err(other("printing is disabled in this process (photocraft_engine::print_cmds::disable_printing or PHOTOCRAFT_NO_PRINT); use dryRun: true"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The printers the system spooler knows (Print's Printer menu): CUPS queues and driverless
|
||||
/// destinations on macOS and Linux, `Win32_Printer` on Windows, none in the browser.
|
||||
fn printers(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
fn system_printers(_: &mut Session, _: &Value) -> Result<Value> {
|
||||
let list = craft_print::printers();
|
||||
let default = list.iter().find(|p| p.default).map(|p| p.name.clone());
|
||||
let printers: Vec<Value> = list.into_iter().map(|p| json!({"name": p.name, "default": p.default})).collect();
|
||||
@@ -627,9 +750,30 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
|
||||
};
|
||||
}
|
||||
const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##;
|
||||
const PRINT_PARAMS: &str = r##"{"printerSettings":hex? (Windows driver settings),"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the backend command, don't spool; write a PDF only at an explicit output path)} → {pdf:path|null (null without explicit output), imageRect, command:diagnostic array|null, sent}"##;
|
||||
|
||||
vec![
|
||||
spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print),
|
||||
CommandSpec {
|
||||
id: "file.print.printers",
|
||||
label: "Printers",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{} → {supported, printers: [{name, default}]} (supported: Windows; elsewhere Print spools with lp)"##,
|
||||
enabled: |_| Ok(()),
|
||||
journal: false,
|
||||
run: printers,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.print.page",
|
||||
label: "Printer Page",
|
||||
menu: &[],
|
||||
shortcut: None,
|
||||
params: r##"{"printer":name? (default printer),"printerSettings":hex?} → {printer, paper: [w,h] pt, printable: [x,y,w,h] pt from the top-left, dpi: [x,y]} (Windows)"##,
|
||||
enabled: |_| Ok(()),
|
||||
journal: false,
|
||||
run: printer_page,
|
||||
},
|
||||
CommandSpec {
|
||||
id: "file.printers",
|
||||
label: "Printers",
|
||||
@@ -638,7 +782,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
params: r##"{} → {printers:[{name, default}], default:name|null} (the system spooler's printers; a name is Print's "printer")"##,
|
||||
enabled: crate::commands::always,
|
||||
journal: false,
|
||||
run: printers,
|
||||
run: system_printers,
|
||||
},
|
||||
spec!(
|
||||
"file.printOneCopy",
|
||||
|
||||
@@ -52,7 +52,7 @@ fn print_dry_run_renders_a_pdf_and_reports_the_platform_backend() {
|
||||
assert!(!cmd.contains(&out), "PDF bytes are streamed instead of passing a path");
|
||||
}
|
||||
#[cfg(windows)]
|
||||
assert!(cmd.last().unwrap().contains("craft-print PDF spooler"));
|
||||
assert_eq!(cmd.first().map(String::as_str), Some("xps-print"));
|
||||
assert_eq!(r["sent"], false);
|
||||
assert_eq!(r["pdf"], out);
|
||||
let pdf = std::fs::read(&out).unwrap();
|
||||
@@ -151,6 +151,60 @@ fn emulsion_down_mirrors_the_whole_page() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
fn page_of(channels: usize, data: Vec<u8>, emulsion_down: bool) -> PrintPage {
|
||||
PrintPage {
|
||||
paper: (600.0, 800.0),
|
||||
image: PrintImage { width: 2, height: 1, channels, data, icc: None },
|
||||
rect: (100.0, 200.0, 144.0, 72.0),
|
||||
marks: Marks::default(),
|
||||
description: None,
|
||||
label: None,
|
||||
emulsion_down,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_print_image_is_rgb_mirrored_for_emulsion_down() {
|
||||
assert_eq!(page_rgb(&page_of(3, vec![1, 2, 3, 4, 5, 6], false)).unwrap(), [1, 2, 3, 4, 5, 6]);
|
||||
assert_eq!(page_rgb(&page_of(3, vec![1, 2, 3, 4, 5, 6], true)).unwrap(), [4, 5, 6, 1, 2, 3]);
|
||||
assert_eq!(page_rgb(&page_of(1, vec![7, 9], true)).unwrap(), [9, 9, 9, 7, 7, 7]);
|
||||
assert!(page_rgb(&page_of(4, vec![0; 8], false)).is_err(), "CMYK can't go to a GDI printer");
|
||||
assert!(page_rgb(&page_of(3, vec![0; 5], false)).is_err(), "short data");
|
||||
// GDI's origin is the sheet's top-left; Emulsion Down moves the box to the mirrored side.
|
||||
assert_eq!(page_rect_top_left(&page_of(3, vec![0; 6], false)), (100.0, 528.0, 144.0, 72.0));
|
||||
assert_eq!(page_rect_top_left(&page_of(3, vec![0; 6], true)), (356.0, 528.0, 144.0, 72.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_rgb_route_preserves_pdf_only_color_and_page_content() {
|
||||
let mut page = page_of(3, vec![0; 6], false);
|
||||
assert!(native_rgb_compatible(&page, "printerManages"));
|
||||
page.label = Some("Print Me".into());
|
||||
assert!(!native_rgb_compatible(&page, "printerManages"));
|
||||
page.label = None;
|
||||
page.description = Some("Proof description".into());
|
||||
assert!(!native_rgb_compatible(&page, "printerManages"));
|
||||
page.description = Some(String::new());
|
||||
assert!(native_rgb_compatible(&page, "printerManages"));
|
||||
page.image.icc = Some(vec![1, 2, 3]);
|
||||
assert!(!native_rgb_compatible(&page, "printerManages"), "preserve embedded source ICC in the PDF route");
|
||||
assert!(native_rgb_compatible(&page, "photocraftManages"));
|
||||
assert!(native_rgb_compatible(&page, "photoshopManages"));
|
||||
assert!(!native_rgb_compatible(&page_of(4, vec![0; 8], false), "photocraftManages"));
|
||||
assert!(native_rgb_compatible(&page_of(1, vec![0; 2], false), "noColorManagement"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_commands_answer_without_a_document_and_reject_bad_settings() {
|
||||
let mut s = Session::new();
|
||||
let r = s.execute("file.print.printers", json!({})).unwrap();
|
||||
assert_eq!(r["supported"], cfg!(windows));
|
||||
assert!(r["printers"].is_array());
|
||||
assert!(s.execute("file.print.page", json!({"printer": "Anything", "printerSettings": "zz"})).is_err());
|
||||
let mut s = session("rgb", 8);
|
||||
assert!(s.execute("file.print", json!({"printer": "Anything", "printerSettings": "0102", "send": true})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn printer_profile_can_be_an_installed_icc_file() {
|
||||
let dir = tmp("icc");
|
||||
@@ -183,7 +237,7 @@ fn print_one_copy_repeats_the_last_settings() {
|
||||
#[cfg(unix)]
|
||||
assert_eq!(&cmd[..3], &["lp", "-n", "1"]);
|
||||
#[cfg(windows)]
|
||||
assert!(cmd.last().unwrap().contains("craft-print PDF spooler"));
|
||||
assert_eq!(cmd.first().map(String::as_str), Some("xps-print"));
|
||||
assert!(r["pdf"].is_null());
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
//! App-owned print-mark composition in points from the sheet's top-left.
|
||||
use super::Marks;
|
||||
use craft_print::rgb::{Primitive, Shape};
|
||||
|
||||
pub(super) fn primitives(marks: Marks, (x, y, w, h): (f64, f64, f64, f64)) -> Vec<Primitive> {
|
||||
let mut out = Vec::with_capacity(24);
|
||||
let line = |out: &mut Vec<Primitive>, x0, y0, x1, y1| {
|
||||
out.push(Primitive { shape: Shape::Line { from: (x0, y0), to: (x1, y1) }, width: 0.3, color: [0; 3] });
|
||||
};
|
||||
let (gap, len) = (6.0, 18.0);
|
||||
if marks.corner_crop {
|
||||
for (cx, cy, dx, dy) in [(x, y, -1.0, -1.0), (x + w, y, 1.0, -1.0), (x, y + h, -1.0, 1.0), (x + w, y + h, 1.0, 1.0)] {
|
||||
line(&mut out, cx + dx * gap, cy, cx + dx * (gap + len), cy);
|
||||
line(&mut out, cx, cy + dy * gap, cx, cy + dy * (gap + len));
|
||||
}
|
||||
}
|
||||
if marks.center_crop {
|
||||
let (mx, my) = (x + w / 2.0, y + h / 2.0);
|
||||
line(&mut out, mx, y - gap, mx, y - gap - len);
|
||||
line(&mut out, mx, y + h + gap, mx, y + h + gap + len);
|
||||
line(&mut out, x - gap, my, x - gap - len, my);
|
||||
line(&mut out, x + w + gap, my, x + w + gap + len, my);
|
||||
}
|
||||
if marks.registration {
|
||||
let (r, off) = (5.0, gap + len / 2.0);
|
||||
for (cx, cy) in [(x + w / 2.0, y - off), (x + w / 2.0, y + h + off), (x - off, y + h / 2.0), (x + w + off, y + h / 2.0)] {
|
||||
out.push(Primitive { shape: Shape::Ellipse { bounds: (cx - r, cy - r, 2.0 * r, 2.0 * r) }, width: 0.3, color: [0; 3] });
|
||||
line(&mut out, cx - r * 1.6, cy, cx + r * 1.6, cy);
|
||||
line(&mut out, cx, cy - r * 1.6, cx, cy + r * 1.6);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn marks_surround_the_final_image_box_in_physical_points() {
|
||||
let out = primitives(Marks { corner_crop: true, center_crop: true, registration: true }, (100.0, 200.0, 144.0, 72.0));
|
||||
assert_eq!(out.len(), 24);
|
||||
assert_eq!(out[0].shape, Shape::Line { from: (94.0, 200.0), to: (76.0, 200.0) });
|
||||
assert_eq!(out[12].shape, Shape::Ellipse { bounds: (167.0, 180.0, 10.0, 10.0) });
|
||||
assert!(out.iter().all(|p| p.width == 0.3 && p.color == [0; 3]));
|
||||
assert!(primitives(Marks::default(), (0.0, 0.0, 10.0, 10.0)).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -78,7 +78,6 @@ fn fill_opacity_masks_and_layer_opacity_survive_the_bake() {
|
||||
s.execute("layer.setProps", json!({"layer": id, "fill": 0.4, "opacity": 0.7})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 34, "height": 48})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let square = json!({"subpaths": [{"closed": true, "knots": [[4, 4], [60, 4], [60, 26], [4, 26]]}]});
|
||||
s.execute("layer.vectorMask.add", json!({"layer": id, "path": square})).unwrap();
|
||||
bake_and_check(&mut s, id, depth);
|
||||
@@ -153,7 +152,7 @@ fn disabled_and_bad_params_fail_gracefully() {
|
||||
let (mut s, id) = scene(8);
|
||||
let bg = doc(&s).layers[0].id.0;
|
||||
assert!(s.execute(ID, json!({"layer": bg})).is_err(), "the Background has no effects");
|
||||
assert!(s.execute(ID, json!({"layer": 9999})).is_err(), "no such layer");
|
||||
assert!(s.execute(ID, json!({"layer": u64::MAX})).is_err(), "no such layer");
|
||||
assert!(s.execute(ID, json!({"layer": u64::MAX})).is_err(), "no such layer");
|
||||
assert_eq!(layer(&s, id).effects.items.len(), 5, "a bad call changes nothing");
|
||||
s.execute("layer.layerStyle.hideAllEffects", json!({})).unwrap();
|
||||
|
||||
@@ -993,7 +993,7 @@ fn patch_fails_gracefully() {
|
||||
json!({"offset": [0, -30]}),
|
||||
json!({"offset": [10, 0], "target": "mask"}),
|
||||
json!({"offset": [10, 0], "target": {"channel": 7}}),
|
||||
json!({"offset": [10, 0], "layer": 999}),
|
||||
json!({"offset": [10, 0], "layer": u64::MAX}),
|
||||
] {
|
||||
assert!(s.execute("paint.patch", p.clone()).is_err(), "{p}");
|
||||
}
|
||||
@@ -1269,7 +1269,7 @@ fn content_aware_move_fails_gracefully() {
|
||||
json!({"offset": [0, -30]}),
|
||||
json!({"offset": [10, 0], "target": "mask"}),
|
||||
json!({"offset": [10, 0], "target": {"channel": 7}}),
|
||||
json!({"offset": [10, 0], "layer": 999}),
|
||||
json!({"offset": [10, 0], "layer": u64::MAX}),
|
||||
json!({"offset": [10, 0], "scaleX": 0}),
|
||||
json!({"offset": [10, 0], "scaleY": 0.5}),
|
||||
json!({"offset": [10, 0], "scaleX": 1e9}),
|
||||
@@ -1727,7 +1727,7 @@ fn remove_bad_params_are_errors() {
|
||||
json!({"points": []}),
|
||||
json!({"points": "x"}),
|
||||
json!({"points": [[1, 1]], "size": "big", "closeLoops": "yes", "sampleAllLayers": 3}),
|
||||
json!({"points": [[1, 1]], "layer": 999_999}),
|
||||
json!({"points": [[1, 1]], "layer": u64::MAX}),
|
||||
] {
|
||||
let _ = s.execute("paint.remove", p);
|
||||
}
|
||||
|
||||
@@ -461,7 +461,12 @@ fn modify(s: &mut Session, p: &Value, op: &str) -> Result<Value> {
|
||||
// continue past the canvas. Border has no such option: its band always follows the canvas edge,
|
||||
// or a Select All would border to nothing.
|
||||
let at_bounds = op == "border" || b(p, "applyAtCanvasBounds", false);
|
||||
let (area, m) = current_mask(&s.active().ok_or(EngineError::NoDocument)?.doc);
|
||||
let doc = &s.active().ok_or(EngineError::NoDocument)?.doc;
|
||||
let area = doc.bounds();
|
||||
if area.size().area() > MAX_MODIFY_PIXELS as u64 {
|
||||
return Err(EngineError::BadParams { cmd: format!("select.modify.{op}"), msg: "the selection is too large to modify".into() });
|
||||
}
|
||||
let (_, m) = current_mask(doc);
|
||||
let (w, h) = (area.width() as usize, area.height() as usize);
|
||||
// Feather reaches 3σ = 3 r (σ = r, as in Photoshop); the others reach r. A margin past that
|
||||
// keeps the canvas edge out of reach. A selection clear of the canvas edge needs none: both
|
||||
@@ -765,6 +770,28 @@ mod tests {
|
||||
assert!(err.to_string().contains("detectFaces"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modify_rejects_oversized_canvases_before_reading_the_mask() {
|
||||
let mut s = Session::new();
|
||||
let mut doc = photocraft_doc::Document::new(
|
||||
"large",
|
||||
photocraft_geom::Size::new(300_000, 300_000),
|
||||
photocraft_color::ColorMode::Rgb,
|
||||
photocraft_color::SampleType::U8,
|
||||
);
|
||||
let mut selection = photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8);
|
||||
selection.write_pixel(0, 0, &[1.0]);
|
||||
doc.selection = Some(selection);
|
||||
s.add_document(doc, None);
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
for op in ["expand", "contract", "border", "smooth", "feather"] {
|
||||
let error = s.execute(&format!("select.modify.{op}"), json!({"radius": 1})).unwrap_err();
|
||||
assert!(error.to_string().contains("too large to modify"));
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
assert!(!s.active().unwrap().history.can_undo());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_range_replace_is_bounded_by_existing_selection() {
|
||||
for params in [json!({"color": "#ff0000", "fuzziness": 0}), json!({"select": "reds"})] {
|
||||
@@ -850,7 +877,6 @@ mod tests {
|
||||
let mut s = session();
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("view.layerMask", json!({"mode": "gray"})).unwrap();
|
||||
s.execute("select.magicWand", json!({"x": 7, "y": 7, "tolerance": 0, "antiAlias": false})).unwrap();
|
||||
assert_eq!(coverage(&s, 2, 2), 1.0, "gray mask view selects the mask");
|
||||
@@ -977,6 +1003,45 @@ mod tests {
|
||||
assert!(lighter > redder + 0.15 && redder > 0.0, "lighter {lighter}, redder {redder}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_range_fuzziness_zero_selects_exact_match_only() {
|
||||
// Sampled Colors at Fuzziness 0 selects only the exact match (TOOL-214-3, #214).
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 50, "height": 10})).unwrap();
|
||||
s.edit("paint", |doc, _| {
|
||||
let bg = doc.layers[0].surface_mut().unwrap();
|
||||
let v = |c: u8| f32::from(c) / 255.0;
|
||||
// Exact target color [200, 140, 120]
|
||||
bg.fill_rect(Rect::new(0, 0, 10, 10), &[v(200), v(140), v(120), 1.0]);
|
||||
// Off by 1 level in red [201, 140, 120]
|
||||
bg.fill_rect(Rect::new(10, 0, 20, 10), &[v(201), v(140), v(120), 1.0]);
|
||||
// Off by 1 level in green [200, 141, 120]
|
||||
bg.fill_rect(Rect::new(20, 0, 30, 10), &[v(200), v(141), v(120), 1.0]);
|
||||
// Off by 2 levels in blue [200, 140, 122] (crosses 8-bit Lab grid threshold)
|
||||
bg.fill_rect(Rect::new(30, 0, 40, 10), &[v(200), v(140), v(122), 1.0]);
|
||||
// Exact target color again at a different position
|
||||
bg.fill_rect(Rect::new(40, 0, 50, 10), &[v(200), v(140), v(120), 1.0]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
// Sampled via eyedropper point at [5, 5] with Fuzziness 0
|
||||
s.execute("select.colorRange", json!({"points": [[5, 5]], "fuzziness": 0})).unwrap();
|
||||
assert_eq!(coverage(&s, 5, 5), 1.0, "sampled pixel itself is fully selected");
|
||||
assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected");
|
||||
assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected at fuzziness 0");
|
||||
assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected at fuzziness 0");
|
||||
assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected at fuzziness 0");
|
||||
|
||||
// Sampled via hex color with Fuzziness 0
|
||||
s.execute("select.colorRange", json!({"color": "#c88c78", "fuzziness": 0})).unwrap();
|
||||
assert_eq!(coverage(&s, 5, 5), 1.0, "exact color match from hex is fully selected");
|
||||
assert_eq!(coverage(&s, 45, 5), 1.0, "identical color elsewhere on canvas is fully selected");
|
||||
assert_eq!(coverage(&s, 15, 5), 0.0, "1 level off in red is unselected for hex at fuzziness 0");
|
||||
assert_eq!(coverage(&s, 25, 5), 0.0, "1 level off in green is unselected for hex at fuzziness 0");
|
||||
assert_eq!(coverage(&s, 35, 5), 0.0, "1 level off in blue is unselected for hex at fuzziness 0");
|
||||
}
|
||||
|
||||
/// Red squares (from `session`), a blue square, a black and a mid-grey strip on white.
|
||||
fn session_colours() -> Session {
|
||||
let mut s = session();
|
||||
|
||||
@@ -243,7 +243,7 @@ fn smart_filter_commands_check_an_explicit_layer_target() {
|
||||
assert_eq!(active(&s), curves, "the active layer stays");
|
||||
// A target that isn't a smart object with filters is still refused, and the active layer stays.
|
||||
assert!(matches!(s.execute("layer.smartFilter.setParams", json!({"layer": curves, "params": {}})), Err(EngineError::Disabled(..))));
|
||||
assert!(s.execute("layer.smartFilter.setParams", json!({"layer": 999_999, "params": {}})).is_err());
|
||||
assert!(s.execute("layer.smartFilter.setParams", json!({"layer": u64::MAX, "params": {}})).is_err());
|
||||
assert_eq!(active(&s), curves);
|
||||
}
|
||||
|
||||
|
||||
@@ -217,10 +217,23 @@ impl ObjectFinderCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Object Selection samples only the active layer by default: when that layer has no pixels in
|
||||
/// `area`, say so instead of quietly finding nothing (#5246; scripts often add an empty layer
|
||||
/// above the photo first).
|
||||
fn check_sampled_pixels(doc: &Document, layer: Option<LayerId>, all_layers: bool, area: Rect) -> Result<()> {
|
||||
let Some(surf) = sampled_target(doc, layer, all_layers).and_then(|id| doc.layer(id)).and_then(Layer::surface) else { return Ok(()) };
|
||||
if surf.content_bounds().intersect(&area).is_empty() {
|
||||
let msg = if surf.content_bounds().is_empty() { "the active layer is empty" } else { "the active layer has no pixels in that area" };
|
||||
return Err(bad("select.object", &format!("{msg}; set \"sampleAllLayers\": true or select a layer with pixels")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `select.object` with `"point"`: the Object Finder's object under the point (cached).
|
||||
fn object_at_point(s: &mut Session, p: &Value, (x, y): (f32, f32)) -> Result<Value> {
|
||||
let all_layers = b(p, "sampleAllLayers", false);
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
check_sampled_pixels(&d.doc, d.active_layer, all_layers, Rect::from_xywh(x.floor() as i32, y.floor() as i32, 1, 1))?;
|
||||
let target = sampled_target(&d.doc, d.active_layer, all_layers);
|
||||
let region = match s.object_finder.lookup(&d.doc, target, x, y) {
|
||||
Some(r) => Some(r),
|
||||
@@ -248,7 +261,10 @@ fn object_selection(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
return object_at_point(s, p, pt);
|
||||
}
|
||||
let rect = rect_param(p).ok_or_else(|| bad("select.object", "needs \"rect\": [x, y, w, h] or \"point\": [x, y]"))?;
|
||||
let region = with_sampler(s, b(p, "sampleAllLayers", false), |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?;
|
||||
let all_layers = b(p, "sampleAllLayers", false);
|
||||
let d = s.active().ok_or(EngineError::NoDocument)?;
|
||||
check_sampled_pixels(&d.doc, d.active_layer, all_layers, rect)?;
|
||||
let region = with_sampler(s, all_layers, |smp, doc| grabcut::object_select(smp, doc.bounds(), rect, 160_000))?;
|
||||
apply(s, "Object Selection", region.as_ref(), mode(p, "replace"))
|
||||
}
|
||||
|
||||
@@ -417,6 +433,7 @@ fn refine_edge(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Select and Mask", |doc, _| {
|
||||
let surface =
|
||||
region.as_ref().map(matting::region_surface).unwrap_or_else(|| photocraft_raster::Surface::new(photocraft_color::PixelFormat::GRAY8));
|
||||
crate::extra_cmds::background_to_layer_for_mask(doc, id);
|
||||
let existing = doc.layer(id).and_then(|l| l.mask.as_ref()).cloned().unwrap_or_else(LayerMask::reveal_all);
|
||||
doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface, ..existing });
|
||||
doc.selection = None;
|
||||
@@ -703,7 +720,7 @@ mod tests {
|
||||
// Any point on the object hits; the background and another target miss.
|
||||
assert!(std::sync::Arc::ptr_eq(&s.object_finder.lookup(&doc, target, 120.0, 90.0).unwrap(), &r));
|
||||
assert!(s.object_finder.lookup(&doc, target, 3.0, 3.0).is_none());
|
||||
assert!(s.object_finder.lookup(&doc, Some(LayerId(9999)), 100.0, 80.0).is_none());
|
||||
assert!(s.object_finder.lookup(&doc, Some(LayerId(u64::MAX)), 100.0, 80.0).is_none());
|
||||
// The click reuses it, and a selection-only edit keeps it.
|
||||
s.execute("select.object", json!({"point": [110, 70]})).unwrap();
|
||||
assert_eq!(s.object_finder.len(), 1);
|
||||
@@ -730,6 +747,26 @@ mod tests {
|
||||
assert!(cov(&s, 100, 80) >= 0.5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_selection_on_an_empty_active_layer_says_so() {
|
||||
// #5246: an empty layer above the photo used to find nothing without a word.
|
||||
let (mut s, inside) = disc(8);
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
for p in [json!({"rect": [40, 20, 120, 120]}), json!({"point": [100, 80]})] {
|
||||
let e = s.execute("select.object", p.clone()).unwrap_err().to_string();
|
||||
assert!(e.contains("active layer is empty") && e.contains("sampleAllLayers"), "{p}: {e}");
|
||||
assert!(s.active().unwrap().doc.selection.is_none());
|
||||
}
|
||||
// Sampling all layers finds the disc below.
|
||||
s.execute("select.object", json!({"rect": [40, 20, 120, 120], "sampleAllLayers": true})).unwrap();
|
||||
assert!(sel_iou(&s, 200, 160, &inside) > 0.95);
|
||||
// A layer with pixels elsewhere: the rectangle holds none of them.
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.execute("paint.pencil", json!({"points": [[5, 5], [10, 5]], "size": 2, "color": "#000000"})).unwrap();
|
||||
let e = s.execute("select.object", json!({"rect": [60, 60, 100, 80]})).unwrap_err().to_string();
|
||||
assert!(e.contains("no pixels in that area"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_subject_centred_object() {
|
||||
let (mut s, inside) = disc(8);
|
||||
@@ -970,7 +1007,6 @@ mod tests {
|
||||
fn refine_edge_works_on_layer_mask_without_selection() {
|
||||
let mut s = blurred_edge_selected();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
assert!(s.active().unwrap().doc.selection.is_none());
|
||||
assert!(s.active().unwrap().doc.layers[0].mask.is_some());
|
||||
assert!(s.is_enabled("select.refineEdge"));
|
||||
|
||||
@@ -553,7 +553,7 @@ fn clipping_masks_apply_to_every_selected_layer() {
|
||||
// A `layer` param still acts on that layer alone.
|
||||
s.execute("layer.releaseClippingMask", json!({"layer": ids[2]})).unwrap();
|
||||
assert_eq!(clipped(&s), [false, true, false]);
|
||||
assert!(s.execute("layer.createClippingMask", json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute("layer.createClippingMask", json!({"layer": u64::MAX})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -992,8 +992,8 @@ fn move_to_copy_rejects_bad_params() {
|
||||
for p in [
|
||||
json!({"layer": a, "copy": true}),
|
||||
json!({"layer": a, "target": "x", "copy": true}),
|
||||
json!({"layer": a, "target": 9_999_999, "copy": true}),
|
||||
json!({"layer": 9_999_999, "target": a, "copy": true}),
|
||||
json!({"layer": a, "target": u64::MAX, "copy": true}),
|
||||
json!({"layer": u64::MAX, "target": a, "copy": true}),
|
||||
json!({"layer": a, "target": a, "position": "into", "copy": true}),
|
||||
] {
|
||||
assert!(s.execute("layer.moveTo", p.clone()).is_err(), "{p}");
|
||||
|
||||
@@ -482,7 +482,7 @@ mod tests {
|
||||
bad(&mut s, "type.navigate", json!({"layer": id, "index": 9, "move": "end"}));
|
||||
bad(&mut s, "type.navigate", json!({"layer": id, "index": 0, "move": "lineNext", "x": "no"}));
|
||||
bad(&mut s, "type.navigate", json!({"layer": pixel, "index": 0, "move": "start"}));
|
||||
assert!(matches!(s.execute("type.caret", json!({"layer": 9_999_999, "index": 0})), Err(EngineError::NoLayer(_))));
|
||||
assert!(matches!(s.execute("type.caret", json!({"layer": u64::MAX, "index": 0})), Err(EngineError::NoLayer(_))));
|
||||
// A point on the named layer but outside its text still returns a caret, marked outside.
|
||||
let far = s.execute("type.hitTest", json!({"layer": id, "x": 390, "y": 290})).unwrap();
|
||||
assert_eq!(far["inside"], false);
|
||||
|
||||
@@ -1184,7 +1184,7 @@ mod tests {
|
||||
st.saved_revision = st.revision;
|
||||
}
|
||||
let rev = s.active().unwrap().revision;
|
||||
let unknown = [(doc_id, LayerId(9999)), (photocraft_doc::DocId(u64::MAX), id)];
|
||||
let unknown = [(doc_id, LayerId(u64::MAX)), (photocraft_doc::DocId(u64::MAX), id)];
|
||||
assert!(s.refresh_type_layers(&[&[(doc_id, id)][..], &unknown].concat()).is_empty());
|
||||
assert!(text_layer(&s, id.0).cache.is_some());
|
||||
let st = s.active().unwrap();
|
||||
|
||||
@@ -108,8 +108,9 @@ fn vertical_orientation_renders_columns_inside_the_canvas() {
|
||||
assert!(l.vertical && l.lines.len() == 2);
|
||||
let [x0, y0, x1, y1] = l.bounds().unwrap();
|
||||
assert!(x1 > 0.0 && x0 < -40.0 && y0 >= -1e-3 && y1 > 60.0, "{:?}", l.bounds());
|
||||
// Bad layer ids fail cleanly.
|
||||
assert!(s.execute("type.orientation.vertical", json!({"layer": 9999})).is_err());
|
||||
// Bad layer ids fail cleanly. Not a small number like 9999: ids come from one process-wide
|
||||
// counter, so in a full test run a layer made above can get it (#3343).
|
||||
assert!(s.execute("type.orientation.vertical", json!({"layer": u64::MAX})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -299,7 +300,7 @@ fn type_attaches_to_a_path_and_releases_it() {
|
||||
.unwrap();
|
||||
assert!(s.execute("type.attachToPath", json!({"subpath": 5})).is_err());
|
||||
assert!(s.execute("type.attachToPath", json!({"start": "far"})).is_err());
|
||||
assert!(s.execute("type.attachToPath", json!({"shape": 9999})).is_err());
|
||||
assert!(s.execute("type.attachToPath", json!({"shape": u64::MAX})).is_err());
|
||||
s.execute("type.attachToPath", json!({"start": 4})).unwrap();
|
||||
assert!(matches!(text(&s, id).shape, TextShape::Path { start, .. } if start == 4.0));
|
||||
let on_path = ink(&s, id);
|
||||
|
||||
@@ -105,7 +105,7 @@ fn listed_pixel_methods_can_be_used_to_redefine_variables() {
|
||||
#[test]
|
||||
fn bad_params_are_errors() {
|
||||
let (mut s, _p, badge, _t) = session();
|
||||
assert!(s.execute("image.variables.define", json!({"defs": [{"name": "x", "layer": 999999, "type": "visibility"}]})).is_err());
|
||||
assert!(s.execute("image.variables.define", json!({"defs": [{"name": "x", "layer": u64::MAX, "type": "visibility"}]})).is_err());
|
||||
assert!(s.execute("image.variables.define", json!({"defs": [{"name": "x", "layer": badge.0, "type": "nope"}]})).is_err());
|
||||
assert!(s.execute("image.applyDataSet", json!({"name": "missing"})).is_err());
|
||||
}
|
||||
|
||||
@@ -646,7 +646,6 @@ fn rasterizing_a_vector_mask_keeps_what_the_masks_show() {
|
||||
if let Some((feather, density)) = pm {
|
||||
s.execute("select.rect", json!({"x": 0, "y": 0, "width": 40, "height": 64})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
s.edit("mask settings", |doc, _| {
|
||||
let m = doc.layer_mut(id).unwrap().mask.as_mut().unwrap();
|
||||
(m.feather, m.density) = (feather, density);
|
||||
@@ -925,7 +924,7 @@ fn combine_shapes_fails_gracefully() {
|
||||
let (mut s, a, _) = two_selected_rects(8);
|
||||
let before = doc(&s).clone();
|
||||
let history = s.active().unwrap().history.past_len();
|
||||
let bad_params = [json!({"layer": 999_999}), json!({"layer": a, "subpath": 99}), json!({"subpath": 99}), json!({"tolerance": "x", "layer": 999_999})];
|
||||
let bad_params = [json!({"layer": u64::MAX}), json!({"layer": a, "subpath": 99}), json!({"subpath": 99}), json!({"tolerance": "x", "layer": u64::MAX})];
|
||||
for cmd in [
|
||||
"layer.combineShapes.unite",
|
||||
"layer.combineShapes.subtractFrontShape",
|
||||
|
||||
@@ -122,7 +122,7 @@ fn eraser_bad_params_fail_gracefully() {
|
||||
assert!(s.execute("paint.stroke", json!({"erase": true})).is_err());
|
||||
assert!(s.execute("paint.stroke", json!({"erase": true, "points": []})).is_err());
|
||||
assert!(s.execute("paint.stroke", json!({"erase": true, "points": "x"})).is_err());
|
||||
assert!(erase(&mut s, json!({"layer": 99999})).is_err());
|
||||
assert!(erase(&mut s, json!({"layer": u64::MAX})).is_err());
|
||||
assert!(erase(&mut s, json!({"target": "mask"})).is_err(), "no mask");
|
||||
// Absurd coordinates are refused up front (a stroke that long would run billions of dabs).
|
||||
assert!(erase(&mut s, json!({"points": [[0, 0], [f64::MAX, 0.0]]})).is_err());
|
||||
|
||||
@@ -67,7 +67,7 @@ fn a_named_layer_of_the_wrong_kind_or_that_does_not_exist_is_refused() {
|
||||
let r = s.execute("layer.smartObjects.rasterize", json!({"layer": pixels}));
|
||||
assert!(matches!(r, Err(EngineError::Disabled(..))), "{r:?}");
|
||||
// A layer that doesn't exist falls back to the active layer's check, and still fails.
|
||||
assert!(s.execute("layer.smartObjects.rasterize", json!({"layer": 999_999})).is_err());
|
||||
assert!(s.execute("layer.smartObjects.rasterize", json!({"layer": u64::MAX})).is_err());
|
||||
assert!(s.execute("layer.smartObjects.rasterize", json!({"layer": "nope"})).is_err());
|
||||
assert_eq!(s.active().unwrap().doc, before);
|
||||
assert_eq!(active(&s), pixels);
|
||||
|
||||
@@ -45,7 +45,12 @@ fn newly_created_layer_masks_follow_document_depth() {
|
||||
assert_eq!(m.value(20, 20), white);
|
||||
if selected {
|
||||
assert_eq!(m.value(0, 0), 0.0);
|
||||
assert_eq!(d.doc.selection, before.selection, "the selection is unchanged");
|
||||
if command == "layer.layerMask.revealSelection" {
|
||||
// The selection became the mask: Photoshop drops it, as Hide Selection does.
|
||||
assert!(d.doc.selection.is_none(), "{command}: the selection is dropped");
|
||||
} else {
|
||||
assert_eq!(d.doc.selection, before.selection, "the selection is unchanged");
|
||||
}
|
||||
} else {
|
||||
assert_eq!(m.surface.tile_count(), 0, "uniform masks stay sparse");
|
||||
assert_eq!(m.value(-300_000, 300_000), white);
|
||||
@@ -133,7 +138,8 @@ fn mask_creation_preserves_selection_coverage_and_existing_masks() {
|
||||
before.selection.as_ref().unwrap().read_region(before.bounds()),
|
||||
"{depth}-bit coverage is unchanged"
|
||||
);
|
||||
assert_eq!(after.selection, before.selection);
|
||||
let kept = if command == "layer.layerMask.revealSelection" { None } else { before.selection.clone() };
|
||||
assert_eq!(after.selection, kept, "{command}");
|
||||
assert_eq!(after.layers[0].mask, before.layers[0].mask, "creating a mask does not requantize an existing mask");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
use photocraft_engine::{Session, command_specs};
|
||||
use serde_json::{Value, json};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Mutex, Once, PoisonError, mpsc};
|
||||
use std::time::Duration;
|
||||
|
||||
fn fresh() -> Session {
|
||||
@@ -22,19 +23,41 @@ fn fresh() -> Session {
|
||||
/// 0.3 s even on a heavily loaded machine, so this only catches real hangs.
|
||||
const DEADLINE: Duration = Duration::from_secs(4);
|
||||
|
||||
/// Run `id` with `p` on a fresh session, on a worker thread. `None` if it timed out, else whether
|
||||
/// it finished without panicking (returning Ok or a graceful Err both count).
|
||||
fn run_once(id: &str, p: &Value) -> Option<bool> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let (id, p) = (id.to_string(), p.clone());
|
||||
std::thread::spawn(move || {
|
||||
let r = catch_unwind(AssertUnwindSafe(|| {
|
||||
let mut s = fresh();
|
||||
let _ = s.execute(&id, p);
|
||||
/// Panics anywhere in the process, counted by a hook. `Session::execute` contains a command's
|
||||
/// panic and returns an ordinary `Err`, so the unwind never reaches `catch_unwind` here; the hook
|
||||
/// still sees it, on whichever thread (rayon workers included) it happened (#4982).
|
||||
static PANICS: AtomicUsize = AtomicUsize::new(0);
|
||||
/// One run at a time, so a panic is charged to the run that caused it.
|
||||
static RUN: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Run `f` on a worker thread. `None` if it timed out, else whether it finished without
|
||||
/// panicking, contained or not (returning Ok or a graceful Err both count).
|
||||
fn run_watched(f: impl FnOnce() + Send + 'static) -> Option<bool> {
|
||||
static HOOK: Once = Once::new();
|
||||
HOOK.call_once(|| {
|
||||
let default = std::panic::take_hook();
|
||||
std::panic::set_hook(Box::new(move |info| {
|
||||
PANICS.fetch_add(1, Ordering::SeqCst);
|
||||
default(info);
|
||||
}));
|
||||
});
|
||||
let _one = RUN.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let before = PANICS.load(Ordering::SeqCst);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let r = catch_unwind(AssertUnwindSafe(f));
|
||||
let _ = tx.send(r.is_ok());
|
||||
});
|
||||
rx.recv_timeout(DEADLINE).ok()
|
||||
rx.recv_timeout(DEADLINE).ok().map(|ok| ok && PANICS.load(Ordering::SeqCst) == before)
|
||||
}
|
||||
|
||||
/// Run `id` with `p` on a fresh session; see [`run_watched`].
|
||||
fn run_once(id: &str, p: &Value) -> Option<bool> {
|
||||
let (id, p) = (id.to_string(), p.clone());
|
||||
run_watched(move || {
|
||||
let mut s = fresh();
|
||||
let _ = s.execute(&id, p);
|
||||
})
|
||||
}
|
||||
|
||||
/// `Err` with a reason on panic or hang, `Ok` otherwise.
|
||||
@@ -60,13 +83,18 @@ fn no_command_panics_or_hangs_on_adversarial_params() {
|
||||
json!({"x": 1e5, "y": -1e5, "radius": 300, "amount": 300, "angle": 1e5, "opacity": -100, "scale": -5, "gamma": -1}),
|
||||
json!({"points": [], "from": [0, 0], "to": [0, 0], "stops": [], "matrix": [0, 0, 0, 0, 0, 0], "colors": [], "name": "", "mode": "", "style": ""}),
|
||||
];
|
||||
// Commands whose success reaches outside the process: `file.print` and `file.printOneCopy`
|
||||
// spool to CUPS, so a fuzz run with `{}` printed a blank page on the default printer. Their
|
||||
// params are validated like everyone else's; the spooling itself is not fuzzed.
|
||||
const EXTERNAL: &[&str] = &["file.print", "file.printOneCopy"];
|
||||
let mut bad: Vec<String> = Vec::new();
|
||||
for spec in command_specs().iter().filter(|spec| !EXTERNAL.contains(&spec.id)) {
|
||||
for spec in command_specs() {
|
||||
for p in ¶ms {
|
||||
// Print and Print One Copy reach real printers (lp, or the Windows driver): fuzz them
|
||||
// as dry runs so the hunt never prints a page.
|
||||
let mut p = p.clone();
|
||||
if spec.id.starts_with("file.print")
|
||||
&& let Some(o) = p.as_object_mut()
|
||||
{
|
||||
o.insert("dryRun".into(), json!(true));
|
||||
}
|
||||
let p = &p;
|
||||
if let Err(why) = run_guarded(spec.id, p) {
|
||||
bad.push(format!("{} [{why}] <- {p}", spec.id));
|
||||
break;
|
||||
@@ -75,3 +103,17 @@ fn no_command_panics_or_hangs_on_adversarial_params() {
|
||||
}
|
||||
assert!(bad.is_empty(), "{} commands panicked or hung:\n{}", bad.len(), bad.join("\n"));
|
||||
}
|
||||
|
||||
/// #4982: a panic the code under test contains still fails the run; a graceful `Err` does not.
|
||||
#[test]
|
||||
fn contained_panics_count_and_graceful_errors_do_not() {
|
||||
let contained = run_watched(|| {
|
||||
let _ = catch_unwind(|| panic!("contained, as Session::execute does"));
|
||||
});
|
||||
assert_eq!(contained, Some(false));
|
||||
let graceful = run_watched(|| {
|
||||
let mut s = fresh();
|
||||
assert!(s.execute("layer.delete", json!({"layer": 999999})).is_err());
|
||||
});
|
||||
assert_eq!(graceful, Some(true));
|
||||
}
|
||||
@@ -140,6 +140,6 @@ fn bad_targets_fail_gracefully() {
|
||||
}
|
||||
let mut sc = scene();
|
||||
for id in ["layer.rasterize.layer", "layer.rasterize.shape", "layer.rasterize.smartObject"] {
|
||||
assert!(sc.s.execute(id, json!({"layer": 9_999_999})).is_err(), "{id}: no such layer");
|
||||
assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer");
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,6 @@ fn bad_targets_fail_gracefully() {
|
||||
}
|
||||
let mut sc = scene();
|
||||
for id in ["layer.layerMask.revealAll", "layer.layerStyle.pasteLayerStyle", "layer.layerStyle.clear"] {
|
||||
assert!(sc.s.execute(id, json!({"layer": 9_999_999})).is_err(), "{id}: no such layer");
|
||||
assert!(sc.s.execute(id, json!({"layer": u64::MAX})).is_err(), "{id}: no such layer");
|
||||
}
|
||||
}
|
||||
@@ -199,12 +199,33 @@ pub fn list_recovery(recovery_dir: &Path) -> Vec<RecoveryEntry> {
|
||||
if bundle.join(crate::store::MANIFEST).is_file() {
|
||||
out.push(RecoveryEntry { info, bundle });
|
||||
}
|
||||
} else if e.file_type().is_ok_and(|ft| ft.is_dir())
|
||||
&& let Some(entry) = sidecarless_entry(recovery_dir, &p)
|
||||
{
|
||||
out.push(entry);
|
||||
}
|
||||
}
|
||||
out.sort_by(|a, b| b.info.saved_at.cmp(&a.info.saved_at).then(a.info.key.cmp(&b.info.key)));
|
||||
out
|
||||
}
|
||||
|
||||
/// A committed `<key>.pcraft` bundle (its manifest is written last) whose sidecar was never
|
||||
/// published, e.g. a crash during a document's first autosave. The metadata is rebuilt from the
|
||||
/// manifest (read like a load reads it) and its modification time. Incomplete bundles (no
|
||||
/// readable manifest) and bundles with anything at the sidecar's path are not entries.
|
||||
fn sidecarless_entry(recovery_dir: &Path, bundle: &Path) -> Option<RecoveryEntry> {
|
||||
let key = bundle.file_name()?.to_str()?.strip_suffix(".pcraft")?;
|
||||
if key.is_empty() || sanitize(key) != key || std::fs::symlink_metadata(recovery_dir.join(format!("{key}.json"))).is_ok() {
|
||||
return None;
|
||||
}
|
||||
let meta = std::fs::symlink_metadata(bundle.join(crate::store::MANIFEST)).ok().filter(|m| m.is_file())?;
|
||||
let source = crate::store::DirSource { root: bundle.to_path_buf() };
|
||||
let manifest = crate::store::read_manifest(&source, &crate::LoadOptions::default()).ok()?;
|
||||
let saved_at = meta.modified().ok().and_then(|t| t.duration_since(UNIX_EPOCH).ok()).map_or(0, |d| d.as_secs());
|
||||
let info = RecoveryInfo { key: key.to_string(), document_name: manifest.document.name, original_path: None, saved_at, revision: 0 };
|
||||
Some(RecoveryEntry { info, bundle: bundle.to_path_buf() })
|
||||
}
|
||||
|
||||
/// Load a recovered document.
|
||||
pub fn recover(entry: &RecoveryEntry) -> Result<Document> {
|
||||
crate::load_path(&entry.bundle)
|
||||
@@ -292,8 +313,9 @@ impl RecoveryStore {
|
||||
const ORPHAN_AGE: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
|
||||
|
||||
/// Best-effort removal of recovery data nothing can ever load or clean up:
|
||||
/// - `<key>.pcraft` bundle folders with no `<key>.json` sidecar (a crash during a document's
|
||||
/// first autosave: the sidecar is written after the bundle, and `list_recovery` skips them);
|
||||
/// - `<key>.pcraft` bundle folders with no `<key>.json` sidecar and no readable manifest (a
|
||||
/// crash in the middle of a document's first autosave). A sidecar-less bundle whose manifest
|
||||
/// was committed is complete and listed by `list_recovery`, so it is kept;
|
||||
/// - `*.pcsave.tmp` files left by an interrupted atomic write (see [`crate::atomic::temp_name`])
|
||||
/// that another process created.
|
||||
///
|
||||
@@ -321,7 +343,8 @@ fn sweep_orphans(recovery_dir: &Path, min_age: std::time::Duration) {
|
||||
// Anything at the sidecar's path (even a broken one) keeps the bundle.
|
||||
let has_sidecar = std::fs::symlink_metadata(recovery_dir.join(format!("{key}.json"))).is_ok();
|
||||
let parts = [path.clone(), path.join("tiles"), path.join("blobs")];
|
||||
if !has_sidecar && parts.iter().all(|p| untouched_for(p, min_age, true)) {
|
||||
// A committed bundle is recoverable work: keep exactly what `list_recovery` lists.
|
||||
if !has_sidecar && sidecarless_entry(recovery_dir, &path).is_none() && parts.iter().all(|p| untouched_for(p, min_age, true)) {
|
||||
let _ = std::fs::remove_dir_all(&path);
|
||||
} else {
|
||||
bundles.extend(parts);
|
||||
@@ -437,4 +460,41 @@ mod tests {
|
||||
assert_eq!(recover(&entries[0]).unwrap(), *doc);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_committed_bundle_without_a_sidecar_is_listed_and_survives_the_sweep() {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"pcraft-nosidecar-{}-{}",
|
||||
std::process::id(),
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)
|
||||
));
|
||||
let doc =
|
||||
Arc::new(Document::new("Lost", photocraft_doc::Size { width: 4, height: 4 }, photocraft_color::ColorMode::Rgb, photocraft_color::SampleType::U8));
|
||||
let saver = Autosaver::new(&dir, "first");
|
||||
saver.request(doc.clone(), 1, None, SaveOptions::default());
|
||||
assert!(saver.flush().is_some_and(|r| r.is_ok()));
|
||||
// The crash: the bundle was committed, the sidecar never published.
|
||||
std::fs::remove_file(dir.join("first.json")).unwrap();
|
||||
|
||||
let entries = list_recovery(&dir);
|
||||
assert_eq!(entries.len(), 1, "the committed bundle is discoverable");
|
||||
assert_eq!((entries[0].info.key.as_str(), entries[0].info.document_name.as_str()), ("first", "Lost"));
|
||||
assert_eq!(recover(&entries[0]).unwrap(), *doc);
|
||||
|
||||
sweep_orphans(&dir, std::time::Duration::ZERO);
|
||||
assert!(dir.join("first.pcraft").is_dir(), "aged cleanup keeps a committed bundle");
|
||||
|
||||
// Incomplete bundles (no manifest, or one that does not read) are neither listed nor kept.
|
||||
let partial = dir.join("partial.pcraft");
|
||||
std::fs::create_dir_all(partial.join("tiles")).unwrap();
|
||||
let broken = dir.join("broken.pcraft");
|
||||
std::fs::create_dir_all(&broken).unwrap();
|
||||
std::fs::write(broken.join("manifest.json"), b"{").unwrap();
|
||||
assert_eq!(list_recovery(&dir).len(), 1);
|
||||
sweep_orphans(&dir, std::time::Duration::ZERO);
|
||||
assert!(!partial.exists() && !broken.exists());
|
||||
assert!(dir.join("first.pcraft").is_dir());
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -1097,9 +1097,10 @@ impl<'a> Planner<'a> {
|
||||
};
|
||||
for &(i, e) in &rev {
|
||||
if let Effect::DropShadow(s) = e {
|
||||
// The layer hides the shadow beneath it where its fill is see-through.
|
||||
// The layer hides the shadow beneath it where its fill is see-through, and wholly
|
||||
// in a mode that blends with it (as the CPU renderer: `shadow_see_through`).
|
||||
let flags = if s.knocks_out { F_KNOCKOUT } else { 0 };
|
||||
let see_through = 1.0 - layer.fill_opacity.clamp(0.0, 1.0);
|
||||
let see_through = photocraft_compose::effects::shadow_see_through(layer);
|
||||
w = self.paint_k(
|
||||
w,
|
||||
content,
|
||||
|
||||
@@ -527,10 +527,17 @@ fn fit(w: u32, h: u32, v: Vec<f32>, max: u32) -> (u32, u32, Vec<f32>) {
|
||||
let k = (w.max(h) as f32 / max as f32).max(1.0);
|
||||
let (nw, nh) = (((w as f32 / k).round() as u32).clamp(1, max), ((h as f32 / k).round() as u32).clamp(1, max));
|
||||
let mut out = vec![0.0f32; nw as usize * nh as usize];
|
||||
// Source rows/columns `[i * n / m, (i + 1) * n / m)` (at least one) for output index `i` of
|
||||
// `m`; in u64, as `(i + 1) * n` passes u32 for a plane over 2^32 / `max` long. The parsers'
|
||||
// edge caps keep today's inputs below that, but this function should not depend on them.
|
||||
let span = |i: u32, n: u32, m: u32| {
|
||||
let at = |k: u32| usize::try_from(u64::from(k) * u64::from(n) / u64::from(m)).unwrap_or(usize::MAX);
|
||||
(at(i), at(i + 1).max(at(i).saturating_add(1)).min(n as usize))
|
||||
};
|
||||
for y in 0..nh {
|
||||
let (y0, y1) = ((y * h / nh) as usize, (((y + 1) * h / nh) as usize).max((y * h / nh) as usize + 1).min(h as usize));
|
||||
let (y0, y1) = span(y, h, nh);
|
||||
for x in 0..nw {
|
||||
let (x0, x1) = ((x * w / nw) as usize, (((x + 1) * w / nw) as usize).max((x * w / nw) as usize + 1).min(w as usize));
|
||||
let (x0, x1) = span(x, w, nw);
|
||||
let (mut sum, mut n) = (0.0, 0usize);
|
||||
for yy in y0..y1 {
|
||||
for xx in x0..x1 {
|
||||
@@ -593,3 +600,18 @@ fn pattern_tile(p: &PsdPattern) -> Option<GrayTile> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod fit_tests {
|
||||
use super::fit;
|
||||
|
||||
/// A tall, narrow plane: `(y + 1) * h` passes `u32::MAX` once `h` is over 2^32 / `max` rows.
|
||||
/// The ABR and pattern parsers cap edges well below that, but `fit` must not rely on it.
|
||||
#[test]
|
||||
fn fit_tall_planes_without_overflow() {
|
||||
let h = 5_000_000u32;
|
||||
let (w, nh, out) = fit(1, h, vec![1.0; h as usize], 1024);
|
||||
assert_eq!((w, nh), (1, 1024));
|
||||
assert!(out.iter().all(|v| (*v - 1.0).abs() < 1e-6), "every output row averages real input rows");
|
||||
}
|
||||
}
|
||||
@@ -106,12 +106,15 @@ fn smooth_ease(u: f32) -> f32 {
|
||||
/// Colour at `t` for sorted stops (positions in 0..1) in `m`'s space.
|
||||
fn eval(stops: &[(f32, [f32; 3])], mids: &[f32], smooth: f32, t: f32, m: Method) -> [f32; 3] {
|
||||
let n = stops.len();
|
||||
if t <= stops[0].0 {
|
||||
return stops[0].1;
|
||||
let (Some(first), Some(last)) = (stops.first(), stops.last()) else { return [0.0; 3] };
|
||||
// A lone stop (even at a NaN position, which neither test below catches) is the colour.
|
||||
if t <= first.0 || n < 2 {
|
||||
return first.1;
|
||||
}
|
||||
if t >= stops[n - 1].0 {
|
||||
return stops[n - 1].1;
|
||||
if t >= last.0 {
|
||||
return last.1;
|
||||
}
|
||||
// From here `stops[i + 1]` and the tangents' `n - 2` are in range: `i < n - 1` and `n >= 2`.
|
||||
let i = stops.windows(2).position(|w| t >= w[0].0 && t <= w[1].0).unwrap_or(0);
|
||||
let (t0, t1) = (stops[i].0, stops[i + 1].0);
|
||||
let h = (t1 - t0).max(1e-6);
|
||||
@@ -281,4 +284,14 @@ mod tests {
|
||||
let s = bake(vec![(0.0, Color::BLACK), (1.0, Color::WHITE)], &[0.25], 0.0, Method::Classic);
|
||||
assert!((at(&s, 0.25)[0] - 0.5).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// `eval` guards its own stops instead of relying on `bake`'s two-stop check.
|
||||
#[test]
|
||||
fn eval_with_fewer_than_two_stops_does_not_index_out_of_range() {
|
||||
assert_eq!(eval(&[], &[], 1.0, 0.5, Method::Smooth), [0.0; 3]);
|
||||
let lone = [(f32::NAN, [0.25, 0.5, 0.75])];
|
||||
for m in [Method::Classic, Method::Smooth] {
|
||||
assert_eq!(eval(&lone, &[], 1.0, 0.5, m), [0.25, 0.5, 0.75]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1636,6 +1636,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
|
||||
// Resources.
|
||||
let mut resources = vec![
|
||||
// hRes/vRes are always pixels per inch. The display unit written here is inches.
|
||||
ImageResource::new(ids::RESOLUTION_INFO, ResolutionInfo::from_dpi(f64::from(doc.resolution_dpi)).to_bytes()),
|
||||
ImageResource::new(ids::GLOBAL_ANGLE, (doc.global_light.angle.round() as i32).to_be_bytes().to_vec()),
|
||||
ImageResource::new(ids::GLOBAL_ALTITUDE, (doc.global_light.altitude.round() as i32).to_be_bytes().to_vec()),
|
||||
|
||||
@@ -673,8 +673,9 @@ pub fn psd_to_document_with(file: &PsdFile, ctl: &photocraft_raster::Interrupt)
|
||||
match r.id {
|
||||
ids::RESOLUTION_INFO => {
|
||||
if let Ok(ri) = photocraft_psd::ResolutionInfo::from_bytes(&r.data) {
|
||||
let ppi = |res: f64, unit: u16| if unit == 2 { res * 2.54 } else { res };
|
||||
let (x, y) = (ppi(ri.h_res(), ri.h_res_unit), ppi(ri.v_res(), ri.v_res_unit));
|
||||
// Fixed 16.16 hRes/vRes are pixels per inch. The unit shorts only
|
||||
// say how to show that number (1 = px/in, 2 = px/cm).
|
||||
let (x, y) = (ri.h_res(), ri.v_res());
|
||||
doc.resolution_dpi = x as f32;
|
||||
warnings.extend(crate::unequal_resolution_warning(x, y));
|
||||
}
|
||||
|
||||
@@ -203,3 +203,36 @@ fn merged_oracle_does_not_treat_extra_channels_as_transparency() {
|
||||
assert_eq!(merged_composite(&file).unwrap(), vec![[2.0, 2.0, 2.0, 1.0]], "{mode:?}");
|
||||
}
|
||||
}
|
||||
|
||||
// Photoshop saves a transparent 32-bit document with a positive layer count and an `Mt32`
|
||||
// ("Saving Merged Transparency") global block: the merged image's first extra channel, named
|
||||
// "Transparency", is its transparency (psd-tools transparentbg.psd). The oracle reads it as the
|
||||
// composite's alpha, and opening the file doesn't turn it into an alpha channel.
|
||||
#[test]
|
||||
fn mt32_marks_the_merged_transparency() {
|
||||
let mut doc = Document::new("transparent", Size::new(2, 1), ColorMode::Rgb, SampleType::F32);
|
||||
let fmt = doc.pixel_format();
|
||||
let mut layer = photocraft_doc::Layer::raster("shape", fmt);
|
||||
if let Some(s) = layer.surface_mut() {
|
||||
s.fill_rect(photocraft_geom::Rect::new(0, 0, 1, 1), &[0.0, 0.0, 0.0, 1.0]);
|
||||
}
|
||||
doc.layers.push(layer);
|
||||
let mut file = PsdFile::from_bytes(&export_psd(&doc)).unwrap();
|
||||
file.header.channels = 4;
|
||||
if let Some(li) = file.layer_info.as_mut() {
|
||||
li.merged_alpha = false;
|
||||
}
|
||||
file.image_data.compression = Compression::Raw;
|
||||
let plane = |v: [f32; 2]| v.into_iter().flat_map(f32::to_be_bytes).collect::<Vec<u8>>();
|
||||
file.image_data.data = [plane([0.0, 1.0]), plane([0.0, 1.0]), plane([0.0, 1.0]), plane([1.0, 0.0])].concat();
|
||||
let name: Vec<u8> = [0u8, 0, 0, 13].into_iter().chain("Transparency\0".encode_utf16().flat_map(u16::to_be_bytes)).collect();
|
||||
file.resources.retain(|r| r.id != 1045);
|
||||
file.resources.push(photocraft_psd::ImageResource::new(1045, name));
|
||||
assert!(!file.merged_has_alpha(), "a positive layer count alone");
|
||||
file.global_blocks.push(photocraft_psd::TaggedBlock::new(*b"Mt32", Vec::new()));
|
||||
assert!(file.merged_has_alpha());
|
||||
let merged = merged_composite(&file).unwrap();
|
||||
assert_eq!(merged.iter().map(|p| p[3]).collect::<Vec<_>>(), vec![1.0, 0.0]);
|
||||
let opened = import("transparent.psd", &file.to_bytes().unwrap()).unwrap();
|
||||
assert!(opened.document.channels.is_empty(), "{:?}", opened.document.channels.iter().map(|c| &c.name).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -460,13 +460,18 @@ fn guides_and_alpha_names_roundtrip() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_in_cm_converted() {
|
||||
fn resolution_info_cm_display_unit_stays_pixels_per_inch() {
|
||||
let mut f = testgen::small(Version::Psd, Compression::Raw);
|
||||
let mut ri = photocraft_psd::ResolutionInfo::from_dpi(100.0);
|
||||
let mut ri = photocraft_psd::ResolutionInfo::from_dpi(300.0);
|
||||
ri.h_res_unit = 2;
|
||||
ri.v_res_unit = 2;
|
||||
f.resources[0] = photocraft_psd::ImageResource::new(1005, ri.to_bytes());
|
||||
let (d, _) = psd_to_document(&f);
|
||||
assert!((d.resolution_dpi - 254.0).abs() < 1e-3);
|
||||
assert!((d.resolution_dpi - 300.0).abs() < 1e-3, "{}", d.resolution_dpi);
|
||||
let out = document_to_psd(&d);
|
||||
let written = out.resolution().unwrap();
|
||||
assert!((written.h_res() - 300.0).abs() < 1e-3, "{}", written.h_res());
|
||||
assert!((written.v_res() - 300.0).abs() < 1e-3, "{}", written.v_res());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -59,13 +59,27 @@ fn psd_with_equal_axes_opens_silently() {
|
||||
let r = import("x.psd", &psd(ResolutionInfo::from_dpi(300.0))).unwrap();
|
||||
assert!((r.document.resolution_dpi - 300.0).abs() < 1e-3, "{}", r.document.resolution_dpi);
|
||||
assert!(resolution_notes(&r).is_empty(), "{:?}", r.warnings);
|
||||
// Each axis is read in its own unit: 100 pixels per centimetre on both is 254 ppi on both.
|
||||
let mut cm = ResolutionInfo::from_dpi(100.0);
|
||||
}
|
||||
|
||||
/// Resource 1005 stores 300 ppi even when the display unit is centimetres. Scaling
|
||||
/// that fixed-point value by 2.54 opened the file at 762 ppi (#5201).
|
||||
#[test]
|
||||
fn resolution_info_cm_display_unit_is_pixels_per_inch() {
|
||||
let mut cm = ResolutionInfo::from_dpi(300.0);
|
||||
cm.h_res_unit = 2;
|
||||
cm.v_res_unit = 2;
|
||||
cm.width_unit = 2;
|
||||
cm.height_unit = 2;
|
||||
let r = import("x.psd", &psd(cm)).unwrap();
|
||||
assert!((r.document.resolution_dpi - 254.0).abs() < 1e-3, "{}", r.document.resolution_dpi);
|
||||
assert!((r.document.resolution_dpi - 300.0).abs() < 1e-3, "{}", r.document.resolution_dpi);
|
||||
assert!(resolution_notes(&r).is_empty(), "{:?}", r.warnings);
|
||||
|
||||
let out = export(&r.document, "out.psd", &ExportOptions::default()).unwrap();
|
||||
let file = photocraft_psd::PsdFile::from_bytes(&out.bytes).unwrap();
|
||||
let written = file.resolution().unwrap();
|
||||
assert!((written.h_res() - 300.0).abs() < 1e-3, "{}", written.h_res());
|
||||
assert!((written.v_res() - 300.0).abs() < 1e-3, "{}", written.v_res());
|
||||
assert_eq!((written.h_res_unit, written.v_res_unit), (1, 1));
|
||||
}
|
||||
|
||||
/// A layered TIFF opens through the PSD importer with the TIFF's own resolution tags.
|
||||
|
||||
@@ -272,7 +272,10 @@ impl PsdFile {
|
||||
self.image_data.decode(&self.header)
|
||||
}
|
||||
|
||||
/// `true` if the merged image carries a transparency channel.
|
||||
/// `true` if the merged image carries a transparency channel: its first extra channel, when
|
||||
/// the layer count was stored negative or a "Saving Merged Transparency" global block (`Mtrn`,
|
||||
/// `Mt16`, `Mt32`) is present. Photoshop marks 32-bit documents with `Mt32` and a positive
|
||||
/// layer count (psd-tools transparentbg.psd).
|
||||
pub fn merged_has_alpha(&self) -> bool {
|
||||
let Some(color) = self.header.color_mode.color_channels() else {
|
||||
return false;
|
||||
@@ -280,8 +283,9 @@ impl PsdFile {
|
||||
if self.header.channels <= color {
|
||||
return false;
|
||||
}
|
||||
let marked = self.global_blocks.iter().any(|b| matches!(&b.key, b"Mtrn" | b"Mt16" | b"Mt32"));
|
||||
match &self.layer_info {
|
||||
Some(li) => li.merged_alpha,
|
||||
Some(li) => li.merged_alpha || marked,
|
||||
None => true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,20 +45,24 @@ pub struct ImageResource {
|
||||
}
|
||||
|
||||
/// Fixed-point resolution info (resource 1005).
|
||||
///
|
||||
/// `h_res_fixed` and `v_res_fixed` are always pixels per inch (16.16 fixed).
|
||||
/// `h_res_unit` and `v_res_unit` only say how to display that number
|
||||
/// (1 = pixels/inch, 2 = pixels/cm) and do not rescale the stored value.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub struct ResolutionInfo {
|
||||
/// Horizontal resolution, 16.16 fixed point (pixels per inch/cm).
|
||||
/// Horizontal resolution, 16.16 fixed point, always pixels per inch.
|
||||
pub h_res_fixed: u32,
|
||||
/// 1 = pixels per inch, 2 = pixels per cm.
|
||||
/// Display unit for the horizontal resolution (1 = px/in, 2 = px/cm).
|
||||
pub h_res_unit: u16,
|
||||
/// Display unit for width (1 in, 2 cm, 3 pt, 4 pica, 5 column).
|
||||
/// Ruler unit for width (1 in, 2 cm, 3 pt, 4 pica, 5 column).
|
||||
pub width_unit: u16,
|
||||
/// Vertical resolution, 16.16 fixed.
|
||||
/// Vertical resolution, 16.16 fixed point, always pixels per inch.
|
||||
pub v_res_fixed: u32,
|
||||
/// Vertical resolution unit.
|
||||
/// Display unit for the vertical resolution (1 = px/in, 2 = px/cm).
|
||||
pub v_res_unit: u16,
|
||||
/// Display unit for height.
|
||||
/// Ruler unit for height (1 in, 2 cm, 3 pt, 4 pica, 5 column).
|
||||
pub height_unit: u16,
|
||||
}
|
||||
|
||||
@@ -68,11 +72,11 @@ impl ResolutionInfo {
|
||||
let f = (dpi * 65536.0).round().clamp(0.0, u32::MAX as f64) as u32;
|
||||
ResolutionInfo { h_res_fixed: f, h_res_unit: 1, width_unit: 1, v_res_fixed: f, v_res_unit: 1, height_unit: 1 }
|
||||
}
|
||||
/// Horizontal resolution as float.
|
||||
/// Horizontal resolution in pixels per inch.
|
||||
pub fn h_res(&self) -> f64 {
|
||||
f64::from(self.h_res_fixed) / 65536.0
|
||||
}
|
||||
/// Vertical resolution as float.
|
||||
/// Vertical resolution in pixels per inch.
|
||||
pub fn v_res(&self) -> f64 {
|
||||
f64::from(self.v_res_fixed) / 65536.0
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ license.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-print = { workspace = true }
|
||||
craft-ui = { workspace = true }
|
||||
photocraft-geom = { workspace = true }
|
||||
photocraft-color = { workspace = true }
|
||||
|
||||
@@ -697,10 +697,12 @@ fn feed_live_stroke(app: &mut PhotocraftApp) {
|
||||
return;
|
||||
}
|
||||
l.fed = d.points.len();
|
||||
let started = crate::gpu_canvas::now_ms();
|
||||
match l.stroke.push(&pts) {
|
||||
Ok(r) => l.damage.push(r),
|
||||
Err(_) => app.live_stroke = None,
|
||||
}
|
||||
app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started);
|
||||
}
|
||||
|
||||
/// The points the live retouching stroke has rendered.
|
||||
@@ -5460,7 +5462,9 @@ fn commit_brush_stroke(app: &mut PhotocraftApp, d: &Drag) {
|
||||
{
|
||||
app.session.clear_live_stroke();
|
||||
}
|
||||
let started = crate::gpu_canvas::now_ms();
|
||||
let result = app.run(stroke_command(app, d.tool), p);
|
||||
app.stroke_trace.stroke(crate::gpu_canvas::now_ms() - started);
|
||||
app.session.clear_live_stroke();
|
||||
let Ok(r) = result else { return };
|
||||
let revision = app.session.documents().iter().find(|st| st.doc.id == doc).map(|st| st.revision);
|
||||
|
||||
@@ -1315,7 +1315,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
|
||||
"frame": app.frame,
|
||||
"session": photocraft_engine::inspect::session(&app.session),
|
||||
"document": app.session.active().map(photocraft_engine::inspect::document),
|
||||
"perf": {"fps": app.fps, "timings": app.perf},
|
||||
"perf": {"fps": app.fps, "timings": app.perf, "strokeTrace": app.stroke_trace.last},
|
||||
"brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity},
|
||||
"distort": app.distort.describe(),
|
||||
"jobs": crate::jobs_ui::inspect(app),
|
||||
|
||||
+106
-13
@@ -726,7 +726,7 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
f.insert("__label".into(), json!("PhotoCraft Print Settings"));
|
||||
// Asked once per opening: the Printer menu lists what the spooler knows now.
|
||||
let printers = app.session.execute("file.printers", json!({})).unwrap_or_default();
|
||||
f.insert("__printers".into(), printers["printers"].clone());
|
||||
f.insert("__systemPrinters".into(), printers["printers"].clone());
|
||||
if let Some(Value::Object(m)) = app.session.file_menu.last_print.clone() {
|
||||
f.extend(m);
|
||||
}
|
||||
@@ -755,9 +755,35 @@ pub fn open_print(app: &mut PhotocraftApp) -> u64 {
|
||||
] {
|
||||
f.entry(k.to_string()).or_insert(v);
|
||||
}
|
||||
// Windows: the system's printers, and the paper from the chosen printer's driver settings.
|
||||
if let Ok(list) = craft_print::rgb::printers() {
|
||||
f.insert("__printers".into(), json!(list.iter().map(|p| p.name.clone()).collect::<Vec<_>>()));
|
||||
let known = |n: &str| list.iter().any(|p| p.name == n);
|
||||
if !known(&s(&f, "printer", "")) {
|
||||
let fallback = list.iter().find(|p| p.default).or(list.first()).map(|p| p.name.clone()).unwrap_or_default();
|
||||
f.insert("printer".into(), json!(fallback));
|
||||
f.remove("printerSettings");
|
||||
}
|
||||
}
|
||||
app.ui.open_dialog(DialogKind::Command, f)
|
||||
}
|
||||
|
||||
/// Takes the paper from the printer's driver settings (Windows), as Photoshop does.
|
||||
fn driver_page(f: &mut Map<String, Value>) {
|
||||
let printer = s(f, "printer", "");
|
||||
let settings = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok());
|
||||
match craft_print::rgb::page(&printer, settings.as_ref()) {
|
||||
Ok(pg) => {
|
||||
f.insert("paper".into(), json!([pg.paper.0, pg.paper.1]));
|
||||
f.insert("orientation".into(), json!("portrait"));
|
||||
f.remove("__pageError");
|
||||
}
|
||||
Err(e) => {
|
||||
f.insert("__pageError".into(), json!(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Points per unit for the Position and Size fields.
|
||||
fn unit_pt(units: &str) -> f64 {
|
||||
match units {
|
||||
@@ -839,6 +865,22 @@ fn print_paper_controls(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some(doc) = app.session.active().map(|d| d.doc.clone()) else { return };
|
||||
// PDF exports and previews retain editable paper on Windows too. Only a real native
|
||||
// submission takes its media from the printer; entering that mode refreshes the driver
|
||||
// geometry after any export-only paper edits.
|
||||
let printers: Option<Vec<String>> = if !b(f, "dryRun", false) && s(f, "output", "").is_empty() {
|
||||
f.get("__printers").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if printers.is_some() {
|
||||
if !b(f, "__driverPageInitialized", false) {
|
||||
driver_page(f);
|
||||
f.insert("__driverPageInitialized".into(), json!(true));
|
||||
}
|
||||
} else {
|
||||
f.remove("__driverPageInitialized");
|
||||
}
|
||||
let p = params(f);
|
||||
ui.horizontal_top(|ui| {
|
||||
// Page preview.
|
||||
@@ -915,17 +957,57 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
ui.label(egui::RichText::new(s).font(crate::theme::semibold(12.0)).color(t.text));
|
||||
};
|
||||
head(ui, tl!("Printer Setup"));
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim));
|
||||
let mut pr = s(f, "printer", "");
|
||||
let opts = printer_options(f.get("__printers"), &pr);
|
||||
let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.clone(), l.as_str())).collect();
|
||||
if crate::widgets::dropdown(ui, "print-printer", &mut pr, &o, 240.0) {
|
||||
f.insert("printer".into(), json!(pr));
|
||||
if let Some(printers) = &printers {
|
||||
// Windows: Photoshop's Printer menu and Print Settings… (the driver's own dialog).
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim));
|
||||
let before = s(f, "printer", "");
|
||||
let opts: Vec<(&str, &str)> = printers.iter().map(|n| (n.as_str(), n.as_str())).collect();
|
||||
dropdown_str(ui, "print-printer", f, "printer", &opts, 220.0);
|
||||
if s(f, "printer", "") != before {
|
||||
f.remove("printerSettings");
|
||||
driver_page(f);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0);
|
||||
if ui.button(tl!("Print Settings…")).clicked() {
|
||||
let printer = s(f, "printer", "");
|
||||
let current = f.get("printerSettings").and_then(Value::as_str).and_then(|h| craft_print::rgb::DevMode::from_hex(h).ok());
|
||||
match craft_print::rgb::settings_dialog(&printer, current.as_ref(), None) {
|
||||
Ok(Some(dm)) => {
|
||||
f.insert("printerSettings".into(), json!(dm.to_hex()));
|
||||
driver_page(f);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => {
|
||||
f.insert("__pageError".into(), json!(e.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let paper = p.get("paper").and_then(Value::as_array).map(|a| (a.first().and_then(Value::as_f64), a.get(1).and_then(Value::as_f64)));
|
||||
let text = match paper {
|
||||
Some((Some(w), Some(h))) => format!("{:.0} × {:.0} mm · {}", w / 72.0 * 25.4, h / 72.0 * 25.4, tl!("set in Print Settings…")),
|
||||
_ => String::new(),
|
||||
};
|
||||
ui.label(egui::RichText::new(text).color(t.text_dim).size(11.0));
|
||||
if let Some(e) = f.get("__pageError").and_then(Value::as_str) {
|
||||
ui.label(egui::RichText::new(e).color(t.warning).size(11.0));
|
||||
}
|
||||
});
|
||||
number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0);
|
||||
print_paper_controls(ui, f);
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Printer")).color(t.text_dim));
|
||||
let mut pr = s(f, "printer", "");
|
||||
let opts = printer_options(f.get("__systemPrinters"), &pr);
|
||||
let o: Vec<(String, &str)> = opts.iter().map(|(k, l)| (k.clone(), l.as_str())).collect();
|
||||
if crate::widgets::dropdown(ui, "print-printer", &mut pr, &o, 240.0) {
|
||||
f.insert("printer".into(), json!(pr));
|
||||
}
|
||||
});
|
||||
number(ui, f, "copies", tl!("Copies"), 1.0..=999.0, "", 1.0);
|
||||
print_paper_controls(ui, f);
|
||||
}
|
||||
head(ui, tl!("Color Management"));
|
||||
dropdown_str(
|
||||
ui,
|
||||
@@ -977,6 +1059,11 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
);
|
||||
check(ui, f, "bpc", tl!("Black Point Compensation"), true);
|
||||
});
|
||||
if printers.is_some() {
|
||||
ui.label(
|
||||
egui::RichText::new(tl!("Remember to turn off the printer's own colour management in Print Settings…")).color(t.warning).size(11.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
head(ui, tl!("Position and Size"));
|
||||
dropdown_str(ui, "print-units", f, "units", &[("cm", tl!("Centimeters")), ("mm", tl!("Millimeters")), ("in", tl!("Inches"))], 130.0);
|
||||
@@ -1040,6 +1127,9 @@ fn print_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Va
|
||||
});
|
||||
head(ui, tl!("Functions"));
|
||||
check(ui, f, "emulsionDown", tl!("Emulsion Down"), false);
|
||||
if b(f, "emulsionDown", false) && printers.is_some() {
|
||||
ui.label(egui::RichText::new(tl!("Don't also tick Mirror Image in Print Settings…: the two flips cancel out.")).color(t.text_dim).size(11.0));
|
||||
}
|
||||
head(ui, tl!("Save as PDF"));
|
||||
let mut out = s(f, "output", "");
|
||||
if ui.add(egui::TextEdit::singleline(&mut out).hint_text(tl!("(print to the printer)")).desired_width(300.0)).changed() {
|
||||
@@ -1058,7 +1148,9 @@ fn print_confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Valu
|
||||
}
|
||||
|
||||
pub(crate) fn print_status(app: &mut PhotocraftApp, r: &Value) {
|
||||
app.ui.status = if r["sent"] == json!(true) {
|
||||
app.ui.status = if let Some(printer) = r["spooler"]["printer"].as_str() {
|
||||
crate::i18n::fmt(tl!("Sent to {printer}"), &[("printer", printer)])
|
||||
} else if r["sent"] == json!(true) {
|
||||
let template = "Sent to the printer ({spooler})";
|
||||
crate::i18n::fmt(tl!(template), &[("spooler", r["spooler"].as_str().unwrap_or(""))])
|
||||
} else {
|
||||
@@ -1353,7 +1445,8 @@ mod tests {
|
||||
let (mut app, ctx) = app();
|
||||
let id = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
let f = &app.ui.dialog_mut(id).unwrap().fields;
|
||||
assert!(f.get("__printers").is_some_and(Value::is_array));
|
||||
assert!(f.get("__systemPrinters").is_some_and(Value::is_array));
|
||||
assert!(params(f).get("__systemPrinters").is_none());
|
||||
assert!(params(f).get("__printers").is_none());
|
||||
}
|
||||
|
||||
|
||||
@@ -898,6 +898,9 @@ pub struct Perf {
|
||||
pub spans: std::collections::BTreeMap<&'static str, f64>,
|
||||
#[serde(skip)]
|
||||
max_decay: f64,
|
||||
/// Composite and upload time of this frame's canvas refreshes, in ms (the stroke trace).
|
||||
#[serde(skip)]
|
||||
pub(crate) frame_refresh_ms: f64,
|
||||
}
|
||||
|
||||
/// What the app renders with and why (Help › System Info, Preferences › Performance, the `perf`
|
||||
@@ -1012,6 +1015,7 @@ pub fn backend_name(b: wgpu::Backend) -> &'static str {
|
||||
|
||||
impl Perf {
|
||||
pub fn record(&mut self, kind: &'static str, px: u64, composite_ms: f64, upload_ms: f64) {
|
||||
self.frame_refresh_ms += composite_ms + upload_ms;
|
||||
self.last_refresh = kind;
|
||||
self.last_refresh_px = px;
|
||||
self.composite_ms = composite_ms;
|
||||
|
||||
@@ -3744,4 +3744,11 @@ navigator Zoom Zvětšení
|
||||
Step {step} is waiting for its dialog Krok {step} čeká na svůj dialog
|
||||
@plural {n} action|{n} actions {n} akce|{n} akce|{n} akcí
|
||||
Auto Add/Delete Automaticky přidat/odstranit
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nezapínejte současně zrcadlení v nastavení tisku: obě převrácení se navzájem zruší.
|
||||
Print Settings… Nastavení tisku…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Nezapomeňte v nastavení tisku vypnout vlastní správu barev tiskárny…
|
||||
Sent to {printer} Odesláno do {printer}
|
||||
set in Print Settings… nastavuje se v nastavení tisku…
|
||||
ICO is limited to 256 × 256 pixels ICO je omezen na 256 × 256 pixelů
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3134,4 +3134,11 @@ curves Smooth Glätten
|
||||
Step {step} is waiting for its dialog Schritt {step} wartet auf seinen Dialog
|
||||
@plural {n} action|{n} actions {n} Aktion|{n} Aktionen
|
||||
Auto Add/Delete Autom. hinzuf./löschen
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Aktiviere nicht zusätzlich das Spiegelbild in den Druckeinstellungen: Die beiden Spiegelungen heben sich auf.
|
||||
Print Settings… Druckeinstellungen…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Denke daran, die eigene Farbverwaltung des Druckers in den Druckeinstellungen auszuschalten…
|
||||
Sent to {printer} An {printer} gesendet
|
||||
set in Print Settings… in den Druckeinstellungen festlegen…
|
||||
ICO is limited to 256 × 256 pixels ICO ist auf 256 × 256 Pixel begrenzt
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3834,4 +3834,11 @@ curves Smooth Εξομάλυνση
|
||||
Step {step} is waiting for its dialog Το βήμα {step} περιμένει το παράθυρο διαλόγου του
|
||||
@plural {n} action|{n} actions {n} ενέργεια|{n} ενέργειες
|
||||
Auto Add/Delete Αυτόματη προσθήκη/διαγραφή
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Μην ενεργοποιείτε επίσης τον κατοπτρισμό στις ρυθμίσεις εκτύπωσης: οι δύο αναστροφές αλληλοαναιρούνται.
|
||||
Print Settings… Ρυθμίσεις εκτύπωσης…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Θυμηθείτε να απενεργοποιήσετε τη διαχείριση χρωμάτων του εκτυπωτή στις ρυθμίσεις εκτύπωσης…
|
||||
Sent to {printer} Στάλθηκε στον {printer}
|
||||
set in Print Settings… ορίζεται στις ρυθμίσεις εκτύπωσης…
|
||||
ICO is limited to 256 × 256 pixels Το ICO περιορίζεται σε 256 × 256 εικονοστοιχεία
|
||||
|
Can't render this file because it contains an unexpected character in line 1029 and column 18.
|
@@ -2821,4 +2821,11 @@ curves Smooth Suavizar
|
||||
Step {step} is waiting for its dialog El paso {step} está esperando su cuadro de diálogo
|
||||
@plural {n} action|{n} actions {n} acción|{n} acciones
|
||||
Auto Add/Delete Añadir/eliminar automáticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. No actives también Imagen especular en Ajustes de impresión: las dos inversiones se anulan.
|
||||
Print Settings… Ajustes de impresión…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Recuerda desactivar la gestión de color de la impresora en Ajustes de impresión…
|
||||
Sent to {printer} Enviado a {printer}
|
||||
set in Print Settings… se establece en Ajustes de impresión…
|
||||
ICO is limited to 256 × 256 pixels ICO está limitado a 256 × 256 píxeles
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -3138,4 +3138,11 @@ curves Smooth Lisser
|
||||
Step {step} is waiting for its dialog L’étape {step} attend sa boîte de dialogue
|
||||
@plural {n} action|{n} actions {n} action|{n} actions
|
||||
Auto Add/Delete Ajout/suppr. auto
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Ne cochez pas aussi Image miroir dans les paramètres d’impression : les deux inversions s’annulent.
|
||||
Print Settings… Paramètres d’impression…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Pensez à désactiver la gestion des couleurs de l’imprimante dans les paramètres d’impression…
|
||||
Sent to {printer} Envoyé à {printer}
|
||||
set in Print Settings… défini dans les paramètres d’impression…
|
||||
ICO is limited to 256 × 256 pixels Le format ICO est limité à 256 × 256 pixels
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -4050,6 +4050,13 @@ cameraRaw Yellow Sárga
|
||||
Loaded Camera Raw settings from {file} Camera Raw-beállítások betöltve innen: {file}
|
||||
Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-beállítások betöltve innen: {file} ({n} nem támogatott)
|
||||
Auto Add/Delete Automatikus hozzáadás/törlés
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. A nyomtatási beállításokban ne jelöld be a tükrözést is: a két tükrözés kioltja egymást.
|
||||
Print Settings… Nyomtatási beállítások…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Ne felejtsd el kikapcsolni a nyomtató saját színkezelését a nyomtatási beállításokban…
|
||||
Sent to {printer} Elküldve ide: {printer}
|
||||
set in Print Settings… a nyomtatási beállításokban adható meg…
|
||||
ICO is limited to 256 × 256 pixels Az ICO legfeljebb 256 × 256 képpont lehet
|
||||
|
||||
# Channel Options and New Spot Channel (#3761)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3125,4 +3125,11 @@ curves Smooth Haluskan
|
||||
Step {step} is waiting for its dialog Langkah {step} menunggu dialognya
|
||||
@plural {n} action|{n} actions {n} tindakan
|
||||
Auto Add/Delete Tambah/Hapus Otomatis
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Jangan aktifkan juga Gambar Cermin di Pengaturan Cetak: kedua pembalikan saling meniadakan.
|
||||
Print Settings… Pengaturan Cetak…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Ingat untuk menonaktifkan pengelolaan warna milik printer di Pengaturan Cetak…
|
||||
Sent to {printer} Dikirim ke {printer}
|
||||
set in Print Settings… diatur di Pengaturan Cetak…
|
||||
ICO is limited to 256 × 256 pixels ICO dibatasi hingga 256 × 256 piksel
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -4099,4 +4099,11 @@ navigator Zoom Zoom
|
||||
Step {step} is waiting for its dialog Il passaggio {step} attende la sua finestra di dialogo
|
||||
@plural {n} action|{n} actions {n} azione|{n} azioni
|
||||
Auto Add/Delete Aggiungi/elimina automaticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Non attivare anche Immagine speculare nelle impostazioni di stampa: le due inversioni si annullano.
|
||||
Print Settings… Impostazioni di stampa…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Ricorda di disattivare la gestione del colore della stampante nelle impostazioni di stampa…
|
||||
Sent to {printer} Inviato a {printer}
|
||||
set in Print Settings… impostato nelle impostazioni di stampa…
|
||||
ICO is limited to 256 × 256 pixels ICO è limitato a 256 × 256 pixel
|
||||
|
Can't render this file because it contains an unexpected character in line 2647 and column 53.
|
@@ -3809,6 +3809,12 @@ curves Smooth スムーズ
|
||||
Vector Mask Hides Effects ベクトルマスクで効果を隠す
|
||||
Auto Add/Delete 自動追加・削除
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 印刷設定の「鏡像」も有効にしないでください。2回反転すると元に戻ります。
|
||||
Print Settings… 印刷設定…
|
||||
Remember to turn off the printer's own colour management in Print Settings… 印刷設定でプリンター独自のカラーマネジメントを無効にしてください…
|
||||
Sent to {printer} {printer} に送信しました
|
||||
set in Print Settings… 印刷設定で指定…
|
||||
# Restored rows (custom print paper #3820, brush presets, Vanishing Point help, brush panel menu)
|
||||
Drag to pan · Scroll to zoom · Double-click to fit ドラッグで移動 · スクロールでズーム · ダブルクリックで全体表示
|
||||
Clear Brush Controls ブラシのコントロールを消去
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3311,4 +3311,11 @@ curves Smooth 매끄럽게
|
||||
Step {step} is waiting for its dialog {step}단계가 대화 상자를 기다리고 있습니다
|
||||
@plural {n} action|{n} actions 액션 {n}개
|
||||
Auto Add/Delete 자동 추가/삭제
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 인쇄 설정에서도 이미지 반전을 켜지 마세요. 두 번 반전하면 원래대로 돌아갑니다.
|
||||
Print Settings… 인쇄 설정…
|
||||
Remember to turn off the printer's own colour management in Print Settings… 인쇄 설정에서 프린터 자체의 색상 관리를 끄세요…
|
||||
Sent to {printer} {printer}(으)로 전송됨
|
||||
set in Print Settings… 인쇄 설정에서 지정…
|
||||
ICO is limited to 256 × 256 pixels ICO는 256 × 256픽셀로 제한됩니다
|
||||
|
Can't render this file because it contains an unexpected character in line 3160 and column 53.
|
@@ -3896,4 +3896,11 @@ curves Smooth Vloeiend maken
|
||||
Step {step} is waiting for its dialog Stap {step} wacht op zijn dialoogvenster
|
||||
@plural {n} action|{n} actions {n} handeling|{n} handelingen
|
||||
Auto Add/Delete Automatisch toevoegen/verwijderen
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Schakel niet ook Spiegelbeeld in bij de afdrukinstellingen: de twee spiegelingen heffen elkaar op.
|
||||
Print Settings… Afdrukinstellingen…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Vergeet niet het eigen kleurbeheer van de printer uit te schakelen in de afdrukinstellingen…
|
||||
Sent to {printer} Verzonden naar {printer}
|
||||
set in Print Settings… instellen in de afdrukinstellingen…
|
||||
ICO is limited to 256 × 256 pixels ICO is beperkt tot 256 × 256 pixels
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3734,4 +3734,11 @@ curves Smooth Wygładź
|
||||
Step {step} is waiting for its dialog Krok {step} czeka na swoje okno dialogowe
|
||||
@plural {n} action|{n} actions {n} operacja|{n} operacje|{n} operacji
|
||||
Auto Add/Delete Automatyczne dodawanie/usuwanie
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nie włączaj też odbicia lustrzanego w ustawieniach druku: oba odbicia wzajemnie się znoszą.
|
||||
Print Settings… Ustawienia druku…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Pamiętaj o wyłączeniu zarządzania kolorami drukarki w ustawieniach druku…
|
||||
Sent to {printer} Wysłano do {printer}
|
||||
set in Print Settings… ustawiane w ustawieniach druku…
|
||||
ICO is limited to 256 × 256 pixels ICO jest ograniczony do 256 × 256 pikseli
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3926,4 +3926,11 @@ layerLabel No Color Sem cor
|
||||
Step {step} is waiting for its dialog A etapa {step} está aguardando sua caixa de diálogo
|
||||
@plural {n} action|{n} actions {n} ação|{n} ações
|
||||
Auto Add/Delete Adicionar/excluir automaticamente
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Não ative também a imagem espelhada nas configurações de impressão: as duas inversões se anulam.
|
||||
Print Settings… Configurações de impressão…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Lembre-se de desativar o gerenciamento de cores da própria impressora nas configurações de impressão…
|
||||
Sent to {printer} Enviado para {printer}
|
||||
set in Print Settings… definido nas configurações de impressão…
|
||||
ICO is limited to 256 × 256 pixels ICO é limitado a 256 × 256 pixels
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3082,6 +3082,13 @@ curves Smooth Сгладить
|
||||
Step {step} is waiting for its dialog Шаг {step} ожидает своего диалога
|
||||
@plural {n} action|{n} actions {n} операция|{n} операции|{n} операций
|
||||
Auto Add/Delete Автодобавление/удаление
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не включайте также зеркальное отражение в параметрах печати: два отражения отменяют друг друга.
|
||||
Print Settings… Параметры печати…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Не забудьте отключить управление цветом самого принтера в параметрах печати…
|
||||
Sent to {printer} Отправлено на {printer}
|
||||
set in Print Settings… задаётся в параметрах печати…
|
||||
ICO is limited to 256 × 256 pixels ICO ограничен размером 256 × 256 пикселей
|
||||
|
||||
# Dynamic selection context menu and appearance favorites
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -4200,9 +4200,17 @@ shape Appearance Izgled
|
||||
Choose a gradient file (.grd). Izaberite datoteku gradijenta (.grd).
|
||||
Auto Add/Delete Automatsko dodavanje/brisanje
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Nemojte uključiti i ogledalsku sliku u podešavanjima štampanja: dva preslikavanja se poništavaju.
|
||||
Print Settings… Podešavanja štampanja…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Ne zaboravite da isključite upravljanje bojama samog štampača u podešavanjima štampanja…
|
||||
Sent to {printer} Poslato na {printer}
|
||||
set in Print Settings… podešava se u podešavanjima štampanja…
|
||||
# Custom print paper (#3820)
|
||||
Paper Width Širina papira
|
||||
Paper Height Visina papira
|
||||
|
||||
# ICO dimensions
|
||||
ICO is limited to 256 × 256 pixels ICO je ograničen na 256 × 256 piksela
|
||||
|
||||
# Channel Options and New Spot Channel (#3761)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -3861,6 +3861,13 @@ cameraData Lens Lens
|
||||
Loaded Camera Raw settings from {file} Camera Raw ayarları {file} dosyasından yüklendi
|
||||
Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw ayarları {file} dosyasından yüklendi ({n} desteklenmiyor)
|
||||
Auto Add/Delete Otomatik Ekle/Sil
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Yazdırma Ayarlarında ayrıca Ayna Görüntüsünü açmayın: iki yansıtma birbirini iptal eder.
|
||||
Print Settings… Yazdırma Ayarları…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Yazdırma Ayarlarında yazıcının kendi renk yönetimini kapatmayı unutmayın…
|
||||
Sent to {printer} {printer} yazıcısına gönderildi
|
||||
set in Print Settings… Yazdırma Ayarlarında belirlenir…
|
||||
ICO is limited to 256 × 256 pixels ICO 256 × 256 piksel ile sınırlıdır
|
||||
|
||||
# Channel Options and New Spot Channel (#3761)
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -3835,4 +3835,11 @@ curves Smooth Згладити
|
||||
Step {step} is waiting for its dialog Крок {step} очікує на свій діалог
|
||||
@plural {n} action|{n} actions {n} операція|{n} операції|{n} операцій
|
||||
Auto Add/Delete Автододавання/видалення
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Не вмикайте також дзеркальне відображення в параметрах друку: два відображення скасовують одне одного.
|
||||
Print Settings… Параметри друку…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Не забудьте вимкнути керування кольором самого принтера в параметрах друку…
|
||||
Sent to {printer} Надіслано на {printer}
|
||||
set in Print Settings… задається в параметрах друку…
|
||||
ICO is limited to 256 × 256 pixels ICO обмежено розміром 256 × 256 пікселів
|
||||
|
Can't render this file because it contains an unexpected character in line 1387 and column 18.
|
@@ -3623,4 +3623,11 @@ curves Smooth Làm mượt
|
||||
Import .GRD Nhập .GRD
|
||||
Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd).
|
||||
Auto Add/Delete Tự động thêm/xóa
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. Đừng bật thêm Ảnh phản chiếu trong thiết lập in: hai lần lật sẽ triệt tiêu nhau.
|
||||
Print Settings… Thiết lập in…
|
||||
Remember to turn off the printer's own colour management in Print Settings… Nhớ tắt quản lý màu riêng của máy in trong thiết lập in…
|
||||
Sent to {printer} Đã gửi tới {printer}
|
||||
set in Print Settings… đặt trong thiết lập in…
|
||||
ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2746,4 +2746,11 @@ curves Smooth 平滑
|
||||
Step {step} is waiting for its dialog 步骤 {step} 正在等待其对话框
|
||||
@plural {n} action|{n} actions {n} 个动作
|
||||
Auto Add/Delete 自动添加/删除
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 不要同时勾选打印设置中的镜像:两次翻转会相互抵消。
|
||||
Print Settings… 打印设置…
|
||||
Remember to turn off the printer's own colour management in Print Settings… 请记得在打印设置中关闭打印机自身的色彩管理…
|
||||
Sent to {printer} 已发送到 {printer}
|
||||
set in Print Settings… 在打印设置中设置…
|
||||
ICO is limited to 256 × 256 pixels ICO 最大为 256 × 256 像素
|
||||
|
Can't render this file because it contains an unexpected character in line 2593 and column 53.
|
@@ -2731,4 +2731,11 @@ curves Smooth 平滑
|
||||
Step {step} is waiting for its dialog 步驟 {step} 正在等待其對話框
|
||||
@plural {n} action|{n} actions {n} 個動作
|
||||
Auto Add/Delete 自動增加/刪除
|
||||
|
||||
# Native Windows printing qualification
|
||||
Don't also tick Mirror Image in Print Settings…: the two flips cancel out. 請勿同時勾選列印設定中的鏡像:兩次翻轉會互相抵消。
|
||||
Print Settings… 列印設定…
|
||||
Remember to turn off the printer's own colour management in Print Settings… 請記得在列印設定中關閉印表機本身的色彩管理…
|
||||
Sent to {printer} 已傳送至 {printer}
|
||||
set in Print Settings… 在列印設定中設定…
|
||||
ICO is limited to 256 × 256 pixels ICO 最大為 256 × 256 像素
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -163,7 +163,7 @@ fn stale_targets_and_invalid_colors_never_apply_or_leave_preview() {
|
||||
app.ui.dialog_mut(picker).unwrap().fields.insert(TARGET.into(), json!(null));
|
||||
}
|
||||
_ => {
|
||||
app.ui.dialog_mut(parent).unwrap().fields.insert("layer".into(), json!(999999));
|
||||
app.ui.dialog_mut(parent).unwrap().fields.insert("layer".into(), json!(u64::MAX));
|
||||
}
|
||||
}
|
||||
let current_parent = app.ui.dialogs.iter().find(|d| d.id == parent).cloned();
|
||||
|
||||
@@ -190,6 +190,7 @@ pub mod spring_tools;
|
||||
pub mod stack_dialog;
|
||||
pub mod state;
|
||||
pub mod stroke_constraint;
|
||||
pub mod stroke_trace;
|
||||
pub mod stroke_trail;
|
||||
pub mod stroke_ui;
|
||||
pub mod stylus;
|
||||
@@ -730,6 +731,8 @@ pub struct PhotocraftApp {
|
||||
started: Option<gpu_status::StartedHook>,
|
||||
/// Frame and canvas-upload timings (exposed via `ui.inspect`).
|
||||
pub perf: gpu_canvas::Perf,
|
||||
/// Per-frame stroke timings for latency reports (`PHOTOCRAFT_STROKE_TRACE`, see `stroke_trace`).
|
||||
pub stroke_trace: stroke_trace::StrokeTrace,
|
||||
/// Preferences, autosave and snapping runtime state (see `prefs_ui`, `snap_ui`).
|
||||
pub(crate) prefs_rt: prefs_ui::Runtime,
|
||||
/// Close, Revert or Exit parked behind the unsaved-changes prompt (see `discard_ui`).
|
||||
@@ -875,6 +878,7 @@ impl PhotocraftApp {
|
||||
gpu: None,
|
||||
started: None,
|
||||
perf: Default::default(),
|
||||
stroke_trace: stroke_trace::StrokeTrace::from_env(),
|
||||
prefs_rt: Default::default(),
|
||||
discard: None,
|
||||
file_dialog: None,
|
||||
@@ -1756,6 +1760,7 @@ impl eframe::App for PhotocraftApp {
|
||||
}
|
||||
|
||||
fn raw_input_hook(&mut self, ctx: &egui::Context, raw_input: &mut egui::RawInput) {
|
||||
let frame_start = gpu_canvas::now_ms();
|
||||
// An undecorated window gets its caption back when the toolkit changes its flags
|
||||
// (maximize, restore, …): take it off again before the frame is laid out (#2246).
|
||||
if let Some(window_frame) = self.services.window_frame.as_mut() {
|
||||
@@ -1779,6 +1784,11 @@ impl eframe::App for PhotocraftApp {
|
||||
if self.custom_titlebar {
|
||||
titlebar::release_after_os_resize(ctx, raw_input);
|
||||
}
|
||||
if self.stroke_trace.enabled() {
|
||||
// The OS's moves and the control channel's (injected just above).
|
||||
let moves = raw_input.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count();
|
||||
self.stroke_trace.begin_frame(frame_start, moves);
|
||||
}
|
||||
}
|
||||
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
@@ -1792,6 +1802,8 @@ impl eframe::App for PhotocraftApp {
|
||||
return;
|
||||
}
|
||||
let t0 = gpu_canvas::now_ms();
|
||||
self.perf.frame_refresh_ms = 0.0;
|
||||
self.stroke_trace.cpu_prev(frame.info().cpu_usage);
|
||||
// A text field's right-click menu, before any field is drawn (text_field_menu.rs).
|
||||
text_field_menu::show(&ctx);
|
||||
// Each painting tool keeps its own brush (#218), so switch the active tool's brush in
|
||||
@@ -1893,7 +1905,13 @@ impl eframe::App for PhotocraftApp {
|
||||
egui::Modal::new(egui::Id::new("screen-color-wait")).frame(egui::Frame::NONE).backdrop_color(egui::Color32::TRANSPARENT).show(&ctx, |_| {});
|
||||
ctx.set_cursor_icon(egui::CursorIcon::Wait);
|
||||
}
|
||||
self.perf.frame(gpu_canvas::now_ms() - t0);
|
||||
let ui_ms = gpu_canvas::now_ms() - t0;
|
||||
self.perf.frame(ui_ms);
|
||||
if self.stroke_trace.enabled() {
|
||||
self.stroke_trace.canvas(self.perf.frame_refresh_ms);
|
||||
let info = &self.perf.gpu_info;
|
||||
self.stroke_trace.end_frame(ui_ms, self.live_stroke.is_some(), || format!("{} {}", info.backend, info.adapter).trim().to_string());
|
||||
}
|
||||
// Synthetic input is injected one press/release step per frame: keep frames coming until
|
||||
// the queue is empty, then release control replies waiting on it.
|
||||
if !self.synthetic.is_empty() {
|
||||
|
||||
@@ -223,7 +223,6 @@ fn dragging_the_mask_thumbnail_to_trash_asks_to_apply_or_delete_it() {
|
||||
s.execute("layer.layerMask.delete", json!({"layer": masked})).unwrap();
|
||||
s.execute("select.rect", json!({"x": 100, "y": 0, "width": 100, "height": 100})).unwrap();
|
||||
s.execute("layer.layerMask.revealSelection", json!({"layer": masked})).unwrap();
|
||||
s.execute("select.deselect", json!({})).unwrap();
|
||||
let mut h = harness(s, 0, 1.0, 290.0);
|
||||
let drag_mask = |h: &mut Harness<'_, PhotocraftApp>| {
|
||||
let from = recorded(&h.ctx, masked).unwrap().0.into_iter().find(|(k, _)| *k == MaskKind::Pixel).unwrap().1.center();
|
||||
@@ -595,7 +594,7 @@ fn mask_view_gestures_fail_gracefully_without_a_mask() {
|
||||
h.run_steps(2);
|
||||
// A stale view (layer gone) draws nothing instead of panicking.
|
||||
h.state_mut().session.active_mut().unwrap().channel_view.layer_mask = Some(photocraft_engine::mask_view_cmds::LayerMaskView {
|
||||
layer: photocraft_doc::LayerId(987_654),
|
||||
layer: photocraft_doc::LayerId(u64::MAX),
|
||||
mode: photocraft_engine::mask_view_cmds::MaskViewMode::Gray,
|
||||
});
|
||||
assert!(canvas_px(&h).is_none());
|
||||
|
||||
@@ -137,7 +137,7 @@ fn a_stale_or_bad_prompt_fails_gracefully() {
|
||||
app.run("layer.rasterize.type", json!({})).unwrap();
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err());
|
||||
// Garbage fields.
|
||||
for f in [json!({"__rasterize": "plaid", "layer": 1}), json!({"__rasterize": "type"}), json!({"__rasterize": "type", "layer": 999_999})] {
|
||||
for f in [json!({"__rasterize": "plaid", "layer": 1}), json!({"__rasterize": "type"}), json!({"__rasterize": "type", "layer": u64::MAX})] {
|
||||
let id = app.ui.open_dialog(crate::state::DialogKind::Command, f.as_object().unwrap().clone());
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err(), "{f}");
|
||||
}
|
||||
|
||||
@@ -338,6 +338,48 @@ fn a_committed_stroke_refreshes_only_what_each_cache_had_not_shown() {
|
||||
assert_eq!(c.since(99), None, "not a key of this stroke");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_stroke_trace_times_each_frame_of_a_stroke_and_ends_on_release() {
|
||||
// The app's hooks around the canvas (`raw_input_hook` starts a frame, `ui` ends it); the
|
||||
// canvas times the live stroke and the release's commit itself.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100, "background": "white"})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.tool = Tool::Brush;
|
||||
app.stroke_trace.output = crate::stroke_trace::Output::Stderr;
|
||||
let mut h = Harness::builder().with_size(vec2(900.0, 600.0)).build_ui_state(
|
||||
|ui, app: &mut PhotocraftApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) {
|
||||
return;
|
||||
}
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let moves = ctx.input(|i| i.raw.events.iter().filter(|e| matches!(e, egui::Event::PointerMoved(_))).count());
|
||||
app.stroke_trace.begin_frame(t0, moves);
|
||||
app.stroke_trace.cpu_prev(Some(0.004));
|
||||
egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui));
|
||||
let stroking = app.live_stroke.is_some();
|
||||
app.stroke_trace.end_frame(crate::gpu_canvas::now_ms() - t0, stroking, || "test".into());
|
||||
},
|
||||
app,
|
||||
);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(4);
|
||||
move_to(&mut h, 20.0, 50.0);
|
||||
button(&mut h, 20.0, 50.0, true);
|
||||
for x in [40.0, 60.0, 80.0, 100.0, 120.0] {
|
||||
move_to(&mut h, x, 50.0);
|
||||
}
|
||||
assert!(h.state().stroke_trace.last.is_none(), "the stroke is still being drawn");
|
||||
button(&mut h, 120.0, 50.0, false);
|
||||
h.run_steps(2);
|
||||
let s = h.state().stroke_trace.last.clone().expect("releasing ends the stroke's trace");
|
||||
assert!(s.frames >= 6, "{s:?}");
|
||||
assert!(s.stroke[1] > 0.0 && s.ui[0] >= s.stroke[0], "{s:?}");
|
||||
assert_eq!(s.moves[1], 1.0, "one move per test frame: {s:?}");
|
||||
assert_eq!(s.backend, "test");
|
||||
}
|
||||
|
||||
/// A Clone Stamp stroke through the canvas renders the points its commit gets (position and
|
||||
/// pressure, no tilt or times), so the commit can take the live pixels; they are what replaying
|
||||
/// the journaled command paints.
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Stroke latency trace (#1343): where each frame's time goes while a brush stroke is drawn, so
|
||||
//! a tester on any platform can report a per-stage breakdown instead of one input-to-pixel number.
|
||||
//!
|
||||
//! Set `PHOTOCRAFT_STROKE_TRACE` before launching: `1` prints a summary to stderr when each stroke
|
||||
//! ends; a file path also appends every frame of every stroke to that CSV. The last summary is in
|
||||
//! the control channel's `perf` output (`strokeTrace`).
|
||||
//!
|
||||
//! Per frame of a stroke it records the interval since the previous frame started, the pointer
|
||||
//! moves the frame delivered, the live stroke's render time, the canvas refresh (composite and
|
||||
//! upload), the UI build, and eframe's CPU time for the frame before (UI, tessellation and GPU
|
||||
//! submission, without the vsync wait). What the app can't see (the OS input queue before a frame
|
||||
//! starts, frames queued for the display, the compositor) is the rest of the input-to-photon time;
|
||||
//! the summary names the GPU backend because GL ignores the frame-latency setting.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// One frame of a stroke. Times in ms.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) struct Row {
|
||||
/// Frame start, from [`crate::gpu_canvas::now_ms`].
|
||||
pub t: f64,
|
||||
/// Since the previous frame started (0 for the first frame the trace saw).
|
||||
pub interval: f64,
|
||||
/// Pointer moves the frame delivered.
|
||||
pub moves: usize,
|
||||
/// Rendering the stroke's new points (the live stroke, or the commit on release).
|
||||
pub stroke: f64,
|
||||
/// Canvas refresh: composite and upload.
|
||||
pub canvas: f64,
|
||||
/// Building the UI (`App::ui`), the two above included.
|
||||
pub ui: f64,
|
||||
/// eframe's CPU time for the previous frame: UI, tessellation and GPU submission.
|
||||
pub cpu_prev: Option<f64>,
|
||||
}
|
||||
|
||||
/// Percentiles of a stroke's frames, for the summary line and the control channel.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Summary {
|
||||
pub frames: usize,
|
||||
/// GPU backend and adapter ("vulkan NVIDIA GeForce …").
|
||||
pub backend: String,
|
||||
/// `[p50, p95]` of each stage, in ms.
|
||||
pub interval: [f64; 2],
|
||||
pub moves: [f64; 2],
|
||||
pub stroke: [f64; 2],
|
||||
pub canvas: [f64; 2],
|
||||
pub ui: [f64; 2],
|
||||
/// eframe's CPU time per frame (UI, tessellation, submission).
|
||||
pub cpu: [f64; 2],
|
||||
/// Frame interval minus that CPU time: waiting on vsync / the swap chain, or idle.
|
||||
pub wait: [f64; 2],
|
||||
}
|
||||
|
||||
impl Summary {
|
||||
/// One line for stderr.
|
||||
pub fn line(&self) -> String {
|
||||
let f = |name: &str, [p50, p95]: [f64; 2]| format!("{name} {p50:.2}/{p95:.2}");
|
||||
[
|
||||
format!("stroke trace: {} frames on {} (p50/p95 ms):", self.frames, self.backend),
|
||||
f("interval", self.interval),
|
||||
f("moves/frame", self.moves),
|
||||
f("stroke", self.stroke),
|
||||
f("canvas", self.canvas),
|
||||
f("ui", self.ui),
|
||||
f("cpu", self.cpu),
|
||||
f("wait", self.wait),
|
||||
]
|
||||
.join(" ")
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the trace goes ([`StrokeTrace::from_env`]).
|
||||
// The web build has no clock, so it never traces.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub(crate) enum Output {
|
||||
#[default]
|
||||
Off,
|
||||
/// A summary per stroke on stderr.
|
||||
Stderr,
|
||||
/// The summary on stderr, and every frame appended to this CSV.
|
||||
Csv(std::path::PathBuf),
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct StrokeTrace {
|
||||
pub(crate) output: Output,
|
||||
/// The frame being built (started by `begin_frame`).
|
||||
frame: Option<Row>,
|
||||
last_start: Option<f64>,
|
||||
/// The current stroke's frames.
|
||||
rows: Vec<Row>,
|
||||
/// Strokes finished so far (numbers the CSV rows).
|
||||
strokes: usize,
|
||||
/// The last finished stroke's summary.
|
||||
pub last: Option<Summary>,
|
||||
}
|
||||
|
||||
/// `[p50, p95]` of `v` (nearest rank; zeros when empty).
|
||||
fn percentiles(mut v: Vec<f64>) -> [f64; 2] {
|
||||
v.retain(|x| x.is_finite());
|
||||
if v.is_empty() {
|
||||
return [0.0, 0.0];
|
||||
}
|
||||
v.sort_by(f64::total_cmp);
|
||||
let at = |p: f64| v.get(((p * (v.len() - 1) as f64).round() as usize).min(v.len() - 1)).copied().unwrap_or(0.0);
|
||||
let r = |x: f64| (x * 100.0).round() / 100.0;
|
||||
[r(at(0.5)), r(at(0.95))]
|
||||
}
|
||||
|
||||
impl StrokeTrace {
|
||||
/// Reads `PHOTOCRAFT_STROKE_TRACE` (off on the web, where there is no clock).
|
||||
pub fn from_env() -> Self {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(v) = std::env::var_os("PHOTOCRAFT_STROKE_TRACE").filter(|v| !v.is_empty()) {
|
||||
let output = if v == "1" || v == "stderr" { Output::Stderr } else { Output::Csv(v.into()) };
|
||||
return Self { output, ..Default::default() };
|
||||
}
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn enabled(&self) -> bool {
|
||||
self.output != Output::Off
|
||||
}
|
||||
|
||||
/// A frame starts (the raw input hook) with `moves` pointer moves.
|
||||
pub fn begin_frame(&mut self, now: f64, moves: usize) {
|
||||
if !self.enabled() {
|
||||
return;
|
||||
}
|
||||
let interval = self.last_start.map_or(0.0, |t| now - t);
|
||||
self.last_start = Some(now);
|
||||
self.frame = Some(Row { t: now, interval, moves, ..Default::default() });
|
||||
}
|
||||
|
||||
/// eframe's CPU time for the previous frame, in seconds (`Frame::info().cpu_usage`).
|
||||
pub fn cpu_prev(&mut self, secs: Option<f32>) {
|
||||
if let Some(f) = self.frame.as_mut() {
|
||||
f.cpu_prev = secs.map(|s| f64::from(s) * 1000.0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Time spent rendering stroke points this frame.
|
||||
pub fn stroke(&mut self, ms: f64) {
|
||||
if let Some(f) = self.frame.as_mut() {
|
||||
f.stroke += ms;
|
||||
}
|
||||
}
|
||||
|
||||
/// Time spent refreshing the canvas this frame.
|
||||
pub fn canvas(&mut self, ms: f64) {
|
||||
if let Some(f) = self.frame.as_mut() {
|
||||
f.canvas += ms;
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame's UI is built (`ui` ms). `stroking`: a stroke is being drawn (a frame that
|
||||
/// rendered stroke points counts too, such as the release's commit). A stroke's frames are
|
||||
/// kept until the first frame without one, which ends it.
|
||||
pub fn end_frame(&mut self, ui: f64, stroking: bool, backend: impl FnOnce() -> String) {
|
||||
let Some(mut f) = self.frame.take() else { return };
|
||||
if stroking || f.stroke > 0.0 {
|
||||
f.ui = ui;
|
||||
// The first frame of a stroke doesn't follow a stroke frame: its interval is idle time.
|
||||
if self.rows.is_empty() {
|
||||
f.interval = 0.0;
|
||||
}
|
||||
self.rows.push(f);
|
||||
} else if !self.rows.is_empty() {
|
||||
self.finish(backend());
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(&mut self, backend: String) {
|
||||
let rows = std::mem::take(&mut self.rows);
|
||||
self.strokes += 1;
|
||||
let col = |g: fn(&Row) -> Option<f64>| percentiles(rows.iter().filter_map(g).collect());
|
||||
let summary = Summary {
|
||||
frames: rows.len(),
|
||||
backend,
|
||||
interval: col(|r| (r.interval > 0.0).then_some(r.interval)),
|
||||
moves: col(|r| Some(r.moves as f64)),
|
||||
stroke: col(|r| Some(r.stroke)),
|
||||
canvas: col(|r| Some(r.canvas)),
|
||||
ui: col(|r| Some(r.ui)),
|
||||
// A frame's cpu_prev belongs to the frame before it, so pair it with that interval.
|
||||
cpu: percentiles(rows.iter().skip(1).filter_map(|r| r.cpu_prev).collect()),
|
||||
wait: percentiles(rows.windows(2).filter_map(|w| Some((w[1].interval - w[1].cpu_prev?).max(0.0))).collect()),
|
||||
};
|
||||
if self.enabled() {
|
||||
eprintln!("{}", summary.line());
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Output::Csv(path) = &self.output
|
||||
&& let Err(e) = append_csv(path, self.strokes, &rows)
|
||||
{
|
||||
eprintln!("stroke trace: can't write {}: {e}", path.display());
|
||||
}
|
||||
self.last = Some(summary);
|
||||
}
|
||||
}
|
||||
|
||||
/// The CSV text for `rows` of stroke `stroke` (with the header when `header`).
|
||||
// The web build has no clock, so it never traces.
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
pub(crate) fn csv(stroke: usize, rows: &[Row], header: bool) -> String {
|
||||
let mut s = String::new();
|
||||
if header {
|
||||
s.push_str("stroke,t_ms,interval_ms,moves,stroke_ms,canvas_ms,ui_ms,cpu_prev_ms\n");
|
||||
}
|
||||
for r in rows {
|
||||
let cpu = r.cpu_prev.map_or(String::new(), |c| format!("{c:.3}"));
|
||||
let _ = writeln!(s, "{stroke},{:.3},{:.3},{},{:.3},{:.3},{:.3},{cpu}", r.t, r.interval, r.moves, r.stroke, r.canvas, r.ui);
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn append_csv(path: &std::path::Path, stroke: usize, rows: &[Row]) -> std::io::Result<()> {
|
||||
use std::io::Write as _;
|
||||
let header = std::fs::metadata(path).map_or(true, |m| m.len() == 0);
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
|
||||
f.write_all(csv(stroke, rows, header).as_bytes())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn on() -> StrokeTrace {
|
||||
StrokeTrace { output: Output::Stderr, ..Default::default() }
|
||||
}
|
||||
|
||||
fn frame(t: &mut StrokeTrace, now: f64, cpu: f32, stroking: bool) {
|
||||
t.begin_frame(now, 3);
|
||||
t.cpu_prev(Some(cpu / 1000.0));
|
||||
if stroking {
|
||||
t.stroke(1.0);
|
||||
t.canvas(2.0);
|
||||
}
|
||||
t.end_frame(4.0, stroking, || "vulkan Test GPU".into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_is_its_frames_from_the_first_stroke_frame_to_the_first_without() {
|
||||
let mut t = on();
|
||||
frame(&mut t, 0.0, 5.0, false);
|
||||
frame(&mut t, 100.0, 5.0, true);
|
||||
for k in 1..=10 {
|
||||
frame(&mut t, 100.0 + 16.0 * f64::from(k), 6.0, true);
|
||||
}
|
||||
assert!(t.last.is_none(), "still drawing");
|
||||
frame(&mut t, 276.0, 6.0, false);
|
||||
let s = t.last.clone().expect("the stroke ended");
|
||||
assert_eq!(s.frames, 11);
|
||||
assert_eq!(s.interval, [16.0, 16.0], "the idle gap before the stroke isn't a frame interval");
|
||||
assert_eq!((s.stroke, s.canvas, s.ui, s.moves), ([1.0, 1.0], [2.0, 2.0], [4.0, 4.0], [3.0, 3.0]));
|
||||
assert_eq!((s.cpu, s.wait), ([6.0, 6.0], [10.0, 10.0]));
|
||||
assert!(s.line().contains("11 frames on vulkan Test GPU") && s.line().contains("wait 10.00/10.00"), "{}", s.line());
|
||||
// Off: nothing is kept.
|
||||
let mut off = StrokeTrace::default();
|
||||
frame(&mut off, 0.0, 1.0, true);
|
||||
frame(&mut off, 16.0, 1.0, false);
|
||||
assert!(off.last.is_none() && off.rows.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_rows_and_odd_numbers() {
|
||||
let rows = [Row { t: 1.0, interval: 16.5, moves: 2, stroke: 0.25, canvas: 1.0, ui: 3.0, cpu_prev: None }];
|
||||
assert_eq!(csv(1, &rows, true), "stroke,t_ms,interval_ms,moves,stroke_ms,canvas_ms,ui_ms,cpu_prev_ms\n1,1.000,16.500,2,0.250,1.000,3.000,\n");
|
||||
assert_eq!(percentiles(vec![]), [0.0, 0.0]);
|
||||
assert_eq!(percentiles(vec![f64::NAN, 2.0, f64::INFINITY]), [2.0, 2.0]);
|
||||
assert_eq!(percentiles((1..=100).map(f64::from).collect()), [51.0, 95.0]);
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn the_csv_gets_one_header_and_every_strokes_frames() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-stroke-trace-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let path = dir.join("trace.csv");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let mut t = StrokeTrace { output: Output::Csv(path.clone()), ..Default::default() };
|
||||
for start in [0.0, 1000.0] {
|
||||
for k in 0..3 {
|
||||
frame(&mut t, start + 16.0 * f64::from(k), 5.0, true);
|
||||
}
|
||||
frame(&mut t, start + 48.0, 5.0, false);
|
||||
}
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 7, "{text}");
|
||||
assert!(lines[0].starts_with("stroke,") && lines[1].starts_with("1,") && lines[6].starts_with("2,"));
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,8 @@ fn app() -> (PhotocraftApp, u64) {
|
||||
let id = open_print(&mut app);
|
||||
// Every UI path in these fixtures is safe even if an unexpected Enter confirms the dialog.
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("dryRun".into(), json!(true));
|
||||
// Exercise PDF paper controls even when native printers are available, on every OS.
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("__printers".into(), json!(["Test native printer"]));
|
||||
(app, id)
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user