mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge remote-tracking branch 'origin/main' into task/T-0003
This commit is contained in:
commit
b470dcab2d
119 files changed
+3403
-360
No files matched your search
Generated
+1
@@ -4397,6 +4397,7 @@ dependencies = [
|
||||
"blake3",
|
||||
"crc32fast",
|
||||
"flate2",
|
||||
"libc",
|
||||
"photocraft-codecs",
|
||||
"photocraft-color",
|
||||
"photocraft-doc",
|
||||
|
||||
@@ -154,3 +154,7 @@ sync_github_name = true
|
||||
[people.VanTan666]
|
||||
display_name = "VanTan"
|
||||
sync_github_name = false
|
||||
|
||||
[people.yeniufuklar-com]
|
||||
real_name = "Ufuk Efe"
|
||||
sync_github_name = true
|
||||
@@ -71,7 +71,10 @@ impl Graph {
|
||||
let ai = a as usize;
|
||||
let j = self.head[ai] as usize;
|
||||
work += 1;
|
||||
if self.r_cap[ai] > EPS && self.dist[i] == self.dist[j].saturating_add(1) {
|
||||
// `checked_add`: two nodes a global relabel left unreachable (`u32::MAX`) must
|
||||
// not count as admissible for each other, or float-stranded excess ping-pongs
|
||||
// between them forever.
|
||||
if self.r_cap[ai] > EPS && self.dist[j].checked_add(1) == Some(self.dist[i]) {
|
||||
let delta = (excess[i] as f32).min(self.r_cap[ai]);
|
||||
self.r_cap[ai] -= delta;
|
||||
self.r_cap[ai ^ 1] += delta;
|
||||
|
||||
@@ -179,3 +179,28 @@ fn solver_workload_release_comparison() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stranded_excess_terminates_and_matches_bk() {
|
||||
// Source capacities far beyond f32 precision (ulp 32 at 3e8) next to small links: rounding
|
||||
// strands excess on nodes a global relabel finds reachable from neither terminal. Those
|
||||
// nodes (height u32::MAX) used to count as admissible for each other and pushed the excess
|
||||
// back and forth forever (Remove Background never finished on some photos).
|
||||
let mut g = Graph::with_capacity(6, 7);
|
||||
for (i, &(s, t)) in [(33123824.0, 0.0), (347622050.0, 0.0), (0.0, 5539047.5), (76592.22, 0.0), (3514.0022, 0.0), (0.0, 13670.268)].iter().enumerate() {
|
||||
g.add_tweights(i, s, t);
|
||||
}
|
||||
for (i, j, c) in [(0, 1, 0.0), (0, 3, 0.0007301044), (1, 2, 2.803e-42), (1, 4, 8.160078), (2, 5, 3.1224866e-7), (3, 4, 28.512966), (4, 5, 4.099367)] {
|
||||
g.add_edge(i, j, c, c);
|
||||
}
|
||||
let mut bk = g.clone();
|
||||
let checks = std::cell::Cell::new(0);
|
||||
let cancel = || {
|
||||
checks.set(checks.get() + 1);
|
||||
checks.get() > 1000
|
||||
};
|
||||
let flow = g.push_relabel(&cancel).expect("push/relabel did not terminate");
|
||||
let bk_flow = bk.maxflow_bk();
|
||||
assert!((flow - bk_flow).abs() <= 1e-6 * bk_flow, "{flow} vs {bk_flow}");
|
||||
assert_eq!((0..6).map(|i| g.in_source(i)).collect::<Vec<_>>(), (0..6).map(|i| bk.in_source(i)).collect::<Vec<_>>());
|
||||
}
|
||||
@@ -17,6 +17,15 @@ fn err(e: impl std::fmt::Display) -> CodecError {
|
||||
CodecError::malformed(F, e)
|
||||
}
|
||||
|
||||
/// Pixels per inch for `pHYs` pixels per metre. A whole number of ppi is stored rounded to whole
|
||||
/// pixels per metre (300 ppi = 11811), so reading it back gives 299.9994: the whole number that
|
||||
/// rounds to the stored value is the resolution that was meant, as Photoshop reads it.
|
||||
pub(crate) fn dpi_of_ppm(ppm: u32) -> f32 {
|
||||
let dpi = f64::from(ppm) * f64::from(METERS_PER_INCH);
|
||||
let whole = dpi.round();
|
||||
if (whole / f64::from(METERS_PER_INCH)).round() == f64::from(ppm) { whole as f32 } else { dpi as f32 }
|
||||
}
|
||||
|
||||
pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError> {
|
||||
let mut input = Cursor::new(bytes);
|
||||
let mut decoder = png::Decoder::new_with_limits(&mut input, png::Limits { bytes: limits.alloc_usize() });
|
||||
@@ -74,7 +83,7 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
|
||||
&& d.xppu > 0
|
||||
&& d.yppu > 0
|
||||
{
|
||||
meta.dpi = Some((d.xppu as f32 * METERS_PER_INCH, d.yppu as f32 * METERS_PER_INCH));
|
||||
meta.dpi = Some((dpi_of_ppm(d.xppu), dpi_of_ppm(d.yppu)));
|
||||
}
|
||||
drop(reader);
|
||||
let end = usize::try_from(input.position()).map_err(|_| err("invalid PNG reader position"))?;
|
||||
|
||||
@@ -100,12 +100,13 @@ pub enum PngCompression {
|
||||
Best,
|
||||
}
|
||||
|
||||
/// TIFF strip compression.
|
||||
/// TIFF strip compression. The default is none, as in Photoshop: uncompressed strips are the
|
||||
/// only kind every TIFF reader opens (Deflate and the predictor are not baseline TIFF, #4484).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum TiffCompression {
|
||||
#[default]
|
||||
None,
|
||||
Lzw,
|
||||
#[default]
|
||||
Deflate,
|
||||
PackBits,
|
||||
}
|
||||
@@ -190,7 +191,7 @@ impl Default for EncodeOptions {
|
||||
png_interlaced: false,
|
||||
webp_lossless: true,
|
||||
webp_quality: 80,
|
||||
tiff_compression: TiffCompression::Deflate,
|
||||
tiff_compression: TiffCompression::None,
|
||||
tiff_bigtiff: false,
|
||||
exr_compression: ExrCompression::Zip16,
|
||||
dpx_bits: None,
|
||||
|
||||
@@ -307,7 +307,9 @@ pub fn encode_jpeg_rgb8(
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
let mut enc = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
|
||||
let subsampled = quality < 90;
|
||||
// Like Photoshop's Save for Web: 4:2:0 chroma up to quality 50, 4:4:4 from 51 (measured on
|
||||
// Photoshop 2025's output; its Save As keeps 4:2:0 at every quality).
|
||||
let subsampled = quality <= 50;
|
||||
enc.set_progressive(progressive);
|
||||
// jpeg-encoder 0.6 writes corrupt baseline scans when optimised Huffman tables meet 4:2:0
|
||||
// (both zune-jpeg and image-rs decode them green); progressive output is fine.
|
||||
@@ -345,6 +347,24 @@ mod tests {
|
||||
(0..w * h).map(|i| (((i % w) * 7 + (i / w) * 13 + (i * i) % 5) % n) as u8).collect()
|
||||
}
|
||||
|
||||
/// The luma sampling factors (h, v) of a baseline or progressive JPEG.
|
||||
fn luma_sampling(bytes: &[u8]) -> Option<(u8, u8)> {
|
||||
let i = bytes.windows(2).position(|w| w[0] == 0xFF && matches!(w[1], 0xC0..=0xC2))?;
|
||||
let f = *bytes.get(i + 11)?;
|
||||
Some((f >> 4, f & 15))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jpeg_chroma_is_full_above_quality_50() {
|
||||
let rgb: Vec<u8> = (0..16 * 16 * 3).map(|i| (i * 37 % 256) as u8).collect();
|
||||
for (q, want) in [(1, (2, 2)), (50, (2, 2)), (51, (1, 1)), (60, (1, 1)), (89, (1, 1)), (100, (1, 1))] {
|
||||
for progressive in [false, true] {
|
||||
let bytes = encode_jpeg_rgb8(16, 16, &rgb, q, progressive, false, None, None, None).unwrap();
|
||||
assert_eq!(luma_sampling(&bytes), Some(want), "quality {q} progressive {progressive}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gif_roundtrips_through_the_decoder() {
|
||||
let pal: Vec<[u8; 3]> = (0..200).map(|i| [i as u8, (255 - i) as u8, (i * 3 % 256) as u8]).collect();
|
||||
|
||||
@@ -425,16 +425,38 @@ fn png_phys_outranks_its_exif() {
|
||||
img.meta.exif = Some(camera_exif(&LE));
|
||||
let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
near(decode(&png).unwrap().meta.dpi, 300.0);
|
||||
near(decode(&with_phys(&png, 5906)).unwrap().meta.dpi, 150.0);
|
||||
}
|
||||
|
||||
/// `png` with a `pHYs` chunk of `ppm` pixels per metre after IHDR.
|
||||
fn with_phys(png: &[u8], ppm: u32) -> Vec<u8> {
|
||||
let mut body = b"pHYs".to_vec();
|
||||
body.extend_from_slice(&5906u32.to_be_bytes());
|
||||
body.extend_from_slice(&5906u32.to_be_bytes());
|
||||
body.extend_from_slice(&ppm.to_be_bytes());
|
||||
body.extend_from_slice(&ppm.to_be_bytes());
|
||||
body.push(1);
|
||||
let mut chunk = 9u32.to_be_bytes().to_vec();
|
||||
chunk.extend_from_slice(&body);
|
||||
chunk.extend_from_slice(&crc32(&body).to_be_bytes());
|
||||
let ihdr_end = 8 + 8 + 13 + 4;
|
||||
let with_phys = [&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat();
|
||||
near(decode(&with_phys).unwrap().meta.dpi, 150.0114);
|
||||
[&png[..ihdr_end], &chunk, &png[ihdr_end..]].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn png_phys_of_a_whole_ppi_reads_back_whole() {
|
||||
// pHYs holds whole pixels per metre: 300 ppi is stored as 11811 (299.9994 ppi), 72 as 2835
|
||||
// (72.009). The whole number that rounds to the stored value is read, as Photoshop does; a
|
||||
// value no whole ppi rounds to stays as it is.
|
||||
let img = Image::from_raw(4, 4, ChannelLayout::Rgb, SampleType::U8, vec![90; 48]).unwrap();
|
||||
let png = encode(&img, Format::Png, &EncodeOptions { embed_metadata: false, ..Default::default() }).unwrap();
|
||||
for (ppm, want) in [(11811, 300.0), (2835, 72.0), (3937, 100.0), (11812, 300.0248)] {
|
||||
let (x, y) = decode(&with_phys(&png, ppm)).unwrap().meta.dpi.unwrap();
|
||||
assert!((x - want).abs() < 1e-4 && (y - want).abs() < 1e-4, "{ppm} px/m: {x} × {y}, wanted {want}");
|
||||
}
|
||||
// And a 300 ppi PNG written by the encoder opens at exactly 300.
|
||||
let mut img = img;
|
||||
img.meta.dpi = Some((300.0, 300.0));
|
||||
let png = encode(&img, Format::Png, &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(decode(&png).unwrap().meta.dpi, Some((300.0, 300.0)));
|
||||
}
|
||||
|
||||
/// `camera_exif` plus IFD1, the embedded thumbnail a camera (or the last editor) wrote:
|
||||
|
||||
@@ -150,3 +150,27 @@ fn ccitt_group4_tiff_decodes() {
|
||||
assert_ne!(d[0], d[8], "{d:?}");
|
||||
assert_eq!(d[0], 255, "white row of a WhiteIsZero image");
|
||||
}
|
||||
|
||||
/// #4484: a TIFF saved with the default options must open in software that only reads
|
||||
/// baseline TIFF (embroidery and plotter tools, older readers). Like Photoshop's default, that
|
||||
/// means uncompressed strips with no predictor, classic offsets and unassociated alpha.
|
||||
#[test]
|
||||
fn default_tiff_is_baseline() {
|
||||
use photocraft_codecs::{ChannelLayout, EncodeOptions, Format, SampleType, encode};
|
||||
use std::io::Cursor;
|
||||
use tiff::tags::Tag;
|
||||
|
||||
for layout in [ChannelLayout::Rgb, ChannelLayout::Rgba] {
|
||||
let img = common::synth(33, 21, layout, SampleType::U8, 7, 0.4);
|
||||
let bytes = encode(&img, Format::Tiff, &EncodeOptions::default()).expect("encode");
|
||||
assert!(bytes.starts_with(b"II*\0") || bytes.starts_with(b"MM\0*"), "{layout:?}: not a classic TIFF");
|
||||
let mut dec = tiff::decoder::Decoder::new(Cursor::new(&bytes[..])).expect("open");
|
||||
assert_eq!(dec.get_tag_u32(Tag::Compression).ok(), Some(1), "{layout:?}: Compression");
|
||||
assert_eq!(dec.find_tag(Tag::Predictor).ok().flatten().and_then(|v| v.into_u16().ok()).unwrap_or(1), 1, "{layout:?}: Predictor");
|
||||
assert!(dec.find_tag(Tag::TileWidth).ok().flatten().is_none(), "{layout:?}: tiled");
|
||||
assert_eq!(dec.get_tag_u32(Tag::PlanarConfiguration).ok().unwrap_or(1), 1, "{layout:?}: planar");
|
||||
let extra = dec.find_tag(Tag::ExtraSamples).ok().flatten().and_then(|v| v.into_u16_vec().ok());
|
||||
assert_eq!(extra, if layout == ChannelLayout::Rgba { Some(vec![2]) } else { None }, "{layout:?}: ExtraSamples");
|
||||
assert_eq!(decode(&bytes).expect("decode").data(), img.data(), "{layout:?}: round trip");
|
||||
}
|
||||
}
|
||||
@@ -605,8 +605,9 @@ const BALANCE_LEVELS: f32 = 0.39;
|
||||
/// - Preserve Luminosity off: a slider only moves its own channel. Midtones is gamma 2^−a.
|
||||
/// Shadows is gamma 2^(−a/2) after a black point at 0.39·|a| when lowered; highlights is
|
||||
/// gamma 2^(−a/2) after a white point at 1 − 0.39·a when raised.
|
||||
/// - Preserve Luminosity on: midtones is gamma 2^(−a/2) on the slider's channel and 2^(a/2) on
|
||||
/// the other two. Shadows and highlights go by the differences between a tone's three sliders:
|
||||
/// - Preserve Luminosity on: midtones uses gamma 2^((max(a) + min(a))/2 − a_ch),
|
||||
/// preserving the one-slider behaviour without summing offsets when multiple sliders move.
|
||||
/// Shadows and highlights go by the differences between a tone's three sliders:
|
||||
/// each channel gets a plain black point at 0.39·(max − its own) for shadows and a plain white
|
||||
/// point at 1 − 0.39·(its own − min) for highlights (so one raised shadows slider darkens the
|
||||
/// other two channels, and two raised together darken only the third).
|
||||
@@ -620,28 +621,27 @@ pub fn color_balance_channel(tones: [[f32; 3]; 3], preserve_luminosity: bool, ch
|
||||
let mut v = v.clamp(0.0, 1.0);
|
||||
for (tone, sliders) in [(2, highlights), (0, shadows), (1, midtones)] {
|
||||
let a: [f32; 3] = sliders.map(|s| (s / 100.0).clamp(-1.0, 1.0));
|
||||
if preserve_luminosity && tone != 1 {
|
||||
if preserve_luminosity {
|
||||
let own = a.get(ch).copied().unwrap_or(0.0);
|
||||
let (lo, hi) = a.iter().fold((f32::MAX, f32::MIN), |m, x| (m.0.min(*x), m.1.max(*x)));
|
||||
v = if tone == 0 { black(v, BALANCE_LEVELS * (hi - own)) } else { white(v, 1.0 - BALANCE_LEVELS * (own - lo)) };
|
||||
v = match tone {
|
||||
0 => black(v, BALANCE_LEVELS * (hi - own)),
|
||||
1 => v.powf(2f32.powf((hi + lo) / 2.0 - own)),
|
||||
_ => white(v, 1.0 - BALANCE_LEVELS * (own - lo)),
|
||||
};
|
||||
continue;
|
||||
}
|
||||
for (src, slider) in sliders.iter().enumerate() {
|
||||
let a = (slider / 100.0).clamp(-1.0, 1.0);
|
||||
let own = src == ch;
|
||||
if a == 0.0 || (!preserve_luminosity && !own) {
|
||||
if a == 0.0 || src != ch {
|
||||
continue;
|
||||
}
|
||||
v = match (tone, preserve_luminosity) {
|
||||
(1, false) => v.powf(2f32.powf(-a)),
|
||||
(1, true) => v.powf(2f32.powf(if own { -a } else { a } / 2.0)),
|
||||
(0, false) if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)),
|
||||
(0, false) => v.powf(2f32.powf(-a / 2.0)),
|
||||
|
||||
(2, false) if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)),
|
||||
(2, false) => v.powf(2f32.powf(-a / 2.0)),
|
||||
|
||||
_ => v,
|
||||
v = match tone {
|
||||
1 => v.powf(2f32.powf(-a)),
|
||||
0 if a < 0.0 => black(v, BALANCE_LEVELS * -a).powf(2f32.powf(-a / 2.0)),
|
||||
0 => v.powf(2f32.powf(-a / 2.0)),
|
||||
2 if a > 0.0 => white(v, 1.0 - BALANCE_LEVELS * a).powf(2f32.powf(-a / 2.0)),
|
||||
_ => v.powf(2f32.powf(-a / 2.0)),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1254,6 +1254,26 @@ mod tone_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_balance_midtones_with_multiple_sliders_preserve_luminosity() {
|
||||
// A shared offset depends on the two extremes, not the sum of moved sliders.
|
||||
// The old per-slider product leaves red/blue unchanged for [30, 0, 30].
|
||||
let tones = [[0.0; 3], [30.0, 0.0, 30.0], [0.0; 3]];
|
||||
for input in [0.25_f32, 0.5, 0.75] {
|
||||
for (ch, offset) in [-0.15_f32, 0.15, -0.15].into_iter().enumerate() {
|
||||
let expected = input.powf(2f32.powf(offset));
|
||||
let actual = color_balance_channel(tones, true, ch, input);
|
||||
assert!((actual - expected).abs() < 1e-6, "channel {ch}, input {input}: {actual} vs {expected}");
|
||||
}
|
||||
// Preserve Luminosity off must still affect only the moved channels.
|
||||
assert_eq!(color_balance_channel(tones, false, 1, input), input);
|
||||
// One moved slider retains its previous half-strength compensation.
|
||||
let single = [[0.0; 3], [30.0, 0.0, 0.0], [0.0; 3]];
|
||||
assert!((color_balance_channel(single, true, 0, input) - input.powf(2f32.powf(-0.15))).abs() < 1e-6);
|
||||
assert!((color_balance_channel(single, true, 1, input) - input.powf(2f32.powf(0.15))).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_and_curves_apply_each_channel_before_the_master() {
|
||||
// These two affine tone adjustments describe the same mapping:
|
||||
|
||||
@@ -58,7 +58,7 @@ choice!(ColorPicker { Adobe = "adobe", System = "system" } default Adobe);
|
||||
choice!(Theme { Pro = "pro", ProMedium = "proMedium", ProLightGray = "proLightGray", ProLight = "proLight", Studio = "studio", StudioLight = "studioLight", Classic = "classic", SolarizedDark = "solarizedDark", Adwaita = "adwaita", AdwaitaDark = "adwaitaDark", BreezeLight = "breezeLight", BreezeDark = "breezeDark", SoftDark = "softDark", SoftLight = "softLight" } default ProMedium);
|
||||
choice!(AppearanceMode { Auto = "auto", Dark = "dark", Light = "light" } default Dark);
|
||||
choice!(DarkTheme { Pro = "pro", ProMedium = "proMedium", Studio = "studio", SolarizedDark = "solarizedDark", AdwaitaDark = "adwaitaDark", BreezeDark = "breezeDark", SoftDark = "softDark" } default ProMedium);
|
||||
choice!(LightTheme { StudioLight = "studioLight", ProLightGray = "proLightGray", ProLight = "proLight", Classic = "classic", Adwaita = "adwaita", BreezeLight = "breezeLight", SoftLight = "softLight" } default StudioLight);
|
||||
choice!(LightTheme { ProLight = "proLight", ProLightGray = "proLightGray", StudioLight = "studioLight", Classic = "classic", Adwaita = "adwaita", BreezeLight = "breezeLight", SoftLight = "softLight" } default ProLight);
|
||||
choice!(CanvasColor { Default = "default", Black = "black", DarkGray = "darkGray", MediumGray = "mediumGray", LightGray = "lightGray", Custom = "custom" } default Default);
|
||||
choice!(CanvasBorder { DropShadow = "dropShadow", Line = "line", None = "none" } default DropShadow);
|
||||
choice!(UiScale { Auto = "auto", P75 = "75", P80 = "80", P85 = "85", P90 = "90", P95 = "95", P100 = "100", P125 = "125", P150 = "150", P175 = "175", P200 = "200", P250 = "250", P300 = "300" } default Auto);
|
||||
@@ -293,7 +293,7 @@ impl Default for Interface {
|
||||
theme: Theme::ProMedium,
|
||||
appearance_mode: AppearanceMode::Dark,
|
||||
dark_theme: DarkTheme::ProMedium,
|
||||
light_theme: LightTheme::StudioLight,
|
||||
light_theme: LightTheme::ProLight,
|
||||
favorite_themes: Vec::new(),
|
||||
canvas_color: CanvasColor::Default,
|
||||
canvas_custom_color: "#282828".into(),
|
||||
|
||||
@@ -55,9 +55,9 @@ fn appearance_defaults_and_legacy_theme_migrate() {
|
||||
// New users keep Photoshop's default; following the system is opt-in.
|
||||
assert_eq!(p.interface.appearance_mode, AppearanceMode::Dark);
|
||||
assert_eq!(p.interface.dark_theme, DarkTheme::ProMedium);
|
||||
assert_eq!(p.interface.light_theme, LightTheme::StudioLight);
|
||||
assert_eq!(p.interface.light_theme, LightTheme::ProLight);
|
||||
for (theme, mode, dark, light) in
|
||||
[("pro", AppearanceMode::Dark, DarkTheme::Pro, LightTheme::StudioLight), ("classic", AppearanceMode::Light, DarkTheme::ProMedium, LightTheme::Classic)]
|
||||
[("pro", AppearanceMode::Dark, DarkTheme::Pro, LightTheme::ProLight), ("classic", AppearanceMode::Light, DarkTheme::ProMedium, LightTheme::Classic)]
|
||||
{
|
||||
let mut s = Session::new();
|
||||
s.load_prefs_json(&json!({"interface": {"theme": theme}}).to_string()).unwrap();
|
||||
|
||||
@@ -24,10 +24,15 @@ crc32fast = "1.5"
|
||||
blake3 = { version = "1.8", default-features = false, features = ["pure"] }
|
||||
ruzstd = "0.9"
|
||||
|
||||
# A plain fsync where a file system refuses the full flush (`sync_file`, atomic.rs). Already in
|
||||
# Cargo.lock on Apple targets (cap-std), so this adds no new crate.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
# Unix directory cleanup uses no-follow descriptor-relative operations; the same
|
||||
# dependency provides the plain-fsync fallback on Apple file systems.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { version = "1.1", default-features = false, features = ["std", "fs"] }
|
||||
|
||||
# rustix does not expose Apple's directory-search open mode. Only the named
|
||||
# constant is used; all descriptor operations remain in safe rustix APIs.
|
||||
[target.'cfg(target_vendor = "apple")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
proptest = { workspace = true }
|
||||
+111
-6
@@ -570,10 +570,82 @@ fn write_bundle_file(root: &Path, path: &Path, data: &[u8]) -> Result<()> {
|
||||
result
|
||||
}
|
||||
|
||||
fn remove_bundle_file(root: &Path, path: &Path) -> Result<()> {
|
||||
/// Keep the existing leaf/path validation and pin the actual unlink to opened
|
||||
/// directory handles on Unix. This closes the check-then-remove path-swap gap.
|
||||
fn remove_bundle_file(root: &Path, path: &Path, gc: &BundleGc) -> Result<()> {
|
||||
validate_bundle_file(root, path)?;
|
||||
std::fs::remove_file(path)?;
|
||||
Ok(())
|
||||
let relative = path.strip_prefix(root).map_err(|_| unsafe_bundle_entry(path))?;
|
||||
gc.remove(relative)
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct BundleGc {
|
||||
root: rustix::fd::OwnedFd,
|
||||
tiles: rustix::fd::OwnedFd,
|
||||
blobs: rustix::fd::OwnedFd,
|
||||
composite: rustix::fd::OwnedFd,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn gc_directory_flags() -> rustix::fs::OFlags {
|
||||
use rustix::fs::OFlags;
|
||||
|
||||
// GC needs directory traversal, not permission to read a directory listing.
|
||||
// Both modes retain a descriptor for the directory opened here, so a later
|
||||
// pathname replacement cannot redirect descriptor-relative cleanup.
|
||||
#[cfg(any(target_os = "linux", target_os = "android"))]
|
||||
let access = OFlags::PATH;
|
||||
#[cfg(target_vendor = "apple")]
|
||||
let access = OFlags::from_bits_retain(libc::O_SEARCH.cast_unsigned());
|
||||
#[cfg(not(any(target_os = "linux", target_os = "android", target_vendor = "apple")))]
|
||||
let access = OFlags::RDONLY;
|
||||
access | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl BundleGc {
|
||||
fn new(root: &Path) -> Result<Self> {
|
||||
use rustix::fs::{Mode, open, openat};
|
||||
|
||||
let flags = gc_directory_flags();
|
||||
let root = open(root, flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let tiles = openat(&root, "tiles", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let blobs = openat(&root, "blobs", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
let composite = openat(&root, "composite", flags, Mode::empty()).map_err(std::io::Error::from)?;
|
||||
Ok(Self { root, tiles, blobs, composite })
|
||||
}
|
||||
|
||||
fn remove(&self, relative: &Path) -> Result<()> {
|
||||
let relative = relative.to_str().ok_or_else(|| unsafe_bundle_entry(relative))?;
|
||||
let (handle, name) = match relative {
|
||||
THUMB => (&self.root, THUMB),
|
||||
COMPOSITE => (&self.composite, "preview.png"),
|
||||
_ => match relative.split_once('/') {
|
||||
Some(("tiles", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.tiles, name),
|
||||
Some(("blobs", name)) if name.strip_suffix(".zst").is_some_and(is_valid_hash) => (&self.blobs, name),
|
||||
_ => return Err(FormatError::Unsupported(format!("invalid bundle cleanup target: {relative}"))),
|
||||
},
|
||||
};
|
||||
rustix::fs::unlinkat(handle, name, rustix::fs::AtFlags::empty()).map_err(std::io::Error::from)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
struct BundleGc {
|
||||
root: PathBuf,
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
impl BundleGc {
|
||||
fn new(root: &Path) -> Result<Self> {
|
||||
Ok(Self { root: root.to_path_buf() })
|
||||
}
|
||||
|
||||
fn remove(&self, relative: &Path) -> Result<()> {
|
||||
std::fs::remove_file(self.root.join(relative))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn existing_object_is_valid(path: &Path, object: &Object, what: &str) -> Result<(bool, Option<FileSignature>)> {
|
||||
@@ -802,11 +874,14 @@ impl PcraftWriter {
|
||||
for (name, data) in &p.previews {
|
||||
write_bundle_file(dir, &dir.join(name), data)?;
|
||||
}
|
||||
// Pin all GC directories before removing stale previews or objects.
|
||||
// Unix cleanup then stays within these directories even if a pathname is swapped.
|
||||
let gc = BundleGc::new(dir)?;
|
||||
for stale in [THUMB, COMPOSITE] {
|
||||
if !p.previews.iter().any(|(n, _)| *n == stale) {
|
||||
let path = dir.join(stale);
|
||||
validate_bundle_file(dir, &path)?;
|
||||
match remove_bundle_file(dir, &path) {
|
||||
match remove_bundle_file(dir, &path, &gc) {
|
||||
Err(FormatError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
other => other?,
|
||||
}
|
||||
@@ -818,7 +893,7 @@ impl PcraftWriter {
|
||||
// complete save into a reported failure); a leftover is retried on the next save.
|
||||
for path in existing {
|
||||
if !p.objects.contains_key(&path) {
|
||||
if remove_bundle_file(dir, &dir.join(&path)).is_ok() {
|
||||
if remove_bundle_file(dir, &dir.join(&path), &gc).is_ok() {
|
||||
stats.objects_removed += 1;
|
||||
}
|
||||
if let Some(cache) = &mut self.verified_directory {
|
||||
@@ -866,6 +941,36 @@ impl PcraftWriter {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[test]
|
||||
fn gc_pinned_directory_handles_resist_subdirectory_swap() {
|
||||
use std::os::unix::fs::symlink;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let root = std::env::temp_dir().join(format!("pcraft-gc-swap-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
|
||||
let bundle = root.join("project.pcraft");
|
||||
let outside = root.join("outside");
|
||||
for sub in ["tiles", "blobs", "composite"] {
|
||||
std::fs::create_dir_all(bundle.join(sub)).unwrap();
|
||||
}
|
||||
std::fs::create_dir(&outside).unwrap();
|
||||
let filename = format!("{}.zst", "c".repeat(64));
|
||||
std::fs::write(bundle.join("tiles").join(&filename), b"stale bundle file").unwrap();
|
||||
std::fs::write(outside.join(&filename), b"outside file must survive").unwrap();
|
||||
|
||||
let gc = BundleGc::new(&bundle).unwrap();
|
||||
std::fs::rename(bundle.join("tiles"), bundle.join("old-tiles")).unwrap();
|
||||
symlink(&outside, bundle.join("tiles")).unwrap();
|
||||
|
||||
// Exercise the descriptor-relative unlink directly: the public save path
|
||||
// also validates the leaf, but that check itself cannot prevent a later swap.
|
||||
gc.remove(Path::new(&format!("tiles/{filename}"))).unwrap();
|
||||
assert!(!bundle.join("old-tiles").join(&filename).exists());
|
||||
assert_eq!(std::fs::read(outside.join(&filename)).unwrap(), b"outside file must survive");
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
fn list_objects(dir: &Path) -> Result<HashSet<String>> {
|
||||
let mut out = HashSet::new();
|
||||
for sub in ["tiles", "blobs"] {
|
||||
@@ -878,7 +983,7 @@ fn list_objects(dir: &Path) -> Result<HashSet<String>> {
|
||||
for e in rd {
|
||||
let e = e?;
|
||||
let name = e.file_name().to_string_lossy().into_owned();
|
||||
if name.ends_with(".zst") {
|
||||
if name.strip_suffix(".zst").is_some_and(is_valid_hash) {
|
||||
let path = e.path();
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Ok(metadata) if metadata.file_type().is_symlink() => return Err(unsafe_bundle_entry(&path)),
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
//! Directory cleanup only owns content-addressed objects; unrelated files survive.
|
||||
|
||||
mod common;
|
||||
|
||||
use common::temp_dir;
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_format::{PcraftWriter, SaveOptions};
|
||||
use photocraft_geom::Size;
|
||||
|
||||
fn empty_doc() -> Document {
|
||||
Document::new("clean", Size::new(1, 1), ColorMode::Rgb, SampleType::U8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_cleanup_preserves_unrelated_zst_files() {
|
||||
let root = temp_dir("unrelated-object");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
|
||||
let unrelated = bundle.join("tiles/personal-notes.zst");
|
||||
let orphan = bundle.join("blobs").join(format!("{}.zst", "b".repeat(64)));
|
||||
std::fs::write(&unrelated, b"unrelated file").unwrap();
|
||||
std::fs::write(&orphan, b"unused content-addressed object").unwrap();
|
||||
|
||||
let stats = writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
assert_eq!(std::fs::read(&unrelated).unwrap(), b"unrelated file");
|
||||
assert!(!orphan.exists(), "a valid but unreferenced object is removed");
|
||||
assert_eq!(stats.objects_removed, 1);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "linux", target_os = "android", target_vendor = "apple"))]
|
||||
mod permissions {
|
||||
use super::*;
|
||||
use photocraft_format::load_path;
|
||||
use photocraft_raster::Rgba8Image;
|
||||
use std::os::unix::fs::{PermissionsExt, symlink};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
struct RestoreMode {
|
||||
path: PathBuf,
|
||||
permissions: std::fs::Permissions,
|
||||
}
|
||||
|
||||
impl RestoreMode {
|
||||
fn set(path: &Path, mode: u32) -> Self {
|
||||
let permissions = std::fs::metadata(path).unwrap().permissions();
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)).unwrap();
|
||||
Self { path: path.to_path_buf(), permissions }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for RestoreMode {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::set_permissions(&self.path, self.permissions.clone());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_without_previews_does_not_require_composite_read_permission() {
|
||||
let root = temp_dir("composite-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved without previews".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
result.expect("saving without previews does not read composite");
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_cleans_stale_previews_through_search_only_root_and_composite() {
|
||||
let root = temp_dir("bundle-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let link = root.join("linked.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
symlink(&bundle, &link).unwrap();
|
||||
std::fs::write(bundle.join("thumb.png"), b"stale thumbnail").unwrap();
|
||||
std::fs::write(bundle.join("composite/preview.png"), b"stale composite").unwrap();
|
||||
let orphan = bundle.join("blobs").join(format!("{}.zst", "a".repeat(64)));
|
||||
std::fs::write(&orphan, b"unreferenced object").unwrap();
|
||||
let composite_mode = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let root_mode = RestoreMode::set(&bundle, 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved through linked root".into();
|
||||
let result = writer.save_dir(&changed, &link, &SaveOptions::default());
|
||||
drop(root_mode);
|
||||
drop(composite_mode);
|
||||
let stats = result.expect("cleanup needs directory traversal and write permission, not read");
|
||||
assert_eq!(stats.objects_removed, 1);
|
||||
assert!(!orphan.exists());
|
||||
assert!(!bundle.join("thumb.png").exists());
|
||||
assert!(!bundle.join("composite/preview.png").exists());
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_save_writes_current_preview_without_composite_read_permission() {
|
||||
let root = temp_dir("preview-search-only");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o300);
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "saved with preview".into();
|
||||
let opts = SaveOptions { composite: Some(Rgba8Image::new(2, 2)), ..Default::default() };
|
||||
let result = writer.save_dir(&changed, &bundle, &opts);
|
||||
drop(restricted);
|
||||
result.expect("writing a preview does not require listing its directory");
|
||||
assert!(std::fs::read(bundle.join("composite/preview.png")).unwrap().starts_with(b"\x89PNG\r\n\x1a\n"));
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_stale_preview_cleanup_preserves_the_previous_manifest() {
|
||||
let root = temp_dir("denied-preview-cleanup");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
let original = empty_doc();
|
||||
writer.save_dir(&original, &bundle, &SaveOptions::default()).unwrap();
|
||||
let preview = bundle.join("composite/preview.png");
|
||||
std::fs::write(&preview, b"stale composite").unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("composite"), 0o500);
|
||||
let permission_probe = bundle.join("composite/permission-probe");
|
||||
if std::fs::write(&permission_probe, b"probe").is_ok() {
|
||||
// An elevated test process may bypass directory permissions.
|
||||
std::fs::remove_file(permission_probe).unwrap();
|
||||
drop(restricted);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
return;
|
||||
}
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "must not commit".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
assert!(result.is_err(), "a required pre-commit cleanup failure is reported");
|
||||
assert_eq!(std::fs::read(preview).unwrap(), b"stale composite");
|
||||
assert_eq!(load_path(&bundle).unwrap(), original);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denied_object_cleanup_remains_best_effort_after_manifest_commit() {
|
||||
let root = temp_dir("denied-object-cleanup");
|
||||
let bundle = root.join("project.pcraft");
|
||||
let mut writer = PcraftWriter::new();
|
||||
writer.save_dir(&empty_doc(), &bundle, &SaveOptions::default()).unwrap();
|
||||
let orphan = bundle.join("tiles").join(format!("{}.zst", "d".repeat(64)));
|
||||
std::fs::write(&orphan, b"unreferenced object").unwrap();
|
||||
let restricted = RestoreMode::set(&bundle.join("tiles"), 0o500);
|
||||
let permission_probe = bundle.join("tiles/permission-probe");
|
||||
if std::fs::write(&permission_probe, b"probe").is_ok() {
|
||||
std::fs::remove_file(permission_probe).unwrap();
|
||||
drop(restricted);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
return;
|
||||
}
|
||||
let mut changed = empty_doc();
|
||||
changed.name = "committed despite housekeeping failure".into();
|
||||
let result = writer.save_dir(&changed, &bundle, &SaveOptions::default());
|
||||
drop(restricted);
|
||||
assert_eq!(result.unwrap().objects_removed, 0);
|
||||
assert!(orphan.exists());
|
||||
assert_eq!(load_path(&bundle).unwrap(), changed);
|
||||
std::fs::remove_dir_all(root).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -845,6 +845,26 @@ impl Compositor {
|
||||
self.prefix.forget(doc);
|
||||
}
|
||||
|
||||
/// [`Self::forget_doc`] for every document `keep` rejects: what the compositor holds for
|
||||
/// documents that were closed, however their canvas entry went (#4529).
|
||||
pub fn retain_docs(&mut self, keep: impl Fn(DocId) -> bool) {
|
||||
let mut gone: Vec<DocId> =
|
||||
self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).filter(|d| !keep(*d)).collect();
|
||||
gone.sort_by_key(|d| d.0);
|
||||
gone.dedup();
|
||||
for d in gone {
|
||||
self.forget_doc(d);
|
||||
}
|
||||
}
|
||||
|
||||
/// Documents the compositor holds pages, effect maps or a lower-stack composite for.
|
||||
pub fn held_docs(&self) -> Vec<DocId> {
|
||||
let mut docs: Vec<DocId> = self.residents.values().map(|r| r.doc).chain(self.fx.values().map(|e| e.doc)).chain(self.prefix.doc()).collect();
|
||||
docs.sort_by_key(|d| d.0);
|
||||
docs.dedup();
|
||||
docs
|
||||
}
|
||||
|
||||
/// GPU memory held by cached effect maps (bytes).
|
||||
pub fn fx_cache_bytes(&self) -> usize {
|
||||
self.fx.values().map(FxEntry::bytes).sum()
|
||||
|
||||
@@ -85,6 +85,11 @@ impl Prefix {
|
||||
}
|
||||
}
|
||||
|
||||
/// The document the cached composite belongs to, if any.
|
||||
pub(crate) fn doc(&self) -> Option<photocraft_doc::DocId> {
|
||||
self.context.as_ref().map(|d| d.id)
|
||||
}
|
||||
|
||||
pub(crate) fn prepare(&mut self, doc: &Document, plan: &Plan<'_>) -> Option<Checkpoint> {
|
||||
if self.budget == 0 {
|
||||
return None;
|
||||
|
||||
@@ -187,6 +187,27 @@ fn check(g: &mut Gpu, doc: &Document, what: &str) {
|
||||
diff_rect(g, doc, doc.bounds(), what).unwrap_or_else(|e| panic!("{e}"));
|
||||
}
|
||||
|
||||
/// Closing a document frees what the compositor holds for it, however its canvas entry went
|
||||
/// (#4529): `retain_docs` drops the resident pages, effect maps and lower-stack composite of
|
||||
/// documents that aren't open, and keeps the open ones.
|
||||
#[test]
|
||||
fn retain_docs_frees_closed_documents() {
|
||||
let Some(mut g) = gpu() else { return };
|
||||
let a = base_doc(64, 48);
|
||||
let mut b = base_doc(32, 32);
|
||||
b.id = photocraft_doc::DocId(a.id.0 + 1);
|
||||
for d in [&a, &b] {
|
||||
render_to_vec(&mut g.comp, &g.device, &g.queue, d, d.bounds()).expect("render");
|
||||
}
|
||||
assert_eq!(g.comp.held_docs(), vec![a.id, b.id]);
|
||||
g.comp.retain_docs(|d| d == b.id);
|
||||
assert_eq!(g.comp.held_docs(), vec![b.id], "only the open document is left");
|
||||
g.comp.retain_docs(|_| false);
|
||||
assert!(g.comp.held_docs().is_empty());
|
||||
assert_eq!(g.comp.composite_cache_bytes(), 0);
|
||||
check(&mut g, &a, "renders again after being forgotten");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_frame_renders() {
|
||||
// Regression: the first submission after device creation is dropped on some drivers
|
||||
|
||||
@@ -429,7 +429,12 @@ impl Mapper<'_> {
|
||||
}
|
||||
dual.mode = mask_mode(enum_value(db, "BlnM")).unwrap_or(MaskMode::Multiply);
|
||||
dual.flip = boolean(db, "Flip").unwrap_or(false);
|
||||
if let Some(v) = pct(db, "Spcn") {
|
||||
// The dual tip's own spacing (`Brsh › Spcn`) is what Photoshop's Dual Brush panel
|
||||
// shows. The `Spcn` beside it on the `dualBrush` object reads 100 % in Photoshop CC
|
||||
// presets whatever the panel says (#4809), so it only stands in for a tip without one.
|
||||
if obj(db, "Brsh").and_then(|t| pct(t, "Spcn")).is_none()
|
||||
&& let Some(v) = pct(db, "Spcn")
|
||||
{
|
||||
dual.spacing = v.clamp(0.01, 10.0);
|
||||
}
|
||||
dual.scatter = self.dynamic(obj(db, "scatterDynamics")).jitter;
|
||||
|
||||
@@ -399,3 +399,32 @@ fn low_depth_height_texture_brush_paints() {
|
||||
assert_eq!(covered, 36, "{mode}: the stroke painted {covered} of 36 pixels");
|
||||
}
|
||||
}
|
||||
|
||||
/// #4809: Photoshop CC presets store the dual tip's spacing in `dualBrush › Brsh › Spcn` and a
|
||||
/// `Spcn` of 100 % on the `dualBrush` object beside it; the tip's value is the panel's. A tip
|
||||
/// without one still takes the outer value.
|
||||
#[test]
|
||||
fn dual_brush_spacing_comes_from_its_tip() {
|
||||
let dual = |tip: Descriptor| {
|
||||
Descriptor::new("brushPreset")
|
||||
.with("Nm ", t("SPACING 10%"))
|
||||
.with("Brsh", Value::Descriptor(Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 30.0))))
|
||||
.with(
|
||||
"dualBrush",
|
||||
Value::Descriptor(
|
||||
Descriptor::new("dualBrush")
|
||||
.with("useDualBrush", Value::Boolean(true))
|
||||
.with("Brsh", Value::Descriptor(tip))
|
||||
.with("BlnM", en("BlnM", "Ovrl"))
|
||||
.with("Spcn", prc(100.0)),
|
||||
),
|
||||
)
|
||||
};
|
||||
let spacing = |preset: Descriptor| {
|
||||
let bytes = write_v6(2, &[], &[], &[preset], false).unwrap();
|
||||
read_abr(&bytes, "Test").unwrap().presets[0].brush.dual_brush.spacing
|
||||
};
|
||||
let tip = Descriptor::new("computedBrush").with("Dmtr", u(b"#Pxl", 40.0));
|
||||
assert!((spacing(dual(tip.clone().with("Spcn", prc(10.0)))) - 0.10).abs() < 1e-6, "the tip's 10 %, not the outer 100 %");
|
||||
assert!((spacing(dual(tip)) - 1.0).abs() < 1e-6, "no tip spacing: the outer value");
|
||||
}
|
||||
+30
-14
@@ -509,11 +509,12 @@ fn parse_black_white(d: &[u8]) -> Option<Adjustment> {
|
||||
/// (colour space + four u16), version 3 "4 bytes each for XYZ color"; then density (u32 percent)
|
||||
/// and preserve luminosity (1 byte).
|
||||
///
|
||||
/// The spec gives no scale for the XYZ values. They are read as D50 XYZ (the ICC PCS) with
|
||||
/// 1.0 = 32768, the ICC 16-bit PCSXYZ encoding. That is inferred, not documented: the
|
||||
/// Photoshop CS2 file in #3777 holds (24191, 25002, 3827), a bright warm yellow at this scale,
|
||||
/// and rendering it against Photoshop's export fit best between 30000 and 32768 (1.0 = 65536,
|
||||
/// a dull olive, was clearly worse).
|
||||
/// The spec gives no scale for the XYZ values. They are read as XYZ relative to the D50 white
|
||||
/// (X / 0.9642, Y, Z / 0.8249) with 1.0 = 32768, so white is stored as (32768, 32768, 32768).
|
||||
/// That is inferred, not documented: decoded this way, every version 3 colour in the Photoshop
|
||||
/// CS2 files of #3777 and #4940 is exactly a Photoshop preset (the Yellow filter holds
|
||||
/// (24191, 25002, 3827) and decodes to #F9E31C, Warming Filter (85) holds (15548, 12029, 0)
|
||||
/// and decodes to #EC8A00); reading them as absolute XYZ gives #FFE03A and #F18600.
|
||||
const PHFL_XYZ_ONE: f32 = 32768.0;
|
||||
|
||||
fn parse_photo_filter(d: &[u8]) -> Option<Adjustment> {
|
||||
@@ -527,11 +528,14 @@ fn parse_photo_filter(d: &[u8]) -> Option<Adjustment> {
|
||||
(crate::channel_map::decode_color(space, c).to_rgb(), 12)
|
||||
}
|
||||
3 => {
|
||||
let xyz = [be32(d, 2)?, be32(d, 6)?, be32(d, 10)?].map(|v| v as f32 / PHFL_XYZ_ONE);
|
||||
// Real colours stay below about 1.0; anything past 2.0 is not an XYZ colour.
|
||||
if xyz.iter().any(|v| *v > 2.0) {
|
||||
let rel = [be32(d, 2)?, be32(d, 6)?, be32(d, 10)?].map(|v| v as f32 / PHFL_XYZ_ONE);
|
||||
// Relative to the white, real colours stay below about 2.0 (Cooling Filter (82)
|
||||
// reaches 1.99 on Z); anything past that is not an XYZ colour.
|
||||
if rel.iter().any(|v| *v > 2.0) {
|
||||
return None;
|
||||
}
|
||||
// Relative to the D50 white: bring it back to absolute D50 XYZ before converting.
|
||||
let xyz = [rel[0] * photocraft_color::convert::D50[0], rel[1], rel[2] * photocraft_color::convert::D50[2]];
|
||||
let lin = photocraft_color::convert::mat3_mul(&photocraft_color::convert::XYZ_D50_TO_SRGB, xyz);
|
||||
(lin.map(|v| photocraft_color::convert::linear_to_srgb(v.clamp(0.0, 1.0))), 14)
|
||||
}
|
||||
@@ -1168,25 +1172,37 @@ mod tests {
|
||||
let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } = parse(b"phfl", &lab, None, Channels::Rgb) else { panic!() };
|
||||
assert!(color.iter().all(|c| (c - 0.466).abs() < 0.01), "{color:?}");
|
||||
assert_eq!(density, 0.25);
|
||||
// Version 3: D50 XYZ, 1.0 = 32768. The ICC sRGB white point (D50) is white.
|
||||
let v3 = phfl_v3([31595, 32768, 27040], 100, true);
|
||||
// Version 3: XYZ relative to the D50 white, 1.0 = 32768. White is (32768, 32768, 32768).
|
||||
let v3 = phfl_v3([32768, 32768, 32768], 100, true);
|
||||
let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &v3, None, Channels::Rgb) else { panic!() };
|
||||
assert!(color.iter().all(|c| (c - 1.0).abs() < 0.005), "{color:?}");
|
||||
assert_eq!(density, 1.0);
|
||||
// Photoshop's Warming Filter (85) preset, sRGB #EC8A00, is D50 XYZ (15193, 12086, 1192).
|
||||
// Photoshop's Warming Filter (85) preset, sRGB #EC8A00: the CS2 file of #4940 stores it
|
||||
// relative to the D50 white as (15548, 12029, 0).
|
||||
let Adjustment::PhotoFilter { color, density, preserve_luminosity: false } =
|
||||
parse(b"phfl", &phfl_v3([15193, 12086, 1192], 25, false), None, Channels::Rgb)
|
||||
parse(b"phfl", &phfl_v3([15548, 12029, 0], 25, false), None, Channels::Rgb)
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let expected = [0xecu8, 0x8a, 0x00].map(|v| f32::from(v) / 255.0);
|
||||
assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}");
|
||||
assert_eq!(density, 0.25);
|
||||
// The block from #3777 (Photoshop CS2): a warm yellow, density 63 %, preserve luminosity.
|
||||
// The block from #3777 (Photoshop CS2): the Yellow filter preset, #F9E31C, density 63 %.
|
||||
let issue = [0, 3, 0, 0, 0x5e, 0x7f, 0, 0, 0x61, 0xaa, 0, 0, 0x0e, 0xf3, 0, 0, 0, 0x3f, 1, 0];
|
||||
let Adjustment::PhotoFilter { color, density, preserve_luminosity: true } = parse(b"phfl", &issue, None, Channels::Rgb) else { panic!() };
|
||||
assert!(color[0] > color[1] && color[1] > color[2] && color[1] > 0.8 && color[2] < 0.3, "{color:?}");
|
||||
let expected = [0xf9u8, 0xe3, 0x1c].map(|v| f32::from(v) / 255.0);
|
||||
assert!(color.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{color:?}");
|
||||
assert_eq!(density, 0.63);
|
||||
// Cooling Filter (82) from #4940: a deep blue outside sRGB; its Z stays under the 2.0
|
||||
// garbage guard and the colour clamps to (0, 181, 255).
|
||||
let Adjustment::PhotoFilter { color: cooling, density, preserve_luminosity: true } =
|
||||
parse(b"phfl", &phfl_v3([5327, 9584, 65357], 72, true), None, Channels::Rgb)
|
||||
else {
|
||||
panic!("Cooling Filter (82) must parse")
|
||||
};
|
||||
let expected = [0u8, 181, 255].map(|v| f32::from(v) / 255.0);
|
||||
assert!(cooling.iter().zip(expected).all(|(got, want)| (got - want).abs() < 1.5 / 255.0), "{cooling:?}");
|
||||
assert_eq!(density, 0.72);
|
||||
// The 19-byte form (no trailing pad) parses the same.
|
||||
assert_eq!(parse(b"phfl", &issue[..19], None, Channels::Rgb), parse(b"phfl", &issue, None, Channels::Rgb));
|
||||
// Version 3 is read, never written: an edited filter is saved as version 2 and keeps its colour.
|
||||
|
||||
@@ -312,8 +312,10 @@ fn document_to_image_for(doc: &Document, warnings: &mut Vec<String>, cmyk_target
|
||||
let canvas = doc.bounds();
|
||||
let fmt = doc.pixel_format();
|
||||
let n = (w as usize) * (h as usize);
|
||||
// Lab has no flat-format layout here: Lab documents always go through the composite.
|
||||
let native = single_layer(doc).filter(|_| fmt.mode != ColorMode::Lab);
|
||||
// Lab has no flat-format layout here: Lab documents always go through the composite, which
|
||||
// flattens nothing when there is a single plain layer.
|
||||
let single = single_layer(doc);
|
||||
let native = single.filter(|_| fmt.mode != ColorMode::Lab);
|
||||
let mut icc = doc.icc_profile.as_ref().map(|i| i.to_vec());
|
||||
let img = if let Some(s) = native {
|
||||
// Native path: keep model and depth. The surface's encoded samples are the codec's raw
|
||||
@@ -340,8 +342,10 @@ fn document_to_image_for(doc: &Document, warnings: &mut Vec<String>, cmyk_target
|
||||
}
|
||||
Image::from_raw(w, h, layout, csample(fmt.sample), data)?
|
||||
} else {
|
||||
let count = doc.layer_count();
|
||||
warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept"));
|
||||
if single.is_none() {
|
||||
let count = doc.layer_count();
|
||||
warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept"));
|
||||
}
|
||||
let cmyk = fmt.mode == ColorMode::Cmyk && cmyk_target;
|
||||
// Only a CMYK target needs the document's profile; RGB-only targets keep the compositor's
|
||||
// own handling (built-in coated CMYK when the embedded profile is unusable).
|
||||
|
||||
@@ -508,7 +508,10 @@ pub fn merged_composite(file: &PsdFile) -> Result<Vec<[f32; 4]>, IoError> {
|
||||
}
|
||||
let l = doc.layers.first().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
|
||||
let s = l.surface().ok_or_else(|| IoError::Unsupported("no merged image".into()))?;
|
||||
Ok(photocraft_compose::surface_to_buffer(s, doc.bounds()).px)
|
||||
// CMYK reads through the file's own profile, as the compositor reads its layers, so a tagged
|
||||
// file's merged image and its composite are compared in the same colours.
|
||||
let cmyk = photocraft_compose::cmyk_space(&doc);
|
||||
Ok(photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || photocraft_compose::surface_to_buffer(s, doc.bounds()).px))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -60,6 +60,8 @@ struct Ex {
|
||||
cmyk: bool,
|
||||
version: Version,
|
||||
next_id: u32,
|
||||
/// Reserved imported layer and generated divider IDs.
|
||||
used_ids: std::collections::HashSet<u32>,
|
||||
/// PSD ids assigned to document layers (kept from `psd_id` when unique).
|
||||
layer_ids: std::collections::HashMap<photocraft_doc::LayerId, u32>,
|
||||
/// The generated `Txt2` object number of each type layer (a preserved `TySh` keeps its own
|
||||
@@ -363,10 +365,14 @@ impl Ex {
|
||||
(MaskData::Mask(pm), Some(self.encode(-2, &plane, w, h)))
|
||||
}
|
||||
|
||||
/// Ids for section dividers: above every layer id.
|
||||
/// Prefer numbers above imported layer IDs, wrapping safely at u32::MAX.
|
||||
fn fresh_id(&mut self) -> u32 {
|
||||
self.next_id += 1;
|
||||
self.next_id
|
||||
loop {
|
||||
self.next_id = self.next_id.wrapping_add(1).max(1);
|
||||
if self.used_ids.insert(self.next_id) {
|
||||
return self.next_id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_id(&mut self, l: &Layer) -> u32 {
|
||||
@@ -1444,6 +1450,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
cmyk: fmt.mode == ColorMode::Cmyk,
|
||||
version,
|
||||
next_id: 0,
|
||||
used_ids: Default::default(),
|
||||
layer_ids: Default::default(),
|
||||
canvas: doc.bounds(),
|
||||
records: Vec::new(),
|
||||
@@ -1484,6 +1491,7 @@ fn document_to_psd_nested(doc: &Document, opts: &PsdExportOptions, depth: u32, c
|
||||
}
|
||||
}
|
||||
ex.next_id = used.iter().copied().max().unwrap_or(0);
|
||||
ex.used_ids = used;
|
||||
// Text objects' number in the generated `Txt2` (#1348): a preserved `TySh` keeps the
|
||||
// number it already names — its `Txt2` object must sit at that slot for `apply_txt2` —
|
||||
// and new layers get the next free number.
|
||||
@@ -1743,6 +1751,27 @@ mod tests {
|
||||
Document::new("size estimate", photocraft_geom::Size::new(width, height), ColorMode::Rgb, SampleType::U8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_divider_id_wraps_without_colliding_with_imported_layer_ids() {
|
||||
let mut doc = document(8, 8);
|
||||
let mut group = Layer::group("Imported group", vec![Layer::raster("Child", doc.pixel_format())]);
|
||||
group.psd_id = Some(u32::MAX);
|
||||
doc.layers.push(group);
|
||||
|
||||
let file = document_to_psd(&doc);
|
||||
let ids: Vec<u32> = file.layers().iter().filter_map(|layer| layer.layer_id()).collect();
|
||||
let unique: std::collections::HashSet<u32> = ids.iter().copied().collect();
|
||||
assert_eq!(ids.len(), 3, "group, child and closing divider");
|
||||
assert_eq!(unique.len(), ids.len(), "no generated ID may collide");
|
||||
assert!(unique.contains(&u32::MAX), "preserve the imported group ID");
|
||||
assert!(unique.contains(&1), "reuse the first unused positive ID on wrap");
|
||||
|
||||
let encoded = file.to_bytes().unwrap();
|
||||
let parsed = PsdFile::from_bytes(&encoded).unwrap();
|
||||
let reloaded_ids: std::collections::HashSet<u32> = parsed.layers().iter().filter_map(|layer| layer.layer_id()).collect();
|
||||
assert_eq!(unique, reloaded_ids);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_lr16_warns_on_import_and_is_not_saved_twice() {
|
||||
// #2700: a 16-bit file whose Lr16 block claims five layers but holds none.
|
||||
|
||||
@@ -233,3 +233,37 @@ fn layered_tiff_keeps_its_existing_cmyk_psd_composite_path() {
|
||||
assert_eq!(tag(&result.bytes, 338), Some(2));
|
||||
assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| (px[4] - 0.5).abs() < 0.0001));
|
||||
}
|
||||
|
||||
/// A tagged CMYK file's merged image reads through its own profile, as the compositor reads the
|
||||
/// layers, so the two are compared in the same colours (the oracle tests rely on it: psd-tools'
|
||||
/// tagged CMYK files were 95–100% off before).
|
||||
#[test]
|
||||
fn merged_composite_of_a_tagged_cmyk_file_reads_through_its_profile() {
|
||||
use photocraft_cms::synth::{CmykParams, cmyk_profile};
|
||||
use photocraft_color::convert::{CmykSpace, cmyk_to_rgb, with_cmyk_space};
|
||||
let mut doc = Document::new("tagged", Size::new(6, 4), ColorMode::Cmyk, SampleType::U8);
|
||||
let profile =
|
||||
cmyk_profile(&CmykParams { description: "Merged Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() });
|
||||
doc.icc_profile = Some(profile.to_bytes());
|
||||
let mut surface = Surface::new(photocraft_color::PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false));
|
||||
for x in 0..6 {
|
||||
for y in 0..4 {
|
||||
surface.write_pixel(x, y, &[x as f32 / 5.0, y as f32 / 3.0, 0.4, (x * y) as f32 / 15.0]);
|
||||
}
|
||||
}
|
||||
doc.layers.push(Layer::new("Background", LayerContent::Raster(surface)));
|
||||
let psd = export(&doc, "psd", &ExportOptions::default()).unwrap();
|
||||
let file = photocraft_psd::PsdFile::from_bytes(&psd.bytes).unwrap();
|
||||
let merged = photocraft_io::merged_composite(&file).unwrap();
|
||||
// The merged image's own inks (planar, 255 = no ink), shown through the file's profile.
|
||||
let raw = file.decode_merged().unwrap();
|
||||
let plane = 6 * 4;
|
||||
let space = CmykSpace::for_profile(doc.icc_profile.as_ref());
|
||||
assert!(space.is_some(), "a profile other than the built-in coated CMYK");
|
||||
let shown: Vec<[f32; 3]> =
|
||||
with_cmyk_space(space.as_ref(), || (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect());
|
||||
let builtin: Vec<[f32; 3]> = (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect();
|
||||
let apart = |a: &[[f32; 3]]| merged.iter().zip(a).flat_map(|(m, s)| (0..3).map(move |c| (m[c] - s[c]).abs())).fold(0.0f32, f32::max);
|
||||
assert!(apart(&shown) < 1e-4, "merged image read through its profile: {}", apart(&shown));
|
||||
assert!(apart(&builtin) > 0.01, "the built-in profile would show it differently");
|
||||
}
|
||||
@@ -963,3 +963,20 @@ fn tga_default_bits_follow_the_alpha_channels() {
|
||||
assert_eq!(tga_default_bits(&with_alpha_channel(d, "Alpha 1")), TgaBits::Bits32);
|
||||
assert_eq!((TgaBits::from_bits(24), TgaBits::from_bits(32), TgaBits::from_bits(16)), (Some(TgaBits::Bits24), Some(TgaBits::Bits32), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lab_document_with_one_layer_is_not_reported_as_flattened() {
|
||||
// Lab always goes through the sRGB composite, but a lone layer loses nothing to it.
|
||||
let d = single(ColorMode::Lab, SampleType::U8, false);
|
||||
for ext in ["tif", "png", "jpg"] {
|
||||
let r = export(&d, ext, &ExportOptions::default()).unwrap();
|
||||
assert!(r.warnings.iter().all(|w| !w.contains("flattened")), "{ext}: {:?}", r.warnings);
|
||||
assert!(r.warnings.iter().any(|w| w.contains("Lab composite written as sRGB")), "{ext}: {:?}", r.warnings);
|
||||
}
|
||||
// Two layers are flattened, and say so.
|
||||
let mut two = single(ColorMode::Lab, SampleType::U8, false);
|
||||
let fmt = two.pixel_format();
|
||||
two.layers.push(raster("Top", fmt, two.bounds(), 5, true));
|
||||
let r = export(&two, "tif", &ExportOptions::default()).unwrap();
|
||||
assert!(r.warnings.iter().any(|w| w.contains("2 layer(s) flattened")), "{:?}", r.warnings);
|
||||
}
|
||||
@@ -27,7 +27,7 @@ fn png_with_unequal_axes_reports_the_dropped_vertical_resolution() {
|
||||
assert!((r.document.resolution_dpi - 300.0).abs() < 0.01, "{}", r.document.resolution_dpi);
|
||||
let notes = resolution_notes(&r);
|
||||
assert_eq!(notes.len(), 1, "{:?}", r.warnings);
|
||||
assert!(notes[0].contains("150.01") && notes[0].contains("300.00"), "{notes:?}");
|
||||
assert!(notes[0].contains("150.00") && notes[0].contains("300.00"), "{notes:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -41,9 +41,15 @@ impl ImageData {
|
||||
|
||||
/// Decodes and returns a single channel plane.
|
||||
pub fn decode_channel(&self, header: &Header, index: usize) -> Result<Vec<u8>> {
|
||||
let invalid = || crate::error::PsdError::invalid(format!("no merged channel {index}"));
|
||||
if index >= usize::from(header.channels) {
|
||||
return Err(invalid());
|
||||
}
|
||||
let plane = header.row_bytes().checked_mul(header.height as usize).ok_or_else(invalid)?;
|
||||
let start = index.checked_mul(plane).ok_or_else(invalid)?;
|
||||
let end = start.checked_add(plane).ok_or_else(invalid)?;
|
||||
let all = self.decode(header)?;
|
||||
let plane = header.row_bytes() * header.height as usize;
|
||||
all.get(index * plane..(index + 1) * plane).map(<[u8]>::to_vec).ok_or_else(|| crate::error::PsdError::invalid(format!("no merged channel {index}")))
|
||||
all.get(start..end).map(<[u8]>::to_vec).ok_or_else(invalid)
|
||||
}
|
||||
|
||||
pub(crate) fn read(r: &mut Reader<'_>, header: &Header) -> Result<Self> {
|
||||
@@ -55,3 +61,25 @@ impl ImageData {
|
||||
Ok(ImageData { compression, data })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::header::{ColorMode, Version};
|
||||
|
||||
#[test]
|
||||
fn merged_channels_reject_invalid_indices_without_decoding_or_overflow() {
|
||||
let header = Header::new(Version::Psd, 2, 1, 3, 8, ColorMode::Rgb);
|
||||
let data = ImageData { compression: Compression::Raw, data: vec![10, 11, 20, 21, 30, 31] };
|
||||
for (index, expected) in [(0, [10, 11]), (1, [20, 21]), (2, [30, 31])] {
|
||||
assert_eq!(data.decode_channel(&header, index).unwrap(), expected.to_vec());
|
||||
}
|
||||
for index in [3, 4, usize::MAX] {
|
||||
assert!(data.decode_channel(&header, index).is_err(), "invalid channel {index}");
|
||||
}
|
||||
// Reject an invalid index before trying to decode corrupt merged data.
|
||||
let corrupt = ImageData { compression: Compression::Raw, data: vec![] };
|
||||
let err = corrupt.decode_channel(&header, usize::MAX).unwrap_err().to_string();
|
||||
assert!(err.contains("no merged channel"), "{err}");
|
||||
}
|
||||
}
|
||||
@@ -747,7 +747,8 @@ impl Surface {
|
||||
/// The surface moved by whole pixels: its encoded samples copied tile to tile (no float
|
||||
/// round trip, no intermediate buffer); moves by whole tiles share the tiles themselves, and
|
||||
/// a target tile read entirely from tiles of one single pixel value shares one such tile (the
|
||||
/// inside of a solid fill stays one copy-on-write tile however often it moves).
|
||||
/// inside of a solid fill stays one copy-on-write tile however often it moves). A tile it
|
||||
/// copies that ends up holding only the default pixel isn't stored.
|
||||
/// `content` must hold every pixel that isn't the default one (`content_bounds`, say): only
|
||||
/// tiles it reaches are kept.
|
||||
pub fn translated(&self, dx: i32, dy: i32, content: Rect) -> Surface {
|
||||
@@ -763,6 +764,8 @@ impl Surface {
|
||||
let targets: std::collections::BTreeSet<TileCoord> = sources().flat_map(|(c, _)| c.rect().translate(dx, dy).intersect(&moved).tiles()).collect();
|
||||
let mut uniform = UniformTiles::default();
|
||||
let zero = vec![0u8; bpp];
|
||||
// One tile row of the default pixel, to compare a finished tile with a row at a time.
|
||||
let default_row = self.default_pixel.repeat(TILE_SIZE.unsigned_abs() as usize);
|
||||
for dc in targets {
|
||||
let dr = dc.rect();
|
||||
let sr = dr.translate(dx.saturating_neg(), dy.saturating_neg());
|
||||
@@ -774,7 +777,10 @@ impl Surface {
|
||||
&& content.contains_rect(&sr)
|
||||
&& sr.tiles().all(|sc| self.tiles.contains_key(&sc));
|
||||
if covered && let Some(shared) = uniform.window(self, sr) {
|
||||
out.tiles.insert(dc, shared);
|
||||
// A tile of only the default pixel is left out, as `prune` would.
|
||||
if shared.data.get(..bpp) != Some(&*self.default_pixel) {
|
||||
out.tiles.insert(dc, shared);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// A covered target is overwritten whole, so skip filling it with the default pixel.
|
||||
@@ -795,7 +801,11 @@ impl Surface {
|
||||
}
|
||||
}
|
||||
}
|
||||
out.tiles.insert(dc, Arc::new(tile));
|
||||
// A target that got only default pixels isn't stored, as `prune` would drop it. Checked
|
||||
// after the copy, a row at a time: a tile with content stops at its first such row.
|
||||
if tile.data.chunks(default_row.len()).any(|row| row != default_row) {
|
||||
out.tiles.insert(dc, Arc::new(tile));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -1427,6 +1437,43 @@ mod tests {
|
||||
let _ = s.translated(i32::MIN + 1, 3, all);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translated_stores_no_tiles_of_only_the_default_pixel() {
|
||||
let only_default = |t: &Surface| {
|
||||
let dp = t.default_pixel();
|
||||
t.tiles().filter(|(c, _)| t.read_region(c.rect()).chunks_exact(dp.len()).all(|p| p == dp.as_slice())).count()
|
||||
};
|
||||
// Two blocks a few tiles apart, moved off the tile grid and back: the default-pixel edges
|
||||
// of their tiles land on tiles of their own, which aren't stored.
|
||||
for fmt in [PixelFormat::RGBA8, PixelFormat::RGBA16, PixelFormat::RGBA32F, PixelFormat::GRAY8] {
|
||||
for default in [0.0, 0.25] {
|
||||
let mut s = Surface::with_default(fmt, &vec![default; fmt.channels()]);
|
||||
s.fill_rect(Rect::new(0, 0, 300, 300), &vec![1.0; fmt.channels()]);
|
||||
s.fill_rect(Rect::new(2000, 1000, 2300, 1300), &vec![0.5; fmt.channels()]);
|
||||
let all = Rect::new(-600, -600, 3000, 2000);
|
||||
let mut t = s.clone();
|
||||
for (dx, dy) in [(100, 56), (-100, -56), (10, 7), (-3, 40), (130, -90), (-137, 43)] {
|
||||
let moved = t.translated(dx, dy, t.content_bounds());
|
||||
assert_eq!(moved.read_region(all), t.read_region(all.translate(-dx, -dy)), "{fmt:?} over {default} by ({dx}, {dy})");
|
||||
assert_eq!(only_default(&moved), 0, "{fmt:?} over {default} by ({dx}, {dy})");
|
||||
t = moved;
|
||||
}
|
||||
assert_eq!(t.read_region(all), s.read_region(all), "{fmt:?} over {default}: back where it started");
|
||||
assert_eq!(t.tile_count(), s.tile_count(), "{fmt:?} over {default}: back where it started");
|
||||
}
|
||||
}
|
||||
// Stored tiles of the default pixel inside `content`: the targets that would share one of
|
||||
// them (#4414's uniform windows) are left out too.
|
||||
let mut s = Surface::with_default(PixelFormat::GRAY8, &[0.25]);
|
||||
s.fill_rect(Rect::new(0, 0, 1024, 1024), &[0.25]);
|
||||
s.write_pixel(600, 600, &[1.0]);
|
||||
let content = Rect::new(0, 0, 1024, 1024);
|
||||
let t = s.translated(10, 7, content);
|
||||
assert_eq!(only_default(&t), 0);
|
||||
assert_eq!(t.tile_count(), 1);
|
||||
assert_eq!(t.read_region(Rect::new(-20, -20, 1100, 1100)), s.read_region(Rect::new(-30, -27, 1090, 1093)));
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#[test]
|
||||
fn region_write_read_roundtrip(x in -600i32..600, y in -600i32..600, w in 1u32..90, h in 1u32..90, seed in any::<u32>()) {
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
//! The lock beside a section name keeps that section's settings when another preset is picked
|
||||
//! (`locks` in the brush, applied by the engine). The Brushes tab lives in [`crate::brushes_tab`].
|
||||
|
||||
use egui::{Color32, CornerRadius, RichText, Sense, Stroke, vec2};
|
||||
use egui::{Color32, CornerRadius, Sense, Stroke, vec2};
|
||||
use photocraft_engine::BrushSettings;
|
||||
use photocraft_engine::paint;
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -359,9 +359,8 @@ fn settings_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
widgets::vline(ui, 482.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(WIDTH - 190.0);
|
||||
let name = SECTIONS.get(section).map_or("Brush Tip Shape", |entry| entry.0);
|
||||
ui.label(RichText::new(tl!(name)).font(theme::semibold(12.5)).color(t.text));
|
||||
ui.add_space(6.0);
|
||||
// No title above the options (#3477): the selected row in the list names them, as
|
||||
// in Photoshop, and the line is better spent on the options.
|
||||
let on = section_flag(&mut b, section).is_none_or(|f| *f);
|
||||
egui::ScrollArea::vertical().id_salt(("brush-section", section)).max_height(450.0).auto_shrink([false, false]).show(ui, |ui| {
|
||||
ui.set_width(WIDTH - 204.0);
|
||||
|
||||
@@ -560,6 +560,51 @@ fn toggle_value(app: &PhotocraftApp, section: usize) -> bool {
|
||||
brush.pointer(path).and_then(Value::as_bool).expect("the checkbox has a boolean brush setting")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hue_jitter_amount_edits_keep_percentage_units_and_command_routing() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::{NodeT, Queryable};
|
||||
|
||||
let mut h = harness(0, 5);
|
||||
h.state_mut()
|
||||
.session
|
||||
.execute(
|
||||
"tools.setBrush",
|
||||
json!({"brush": {"colorDynamics": {
|
||||
"enabled": true, "hueJitter": 0.37, "saturationJitter": 0.23, "brightnessJitter": 0.41, "purity": -0.16
|
||||
}}}),
|
||||
)
|
||||
.unwrap();
|
||||
let before = h.state().session.tools.brush.clone();
|
||||
h.run_steps(2);
|
||||
let field = h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().numeric_value() == Some(37.0)).unwrap();
|
||||
let center = field.rect().center();
|
||||
field.click();
|
||||
h.key_press(egui::Key::ArrowUp);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().session.tools.brush.color_dynamics.hue_jitter, 0.38);
|
||||
h.key_press(egui::Key::Enter);
|
||||
// Click near the high end of the track, then beyond its right edge while dragging.
|
||||
let from = egui::pos2(center.x, center.y + 24.0);
|
||||
h.event(egui::Event::PointerMoved(from));
|
||||
h.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(1);
|
||||
let to = from + vec2(200.0, 0.0);
|
||||
h.event(egui::Event::PointerMoved(to));
|
||||
h.run_steps(1);
|
||||
h.event(egui::Event::PointerButton { pos: to, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
|
||||
h.run_steps(2);
|
||||
let mut expected = before;
|
||||
expected.color_dynamics.hue_jitter = 1.0;
|
||||
assert_eq!(h.state().session.tools.brush, expected, "the amount clamps at 100% and preserves neighboring settings");
|
||||
assert_eq!(last_journal(h.state()).unwrap().0, "tools.setBrush");
|
||||
let mut replay = photocraft_engine::Session::new();
|
||||
for (id, params) in h.state().session.journal.clone() {
|
||||
replay.execute(&id, params).unwrap();
|
||||
}
|
||||
assert_eq!(replay.tools.brush, expected, "the edit remains replayable through the engine");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkbox_only_rows_toggle_without_changing_the_selected_controls() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -992,7 +1037,7 @@ fn app_harness_with_language(lang: crate::i18n::Lang) -> Harness<'static, Photoc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn brush_sections_paint_simplified_chinese_labels_and_heading() {
|
||||
fn brush_sections_paint_simplified_chinese_labels() {
|
||||
fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => out.push(text.galley.job.text.clone()),
|
||||
@@ -1017,8 +1062,27 @@ fn brush_sections_paint_simplified_chinese_labels_and_heading() {
|
||||
assert!(painted.iter().any(|s| s == translated), "{name} must paint as {translated}");
|
||||
assert!(!painted.iter().any(|s| s == name), "{name} must not paint in English");
|
||||
}
|
||||
let heading = crate::i18n::tr(zh, "Brush Tip Shape");
|
||||
assert_eq!(painted.iter().filter(|s| s.as_str() == heading).count(), 2, "both the section row and heading are translated");
|
||||
}
|
||||
|
||||
/// #3477: the options pane has no title of its own. The selected row in the section list is the
|
||||
/// only place the section's name is painted.
|
||||
#[test]
|
||||
fn options_pane_does_not_repeat_the_selected_sections_name() {
|
||||
fn collect_text(shape: &egui::Shape, out: &mut Vec<String>) {
|
||||
match shape {
|
||||
egui::Shape::Text(text) => out.push(text.galley.job.text.clone()),
|
||||
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect_text(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for (section, (name, _)) in SECTIONS.iter().enumerate().take(CHECKBOX_ONLY_START) {
|
||||
let h = harness(0, section);
|
||||
let mut painted = Vec::new();
|
||||
for shape in &h.output().shapes {
|
||||
collect_text(&shape.shape, &mut painted);
|
||||
}
|
||||
assert_eq!(painted.iter().filter(|s| s.as_str() == *name).count(), 1, "{name} is painted once, in the section list");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -512,10 +512,7 @@ fn color_dynamics(ui: &mut egui::Ui, b: &mut BrushSettings) {
|
||||
widgets::checkbox(ui, &mut c.per_tip, tl!("Apply Per Tip"));
|
||||
ui.add_space(6.0);
|
||||
dynamic(ui, "brush-fgbg-ctl", tl!("Foreground/Background Jitter"), &mut c.fg_bg, 1.0, None, false);
|
||||
let mut h = (c.hue_jitter * 100.0).round();
|
||||
if widgets::slider_row(ui, tl!("Hue Jitter"), &mut h, 0.0..=100.0, "%", Some(&widgets::hue_stops())).changed() {
|
||||
c.hue_jitter = (h.round() / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
pct(ui, tl!("Hue Jitter"), &mut c.hue_jitter, 1.0);
|
||||
pct(ui, tl!("Saturation Jitter"), &mut c.saturation_jitter, 1.0);
|
||||
pct(ui, tl!("Brightness Jitter"), &mut c.brightness_jitter, 1.0);
|
||||
signed_pct(ui, tl!("Purity"), &mut c.purity, -1.0, 1.0);
|
||||
@@ -648,6 +645,29 @@ mod tests {
|
||||
h
|
||||
}
|
||||
|
||||
/// #3825: jitter is an amount, not a hue selector; it uses the themed amount track.
|
||||
#[test]
|
||||
fn hue_jitter_paints_an_amount_track_in_every_theme() {
|
||||
for kind in theme::ThemeKind::ALL {
|
||||
let mut b = BrushSettings::default();
|
||||
b.color_dynamics.hue_jitter = 0.37;
|
||||
let mut h = section_harness(5, b.clone());
|
||||
crate::PhotocraftApp::setup_context(&h.ctx, kind);
|
||||
h.run_steps(3);
|
||||
let label = h.get_by_label("Hue Jitter").rect();
|
||||
let t = Tokens::get(&h.ctx);
|
||||
assert!(
|
||||
h.output().shapes.iter().any(|c| matches!(&c.shape, egui::Shape::Rect(r)
|
||||
if r.rect.width() > 150.0 && (r.rect.height() - 3.0).abs() < 0.1
|
||||
&& r.rect.top() > label.bottom() && r.rect.bottom() < label.bottom() + 30.0
|
||||
&& r.fill == t.field_border)),
|
||||
"{kind:?}: Hue Jitter paints the same neutral track as other percentage amounts"
|
||||
);
|
||||
assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().numeric_value() == Some(37.0)));
|
||||
assert_eq!(h.state(), &b, "rendering does not change saved brush settings");
|
||||
}
|
||||
}
|
||||
|
||||
fn set_controls(b: &mut BrushSettings, control: Control) {
|
||||
for d in [
|
||||
&mut b.shape_dynamics.size,
|
||||
|
||||
@@ -475,6 +475,22 @@ fn darker(c: Color32, f: f32) -> Color32 {
|
||||
Color32::from_rgba_unmultiplied((r as f32 * f).round() as u8, (g as f32 * f).round() as u8, (b as f32 * f).round() as u8, a)
|
||||
}
|
||||
|
||||
/// Where a card's tip thumbnail goes in its `cell`. `number_h` is the height of the size number
|
||||
/// under it, `None` on compact cards (no number: the tip takes the cell whole). Otherwise the
|
||||
/// number keeps a band at the bottom of the cell and the tip is centred in what's left above it,
|
||||
/// at [`CARD_TIP_BASE`] × `scale` or that room's side, whichever is smaller, times the preset's
|
||||
/// [`crate::brush_sections::thumb_scale`]: big brushes still read bigger than small ones, and
|
||||
/// none of them reaches down over the number.
|
||||
fn card_tip_rect(cell: egui::Rect, number_h: Option<f32>, size: f32, scale: f32) -> egui::Rect {
|
||||
let Some(number_h) = number_h else {
|
||||
return egui::Rect::from_center_size(cell.center(), egui::Vec2::splat((cell.width().min(cell.height()) - 2.0).max(1.0)));
|
||||
};
|
||||
// The number sits 1 pt off the cell's bottom, with a 1 pt gap above it.
|
||||
let room = egui::Rect::from_min_max(cell.min, pos2(cell.right(), (cell.bottom() - number_h - 2.0).max(cell.top())));
|
||||
let side = (CARD_TIP_BASE * scale).min(room.width().min(room.height())).max(0.0) * crate::brush_sections::thumb_scale(size);
|
||||
egui::Rect::from_center_size(room.center(), egui::Vec2::splat(if side.is_finite() { side.max(1.0) } else { 1.0 }))
|
||||
}
|
||||
|
||||
/// One preset in the Brush Preset picker: a 2 × 2 grid whose bottom row (the name) spans both
|
||||
/// columns — tip at the top left, stroke preview at the top right. A part that's off loses its
|
||||
/// cell (the other takes the room): with only the tip and the name on, the name moves into the
|
||||
@@ -545,18 +561,13 @@ fn preset_card(
|
||||
let tip_w = if tip_only { top.width() } else { (CARD_TIP_W * scale).min(top.width() * 0.5) };
|
||||
let cell = egui::Rect::from_min_size(top.left_top(), vec2(tip_w, top_h));
|
||||
let tip = brush_preview::tip_texture(ui.ctx(), &format!("brushes-tip:{}", p.name), &pb.tip, (pb.hardness, pb.angle, pb.roundness), 36, t.text);
|
||||
let side = if compact { (cell.width().min(cell.height()) - 2.0).max(1.0) } else { CARD_TIP_BASE * scale * crate::brush_sections::thumb_scale(pb.size) };
|
||||
let center = if compact { cell.center() } else { pos2(cell.center().x, cell.center().y - 2.0 * scale_h) };
|
||||
let tr = egui::Rect::from_center_size(center, vec2(side, side));
|
||||
let number =
|
||||
(!compact).then(|| ui.painter().layout_no_wrap(format!("{}", pb.size.round() as i64), egui::FontId::proportional(CARD_NUM_FONT), t.text_faint));
|
||||
let tr = card_tip_rect(cell, number.as_ref().map(|g| g.size().y), pb.size, scale);
|
||||
ui.painter().image(tip.id(), tr, full_uv(), Color32::WHITE);
|
||||
if !compact {
|
||||
ui.painter().text(
|
||||
pos2(cell.center().x, cell.bottom() - 1.0),
|
||||
egui::Align2::CENTER_BOTTOM,
|
||||
format!("{}", pb.size.round() as i64),
|
||||
egui::FontId::proportional(CARD_NUM_FONT),
|
||||
t.text_faint,
|
||||
);
|
||||
if let Some(g) = number {
|
||||
let at = pos2(cell.center().x - g.size().x / 2.0, cell.bottom() - 1.0 - g.size().y);
|
||||
ui.painter().galley(at, g, t.text_faint);
|
||||
}
|
||||
x = cell.right();
|
||||
}
|
||||
|
||||
@@ -265,3 +265,56 @@ fn the_brushes_tab_grid_is_centred_past_its_indent() {
|
||||
h.run_steps(6);
|
||||
rows_are_centred(&h, PANEL_LIST.indent, 2);
|
||||
}
|
||||
|
||||
/// #4454: a card's size number sat under the tip thumbnail of any medium or large brush (the
|
||||
/// tip took up to 44.8 pt of a 42 pt cell, the number anchored to the cell's bottom), so the
|
||||
/// "30" of Hard Round and the "45" of Soft Round couldn't be read. At every footer scale that
|
||||
/// shows numbers, in each card kind, the tip now stays above the number, and bigger brushes still
|
||||
/// get bigger tips.
|
||||
#[test]
|
||||
fn card_tips_never_cover_their_size_number() {
|
||||
let number_h = std::rc::Rc::new(std::cell::Cell::new(0.0_f32));
|
||||
let seen = number_h.clone();
|
||||
let mut h = Harness::new_ui(move |ui| {
|
||||
let g = ui.painter().layout_no_wrap("45".into(), egui::FontId::proportional(CARD_NUM_FONT), Color32::WHITE);
|
||||
seen.set(g.size().y);
|
||||
});
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run();
|
||||
let number_h = number_h.get();
|
||||
assert!(number_h > 8.0, "the number has a real height: {number_h}");
|
||||
let mut scale = CARD_COMPACT_SCALE + 0.01;
|
||||
while scale <= *crate::brush_picker::SCALE_RANGE.end() + 1e-3 {
|
||||
let scale_h = scale.max(CARD_MIN_H_SCALE);
|
||||
// The tip cell of a full card (name row under it), a tip-and-name card and a tip-only one,
|
||||
// as [`preset_card`] sizes them in a wide column.
|
||||
let cells = [
|
||||
vec2(CARD_TIP_W * scale, (CARD_MAX_H - CARD_PAD * 2.0 - CARD_NAME_H) * scale_h),
|
||||
vec2(CARD_TIP_W * scale, (CARD_TIP_NAME_H - CARD_PAD * 2.0) * scale_h),
|
||||
vec2((CARD_TIP_ONLY_W - 16.0) * scale, (CARD_TIP_ONLY_H - CARD_PAD * 2.0) * scale_h),
|
||||
];
|
||||
for size in cells {
|
||||
let cell = Rect::from_min_size(egui::pos2(10.0, 20.0), size);
|
||||
let number_top = cell.bottom() - 1.0 - number_h;
|
||||
let mut last = 0.0;
|
||||
for brush in [1.0, 5.0, 13.0, 30.0, 45.0, 100.0, 2500.0] {
|
||||
let tip = card_tip_rect(cell, Some(number_h), brush, scale);
|
||||
assert!(tip.bottom() <= number_top + 1e-3, "scale {scale}, cell {size:?}, {brush} px: tip {tip:?} reaches the number at {number_top}");
|
||||
assert!(cell.expand(1e-3).contains_rect(tip), "scale {scale}, {brush} px: tip {tip:?} leaves its cell {cell:?}");
|
||||
assert!(tip.width() >= last, "scale {scale}, {brush} px: a bigger brush gets a smaller tip");
|
||||
last = tip.width();
|
||||
}
|
||||
}
|
||||
scale += 0.05;
|
||||
}
|
||||
// The tip-only grid's cells are tall enough for the number: a big brush's tip still spans
|
||||
// the cell's width.
|
||||
let cell = Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(CARD_TIP_ONLY_W - 16.0, CARD_TIP_ONLY_H - CARD_PAD * 2.0));
|
||||
assert!((card_tip_rect(cell, Some(number_h), 45.0, 1.0).width() - cell.width()).abs() < 1e-3);
|
||||
// Compact cards: no number, the tip fills the cell; nonsense never makes a non-finite rect.
|
||||
assert_eq!(card_tip_rect(cell, None, 45.0, 0.5).width(), cell.width() - 2.0);
|
||||
for (n, size, scale) in [(f32::NAN, 30.0, 1.0), (500.0, f32::NAN, 1.0), (12.0, 30.0, f32::INFINITY), (12.0, -5.0, 0.0)] {
|
||||
let r = card_tip_rect(cell, Some(n), size, scale);
|
||||
assert!(r.min.is_finite() && r.max.is_finite(), "{n} {size} {scale}: {r:?}");
|
||||
}
|
||||
}
|
||||
@@ -122,10 +122,8 @@ pub(crate) fn interact(ui: &mut Ui, state: &mut CameraRawPreviewState, viewport:
|
||||
crate::tool_cursor::hand(ui.ctx(), false)
|
||||
} else if !zoom_tool {
|
||||
egui::CursorIcon::Crosshair
|
||||
} else if modifiers.alt {
|
||||
egui::CursorIcon::ZoomOut
|
||||
} else {
|
||||
egui::CursorIcon::ZoomIn
|
||||
crate::tool_cursor::zoom(ui.ctx(), modifiers.alt)
|
||||
});
|
||||
}
|
||||
let capture_id = response.id.with("zoom-capture");
|
||||
|
||||
+223
-30
@@ -944,8 +944,10 @@ pub fn doc_point_at(app: &PhotocraftApp, pos: Pos2) -> Option<[f64; 2]> {
|
||||
pub fn fit_view(view: &mut View, doc: &Document, area: Vec2, ppp: f32, aspect: f32) {
|
||||
let (w, h) = (doc.size.width as f32, doc.size.height as f32);
|
||||
let shown_w = w * if aspect.is_finite() && aspect > 0.0 { aspect } else { 1.0 };
|
||||
let points = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h).min(1.0);
|
||||
let zoom = crate::zoom_levels::clamp(points * ppp, [doc.size.width, doc.size.height]);
|
||||
// Fit never magnifies past 100%: one image pixel per *physical* pixel, so the cap applies
|
||||
// after the points → device pixels conversion (a 150% display would otherwise open at 150%).
|
||||
let fit = ((area.x - 40.0) / shown_w).min((area.y - 40.0) / h) * ppp;
|
||||
let zoom = crate::zoom_levels::clamp(fit.min(1.0), [doc.size.width, doc.size.height]);
|
||||
view.zoom = zoom;
|
||||
view.center = [w / 2.0, h / 2.0];
|
||||
view.fit_pending = false;
|
||||
@@ -1187,6 +1189,54 @@ fn navigator_waits_for_drag(app: &PhotocraftApp, idx: usize) -> bool {
|
||||
/// The Navigator panel's image of document `idx`. With the CPU canvas that is the canvas texture
|
||||
/// itself; with the GPU canvas a thumbnail cached per revision, so an edit to a huge document
|
||||
/// doesn't also pay a full-resolution CPU composite for the navigator.
|
||||
/// The Navigator's preview from the GPU canvas (#4518): the main canvas's texture of the
|
||||
/// document, drawn at `rect` with its own mip chain, so an edit costs no CPU composite. `None`
|
||||
/// while the canvas isn't showing the plain document on the GPU (the CPU thumbnail then).
|
||||
pub fn navigator_gpu_view(app: &PhotocraftApp, idx: usize, rect: Rect, ctx: &egui::Context) -> Option<crate::gpu_canvas::ViewParams> {
|
||||
app.gpu.as_ref()?;
|
||||
let st = app.session.documents().get(idx)?;
|
||||
let params = *app.navigator_gpu.get(&st.doc.id)?;
|
||||
let [w, h] = params.doc_size;
|
||||
if w == 0 || h == 0 || !rect.is_positive() || [st.doc.size.width, st.doc.size.height] != params.doc_size {
|
||||
return None;
|
||||
}
|
||||
Some(crate::gpu_canvas::ViewParams {
|
||||
zoom: rect.width() / w as f32,
|
||||
center: [w as f32 / 2.0, h as f32 / 2.0],
|
||||
rotation: 0.0,
|
||||
shadow: false,
|
||||
pixel_grid: false,
|
||||
view_key: egui::Id::new(("pc-navigator", ctx.viewport_id(), idx)).value(),
|
||||
offset: [0.0, 0.0],
|
||||
..params
|
||||
})
|
||||
}
|
||||
|
||||
/// Frames the Navigator waits for the GPU canvas to draw a document it hasn't drawn yet, rather
|
||||
/// than build a CPU thumbnail it would only use once (a full composite on a large document).
|
||||
const NAVIGATOR_WAIT_FRAMES: u32 = 3;
|
||||
|
||||
/// Whether the Navigator should wait a frame for the GPU canvas (#4518): the GPU canvas is on but
|
||||
/// hasn't drawn document `idx` yet (the Navigator can draw before the canvas in a frame). After
|
||||
/// [`NAVIGATOR_WAIT_FRAMES`] it stops waiting, so it never stays empty.
|
||||
pub fn navigator_waits_for_gpu(app: &PhotocraftApp, idx: usize, ctx: &egui::Context) -> bool {
|
||||
if app.gpu.is_none() {
|
||||
return false;
|
||||
}
|
||||
let Some(id) = app.session.documents().get(idx).map(|st| st.doc.id) else { return false };
|
||||
if app.canvases.keys().any(|(d, _)| *d == id) {
|
||||
return false;
|
||||
}
|
||||
let key = egui::Id::new(("navigator-waits", id.0));
|
||||
let waited = ctx.data(|d| d.get_temp::<u32>(key)).unwrap_or(0);
|
||||
if waited >= NAVIGATOR_WAIT_FRAMES {
|
||||
return false;
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(key, waited + 1));
|
||||
ctx.request_repaint();
|
||||
true
|
||||
}
|
||||
|
||||
pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize) -> Option<egui::TextureId> {
|
||||
if app.gpu.is_none() {
|
||||
return ensure_texture(app, ctx, idx, app.session.color.main_display).map(|(t, _)| t);
|
||||
@@ -1254,6 +1304,14 @@ pub fn navigator_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usiz
|
||||
Some(tex.id())
|
||||
}
|
||||
|
||||
/// The CPU canvas texture's sampling (#4810). Zoomed in, a full-resolution texture shows each
|
||||
/// document pixel as a crisp square, as the GPU canvas's sharp nearest filter and Photoshop do;
|
||||
/// zoomed out it is still filtered. A reduced texture (`factor` > 1) stays bilinear: its texels
|
||||
/// are averages of several pixels, and squares of them would be blocks the image doesn't have.
|
||||
fn canvas_texture_options(factor: u32) -> TextureOptions {
|
||||
if factor > 1 { TextureOptions::LINEAR } else { TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR } }
|
||||
}
|
||||
|
||||
/// Make sure the canvas texture for document `idx` on `display` is current; returns (texture
|
||||
/// id, scale).
|
||||
pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize, display: Option<u32>) -> Option<(egui::TextureId, f32)> {
|
||||
@@ -1298,7 +1356,7 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
|
||||
let r = buf.rect;
|
||||
if !r.is_empty() {
|
||||
let t1 = crate::gpu_canvas::now_ms();
|
||||
t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), TextureOptions::LINEAR);
|
||||
t.set_partial([r.x0 as usize, r.y0 as usize], display_image(display.as_deref(), &buf), canvas_texture_options(factor));
|
||||
let px = (r.width() as u64 * r.height() as u64).saturating_mul(u64::from(factor).pow(2));
|
||||
app.perf.record("rect", px, t1 - t0, crate::gpu_canvas::now_ms() - t1);
|
||||
}
|
||||
@@ -1308,8 +1366,8 @@ pub fn ensure_texture(app: &mut PhotocraftApp, ctx: &egui::Context, idx: usize,
|
||||
let t1 = crate::gpu_canvas::now_ms();
|
||||
let (img, scale) = (display_image(display.as_deref(), &full), 1.0 / factor as f32);
|
||||
match cache.texture.as_mut() {
|
||||
Some(t) if t.size() == img.size => t.set(img, TextureOptions::LINEAR),
|
||||
_ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, TextureOptions::LINEAR)),
|
||||
Some(t) if t.size() == img.size => t.set(img, canvas_texture_options(factor)),
|
||||
_ => cache.texture = Some(ctx.load_texture(format!("canvas-{}-{}", id.0, cache_key(id, output).1), img, canvas_texture_options(factor))),
|
||||
}
|
||||
cache.scale = scale;
|
||||
app.perf.record("full", doc.size.width as u64 * doc.size.height as u64, t1 - t0, crate::gpu_canvas::now_ms() - t1);
|
||||
@@ -1453,6 +1511,14 @@ fn ensure_gpu(app: &mut PhotocraftApp, idx: usize, visible: DRect) -> bool {
|
||||
damage = Some(crate::adjust_preview::switch_damage(app, raw_key, r, visible));
|
||||
}
|
||||
let preview_key = raw_key ^ display_key;
|
||||
// The Navigator may draw this texture only while it holds the plain document (no live
|
||||
// preview, which can be composited only where the view is).
|
||||
if raw_key == 0 {
|
||||
app.navigator_plain.insert(id);
|
||||
} else {
|
||||
app.navigator_plain.remove(&id);
|
||||
app.navigator_gpu.remove(&id);
|
||||
}
|
||||
let size = [doc.size.width, doc.size.height];
|
||||
let cache = app.canvases.entry((id, GPU_OUTPUT)).or_insert(CanvasCache {
|
||||
revision: 0,
|
||||
@@ -1589,16 +1655,24 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
|
||||
let fresh = app.filter_preview.as_ref().is_some_and(|p| p.key == request);
|
||||
if !fresh && !app.filter_preview_worker.busy() {
|
||||
let doc = app.session.documents().get(idx)?.doc.clone();
|
||||
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
|
||||
let task = request.clone();
|
||||
if let Err(error) = app.filter_preview_worker.start(request.clone(), ctx.clone(), move |cancel| {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let result =
|
||||
crate::filter_dialog::preview_document_for_target(&doc, task.active, &task.command, &task.params, task.k, Some(cancel), task.target).map(
|
||||
|doc| {
|
||||
let buffer = photocraft_compose::flatten(&doc);
|
||||
(std::sync::Arc::new(doc), buffer)
|
||||
},
|
||||
);
|
||||
let result = crate::filter_dialog::preview_document_for_target(
|
||||
&doc,
|
||||
task.active,
|
||||
&task.command,
|
||||
&task.params,
|
||||
task.k,
|
||||
Some(cancel),
|
||||
task.target,
|
||||
&documents,
|
||||
)
|
||||
.map(|doc| {
|
||||
let buffer = photocraft_compose::flatten(&doc);
|
||||
(std::sync::Arc::new(doc), buffer)
|
||||
});
|
||||
crate::filter_preview_worker::Computed { result, ms: crate::gpu_canvas::now_ms() - t0 }
|
||||
}) {
|
||||
app.filter_preview = Some(crate::filter_dialog::FilterPreview { key: request.clone(), result: None, committing: false });
|
||||
@@ -1629,10 +1703,19 @@ pub(crate) fn ensure_filter_preview(app: &mut PhotocraftApp, idx: usize, ctx: &e
|
||||
let _ = ctx;
|
||||
if app.filter_preview.as_ref().is_none_or(|p| p.key != request) {
|
||||
let doc = app.session.documents().get(idx)?.doc.clone();
|
||||
let documents: Vec<_> = app.session.documents().iter().map(|d| d.doc.clone()).collect();
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let result =
|
||||
crate::filter_dialog::preview_document_for_target(&doc, request.active, &request.command, &request.params, request.k, None, request.target)
|
||||
.map(std::sync::Arc::new);
|
||||
let result = crate::filter_dialog::preview_document_for_target(
|
||||
&doc,
|
||||
request.active,
|
||||
&request.command,
|
||||
&request.params,
|
||||
request.k,
|
||||
None,
|
||||
request.target,
|
||||
&documents,
|
||||
)
|
||||
.map(std::sync::Arc::new);
|
||||
if let Some(r) = &result {
|
||||
let buf = photocraft_compose::flatten(r);
|
||||
let t1 = crate::gpu_canvas::now_ms();
|
||||
@@ -2767,6 +2850,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
ensure_adjust_proxy(app, idx, view.zoom).or_else(|| ensure_filter_preview(app, idx, &ctx)).or_else(|| ensure_proxy_preview(app, idx))
|
||||
{
|
||||
on_gpu = true;
|
||||
app.navigator_gpu.remove(&doc.id);
|
||||
let original_size = [doc.size.width.div_ceil(k), doc.size.height.div_ceil(k)];
|
||||
let params = crate::gpu_canvas::ViewParams {
|
||||
doc: key,
|
||||
@@ -2811,8 +2895,14 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
hdr: hdr_preview(app, &doc),
|
||||
offset: [0.0, 0.0],
|
||||
};
|
||||
if app.navigator_plain.contains(&doc.id) {
|
||||
app.navigator_gpu.insert(doc.id, params);
|
||||
} else {
|
||||
app.navigator_gpu.remove(&doc.id);
|
||||
}
|
||||
paint_gpu_view(&painter, rect, params, &pattern);
|
||||
} else {
|
||||
app.navigator_gpu.remove(&doc.id);
|
||||
if !crate::theme::Tokens::get(&ctx).bevel && drop_shadow {
|
||||
painter.add(egui::Shadow { offset: [0, 8], blur: 28, spread: 0, color: Color32::from_black_alpha(150) }.as_shape(img_rect, 0));
|
||||
}
|
||||
@@ -3253,7 +3343,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
(buttons.started, buttons.dragged, buttons.stopped, buttons.clicked) = (false, false, false, false);
|
||||
}
|
||||
// Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below.
|
||||
if tool == Tool::Zoom && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) {
|
||||
// Like the Hand, the selected Zoom yields to an open Free Transform box (#4799).
|
||||
if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, &ctx, &mut view, &xf, &buttons, response.interact_pointer_pos()) {
|
||||
(buttons.started, buttons.dragged, buttons.stopped) = (false, false, false);
|
||||
}
|
||||
// A drag is only recognised once the pointer has moved past egui's click distance: the
|
||||
@@ -3387,7 +3478,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
let click_mods = ui.input(|i| pointer_button_modifiers(&i.events, click_button)).unwrap_or(mods);
|
||||
let d = xf.to_doc(p);
|
||||
match tool {
|
||||
Tool::Zoom => {
|
||||
Tool::Zoom if !transform_owns_pointer => {
|
||||
let nz = crate::zoom_levels::step(view.zoom, if zoom_out(click_mods.alt) { -1 } else { 1 }, view.doc_size);
|
||||
let center = app.session.prefs().tools.zoom_clicked_point_to_center;
|
||||
zoom_about(&mut view, &xf, p, nz, center, ppp);
|
||||
@@ -3552,6 +3643,8 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
let toward = xf.to_screen((d[0] + k[0] * 16.0) as f32, (d[1] + k[1] * 16.0) as f32) - p;
|
||||
crate::crop_ui::draw_turn_cursor(&ctx, p, toward);
|
||||
}
|
||||
} else if let Some(c) = response.hover_pos().and_then(|p| crate::symmetry_ui::cursor(app, &xf, xf.to_doc(p))) {
|
||||
ui.ctx().set_cursor_icon(c);
|
||||
} else if let Some(c) = response.hover_pos().and_then(|p| crate::cam_transform::cursor(app, &ctx, &xf, p)) {
|
||||
ui.ctx().set_cursor_icon(c);
|
||||
} else if let Some((r, p, c)) =
|
||||
@@ -3729,13 +3822,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect:
|
||||
// Dragging is handled with the pan itself, above.
|
||||
Tool::Hand => crate::tool_cursor::hand(ui.ctx(), false),
|
||||
Tool::RotateView => crate::rotate_view::cursor(response.dragged()),
|
||||
Tool::Zoom => {
|
||||
if zoom_out(alt) {
|
||||
egui::CursorIcon::ZoomOut
|
||||
} else {
|
||||
egui::CursorIcon::ZoomIn
|
||||
}
|
||||
}
|
||||
Tool::Zoom => crate::tool_cursor::zoom(ui.ctx(), zoom_out(alt)),
|
||||
Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => egui::CursorIcon::Text,
|
||||
Tool::MagneticLasso => crate::magnetic_lasso_ui::cursor(app, &painter, p, xf.zoom),
|
||||
Tool::RedEye => {
|
||||
@@ -5500,6 +5587,7 @@ fn polygon_click(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers)
|
||||
return;
|
||||
}
|
||||
if app.ui.polygon.is_empty() {
|
||||
app.ui.polygon_doc = app.session.active().map(|st| st.doc.id);
|
||||
// ⌥ with nothing selected draws freehand; there is nothing to subtract from.
|
||||
let nothing_selected = app.session.active().is_none_or(|st| st.doc.selection.is_none());
|
||||
let intent = if nothing_selected { egui::Modifiers { alt: false, ..mods } } else { mods };
|
||||
@@ -5523,6 +5611,22 @@ pub fn polygon_retract(app: &mut PhotocraftApp) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The polygon in progress belongs to the document it was started on (`UiState::polygon_doc`):
|
||||
/// once another document becomes active it is dropped, so its outline doesn't show on (or get
|
||||
/// committed to) the other document, and the selection it would have replaced is shown again.
|
||||
/// Switching tools is handled in `PhotocraftApp::sync_views`. Like the Lasso's
|
||||
/// ([`crate::lasso_ui::cancel_stale`]) and the Magnetic Lasso's ([`crate::magnetic_lasso_ui::frame`]).
|
||||
pub fn polygon_cancel_stale(app: &mut PhotocraftApp) {
|
||||
let active = app.session.active().map(|st| st.doc.id);
|
||||
if app.ui.polygon.is_empty() {
|
||||
app.ui.polygon_doc = None;
|
||||
} else if app.ui.polygon_doc.is_some_and(|d| Some(d) != active) {
|
||||
app.ui.polygon.clear();
|
||||
app.ui.polygon_mode.clear();
|
||||
app.ui.polygon_doc = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// A new-selection polygonal (or magnetic) lasso is being drawn, so the selection it will replace
|
||||
/// is hidden.
|
||||
pub fn polygon_replaces_selection(app: &PhotocraftApp) -> bool {
|
||||
@@ -5850,6 +5954,46 @@ mod tests {
|
||||
assert_eq!((app.canvases[&(id, 1)].tex_revision, app.canvases[&(id, 4)].tex_revision), (rev, rev));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_canvas_shows_crisp_pixels_when_zoomed_in() {
|
||||
// #4810: above 100% the CPU canvas shows each pixel as a square, like the GPU canvas's
|
||||
// sharp nearest filter; below 100% it still filters. Both the first upload and a
|
||||
// damage-rect update carry the sampling, since the renderer takes it from each delta.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 2, "height": 2})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let tex = ensure_texture(&mut app, &ctx, 0, None).unwrap().0;
|
||||
let uploads = |ctx: &egui::Context| {
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
let seen = delta.set.get(&tex).into_iter().flatten().map(|d| (d.pos.is_some(), d.options)).collect::<Vec<_>>();
|
||||
delta.clear();
|
||||
seen
|
||||
};
|
||||
let crisp = TextureOptions { magnification: egui::TextureFilter::Nearest, ..TextureOptions::LINEAR };
|
||||
assert_eq!(uploads(&ctx), vec![(false, crisp)]);
|
||||
app.run("select.rect", json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
|
||||
ensure_texture(&mut app, &ctx, 0, None).unwrap();
|
||||
uploads(&ctx);
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
assert_eq!(ensure_texture(&mut app, &ctx, 0, None).unwrap().0, tex);
|
||||
assert_eq!(uploads(&ctx), vec![(true, crisp)], "a partial update keeps the crisp sampling");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cpu_canvas_of_a_reduced_document_stays_bilinear() {
|
||||
// Over MAX_TEXTURE the texture holds one texel per `factor` pixels: a texel is not a
|
||||
// document pixel, so showing it as a square would draw blocks that aren't in the image.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": MAX_TEXTURE + 1, "height": 2})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
let (tex, scale) = ensure_texture(&mut app, &ctx, 0, None).unwrap();
|
||||
assert!(scale < 1.0);
|
||||
let mut delta = ctx.tex_manager().write().take_delta();
|
||||
let uploads: Vec<_> = delta.set.get(&tex).into_iter().flatten().map(|d| d.options).collect();
|
||||
delta.clear();
|
||||
assert_eq!(uploads, vec![TextureOptions::LINEAR]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_display_luts_are_per_display() {
|
||||
let Ok(rs) = std::panic::catch_unwind(|| egui_kittest::wgpu::create_render_state(crate::gpu_canvas::wgpu_setup(), Default::default())) else {
|
||||
@@ -7210,6 +7354,46 @@ mod tests {
|
||||
assert!(app.style_preview.is_none());
|
||||
}
|
||||
|
||||
/// Layer Style opened while Free Transform is open applies the box first, as Photoshop does,
|
||||
/// so the dialog previews on the transformed layer (#4821): a dropped file (placed in the box,
|
||||
/// untouched) and a box opened by hand and moved.
|
||||
#[test]
|
||||
fn layer_style_opened_during_free_transform_applies_the_box_and_previews() {
|
||||
for placed in [true, false] {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#0000ff"})).unwrap();
|
||||
app.run("select.deselect", json!({})).unwrap();
|
||||
app.sync_views();
|
||||
let ctx = egui::Context::default();
|
||||
let dx = if placed {
|
||||
crate::transform_tool::begin_placed(&mut app, &ctx).unwrap();
|
||||
0
|
||||
} else {
|
||||
crate::transform_tool::begin(&mut app, &ctx).unwrap();
|
||||
app.ui.transform.as_mut().unwrap().quad = [[28.0, 8.0], [44.0, 8.0], [44.0, 24.0], [28.0, 24.0]];
|
||||
20
|
||||
};
|
||||
crate::layer_style::open(&mut app, Some("dropShadow")).unwrap();
|
||||
assert!(app.ui.transform.is_none() && app.transform_preview.is_none(), "placed {placed}: the box is applied");
|
||||
let (shown, _) = display_doc(&mut app, 0);
|
||||
let rect = photocraft_geom::Rect::new(0, 0, 64, 64);
|
||||
let with = photocraft_compose::render(&shown, rect);
|
||||
let without = photocraft_compose::render(&app.session.documents()[0].doc, rect);
|
||||
assert!(
|
||||
with.get(16 + dx, 16)[0] < 0.1 && with.get(16 + dx, 16)[2] > 0.9,
|
||||
"placed {placed}: the blue block where the box left it, not the white under it"
|
||||
);
|
||||
// The shadow darkens the white around the block, which the document doesn't have yet.
|
||||
let block = |x: i32, y: i32| (8 + dx..24 + dx).contains(&x) && (8..24).contains(&y);
|
||||
let shadow =
|
||||
(0..64).flat_map(|y| (0..64).map(move |x| (x, y))).filter(|&(x, y)| !block(x, y) && without.get(x, y)[0] - with.get(x, y)[0] > 0.05).count();
|
||||
assert!(shadow > 20, "placed {placed}: the Drop Shadow is previewed ({shadow} px)");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_view_covers_the_canvas_and_centres_the_document() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
@@ -7228,13 +7412,22 @@ mod tests {
|
||||
fill_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0);
|
||||
assert_eq!(view.zoom, 6.0);
|
||||
|
||||
// Fit never magnifies past the 1 point-per-pixel cap; on a scaled display the cap is 2.
|
||||
// Fit never magnifies past 100% = one image pixel per physical pixel, at any display
|
||||
// scale (it used to cap at one per *point*, so a 150% display opened images at 150%).
|
||||
for ppp in [1.0f32, 1.5, 2.0] {
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), ppp, 1.0);
|
||||
assert_eq!(view.zoom, 1.0, "ppp {ppp}: a small image opens at 100%");
|
||||
}
|
||||
// A large image still shrinks to fit: 1000×500 into 440 points is 0.44 pt/px, so 0.66
|
||||
// physical at ppp 1.5.
|
||||
let big = {
|
||||
app.run("file.new", json!({"width": 1000, "height": 500})).unwrap();
|
||||
app.session.active().unwrap().doc.clone()
|
||||
};
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), 1.0, 1.0);
|
||||
assert_eq!(view.zoom, 1.0);
|
||||
let mut view = View { fit_pending: true, ..View::default() };
|
||||
fit_view(&mut view, &doc, vec2(600.0, 600.0), 2.0, 1.0);
|
||||
assert_eq!(view.zoom, 2.0);
|
||||
fit_view(&mut view, &big, vec2(480.0, 480.0), 1.5, 1.0);
|
||||
assert!((view.zoom - 0.66).abs() < 1e-5, "{}", view.zoom);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+107
-19
@@ -285,37 +285,60 @@ fn missing_char(ctx: &egui::Context, shapes: &[egui::epaint::ClippedShape], fall
|
||||
ctx.fonts_mut(|f| chars.into_iter().find(|c| !f.has_glyph(&font, *c)))
|
||||
}
|
||||
|
||||
/// (ascent, descent, line gap) of a face in em, from its `hhea` table; `descent` is negative.
|
||||
fn vertical_metrics(font: &[u8], index: u32) -> Option<(f32, f32, f32)> {
|
||||
let u16_at = |o: usize| font.get(o..o.checked_add(2)?).map(|b| u16::from_be_bytes([b[0], b[1]]));
|
||||
let u32_at = |o: usize| font.get(o..o.checked_add(4)?).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]));
|
||||
let i16_at = |o: usize| u16_at(o).map(|v| v as i16 as f32);
|
||||
/// Big-endian readers over a font's bytes; `None` past the end.
|
||||
fn be_u16(font: &[u8], o: usize) -> Option<u16> {
|
||||
font.get(o..o.checked_add(2)?).map(|b| u16::from_be_bytes([b[0], b[1]]))
|
||||
}
|
||||
|
||||
fn be_u32(font: &[u8], o: usize) -> Option<u32> {
|
||||
font.get(o..o.checked_add(4)?).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
|
||||
}
|
||||
|
||||
/// The offset of table `tag` in face `index` of `font` (a collection or a single face).
|
||||
fn table_offset(font: &[u8], index: u32, tag: &[u8; 4]) -> Option<usize> {
|
||||
let dir = if font.get(..4)? == b"ttcf" {
|
||||
// Collection: the offset table of face `index` follows a 12-byte header.
|
||||
u32_at(12usize.checked_add((index as usize).checked_mul(4)?)?)? as usize
|
||||
be_u32(font, 12usize.checked_add((index as usize).checked_mul(4)?)?)? as usize
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let tables = u16_at(dir.checked_add(4)?)? as usize;
|
||||
let (mut hhea, mut head) = (None, None);
|
||||
for i in 0..tables {
|
||||
let tables = be_u16(font, dir.checked_add(4)?)? as usize;
|
||||
(0..tables).find_map(|i| {
|
||||
let rec = dir.checked_add(12)?.checked_add(i.checked_mul(16)?)?;
|
||||
let tag = font.get(rec..rec.checked_add(4)?)?;
|
||||
let off = u32_at(rec.checked_add(8)?)? as usize;
|
||||
match tag {
|
||||
b"hhea" => hhea = Some(off),
|
||||
b"head" => head = Some(off),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let (hhea, head) = (hhea?, head?);
|
||||
let upm = u16_at(head.checked_add(18)?)? as f32;
|
||||
(font.get(rec..rec.checked_add(4)?)? == tag).then_some(())?;
|
||||
Some(be_u32(font, rec.checked_add(8)?)? as usize)
|
||||
})
|
||||
}
|
||||
|
||||
/// (ascent, descent, line gap) of a face in em, from its `hhea` table; `descent` is negative.
|
||||
fn vertical_metrics(font: &[u8], index: u32) -> Option<(f32, f32, f32)> {
|
||||
let i16_at = |o: usize| be_u16(font, o).map(|v| v as i16 as f32);
|
||||
let (hhea, head) = (table_offset(font, index, b"hhea")?, table_offset(font, index, b"head")?);
|
||||
let upm = be_u16(font, head.checked_add(18)?)? as f32;
|
||||
if upm <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
Some((i16_at(hhea.checked_add(4)?)? / upm, i16_at(hhea.checked_add(6)?)? / upm, i16_at(hhea.checked_add(8)?)? / upm))
|
||||
}
|
||||
|
||||
/// The weight a variable face should be drawn at: Regular (400) within its `wght` axis, or
|
||||
/// `None` when it has no weight axis or already defaults to Regular. Noto Sans CJK's variable
|
||||
/// collection defaults to Thin (100), so the UI's CJK text came out hairline (#4820).
|
||||
fn regular_weight(font: &[u8], index: u32) -> Option<f32> {
|
||||
let fvar = table_offset(font, index, b"fvar")?;
|
||||
let axes = fvar.checked_add(be_u16(font, fvar.checked_add(4)?)? as usize)?;
|
||||
let count = be_u16(font, fvar.checked_add(8)?)? as usize;
|
||||
let size = be_u16(font, fvar.checked_add(10)?)? as usize;
|
||||
let fixed = |o: usize| be_u32(font, o).map(|v| v as i32 as f32 / 65536.0);
|
||||
(0..count.min(64)).find_map(|i| {
|
||||
let rec = axes.checked_add(i.checked_mul(size)?)?;
|
||||
(font.get(rec..rec.checked_add(4)?)? == b"wght").then_some(())?;
|
||||
let (min, default, max) = (fixed(rec.checked_add(4)?)?, fixed(rec.checked_add(8)?)?, fixed(rec.checked_add(12)?)?);
|
||||
let regular = 400f32.clamp(min.min(max), max.max(min));
|
||||
(regular.is_finite() && (regular - default).abs() > 0.5).then_some(regular)
|
||||
})
|
||||
}
|
||||
|
||||
/// `y_offset_factor` that puts `face`'s baseline where `primary`'s would be. egui centres a
|
||||
/// fallback face's row in the primary font's row, so a face with a big line gap (Hiragino: 0.5em)
|
||||
/// otherwise rides about 0.23em high next to Latin text.
|
||||
@@ -332,6 +355,9 @@ fn add_to_all_families(ctx: &egui::Context, name: String, mut data: FontData) {
|
||||
if let (Some(face), Some(primary)) = (vertical_metrics(&data.font, data.index), primary) {
|
||||
data.tweak.y_offset_factor = baseline_offset(face, primary);
|
||||
}
|
||||
if let Some(weight) = regular_weight(&data.font, data.index) {
|
||||
data.tweak.coords = egui::epaint::text::VariationCoords::new([(b"wght", weight)]);
|
||||
}
|
||||
let mut families: Vec<FontFamily> = ctx.fonts(|f| f.definitions().families.keys().cloned().collect());
|
||||
for f in [FontFamily::Proportional, FontFamily::Monospace] {
|
||||
if !families.contains(&f) {
|
||||
@@ -427,6 +453,68 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A font holding only an `fvar` table with the given axes (tag, min, default, max), as a
|
||||
/// single face or as face 1 of a two-face collection.
|
||||
fn fvar_font(axes: &[(&[u8; 4], f32, f32, f32)], collection: bool) -> Vec<u8> {
|
||||
let fixed = |v: f32| ((v * 65536.0) as i32).to_be_bytes();
|
||||
let mut fvar = Vec::new();
|
||||
for x in [1u16, 0, 16, 2, axes.len() as u16, 20, 0, 0] {
|
||||
fvar.extend(x.to_be_bytes());
|
||||
}
|
||||
for (tag, min, def, max) in axes {
|
||||
fvar.extend(*tag);
|
||||
for v in [*min, *def, *max] {
|
||||
fvar.extend(fixed(v));
|
||||
}
|
||||
fvar.extend([0, 0, 1, 0]);
|
||||
}
|
||||
let face = |at: u32| {
|
||||
let mut d = vec![0, 1, 0, 0, 0, 1, 0, 16, 0, 0, 0, 0];
|
||||
d.extend(b"fvar");
|
||||
d.extend([0; 4]);
|
||||
d.extend(at.to_be_bytes());
|
||||
d.extend((fvar.len() as u32).to_be_bytes());
|
||||
d
|
||||
};
|
||||
if !collection {
|
||||
let mut f = face(28);
|
||||
f.extend(&fvar);
|
||||
return f;
|
||||
}
|
||||
// ttcf header (12 + 2×4), two 28-byte directories, then the shared table.
|
||||
let mut f = b"ttcf".to_vec();
|
||||
f.extend([0, 1, 0, 0, 0, 0, 0, 2]);
|
||||
f.extend(20u32.to_be_bytes());
|
||||
f.extend(48u32.to_be_bytes());
|
||||
f.extend(face(76));
|
||||
f.extend(face(76));
|
||||
f.extend(&fvar);
|
||||
f
|
||||
}
|
||||
|
||||
/// #4820: Noto Sans CJK's variable collection defaults to Thin; the fallback asks for Regular.
|
||||
#[test]
|
||||
fn variable_fallbacks_are_drawn_at_regular_weight() {
|
||||
let thin = fvar_font(&[(b"wght", 100.0, 100.0, 900.0)], true);
|
||||
assert_eq!(regular_weight(&thin, 1), Some(400.0), "Noto Sans CJK VF, face 1 of a collection");
|
||||
assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0), (b"wght", 100.0, 100.0, 900.0)], false), 0), Some(400.0));
|
||||
assert_eq!(regular_weight(&fvar_font(&[(b"wght", 500.0, 600.0, 900.0)], false), 0), Some(500.0), "Regular clamped into the axis");
|
||||
assert_eq!(regular_weight(&fvar_font(&[(b"wght", 100.0, 400.0, 900.0)], false), 0), None, "already Regular");
|
||||
assert_eq!(regular_weight(&fvar_font(&[(b"wdth", 75.0, 100.0, 100.0)], false), 0), None, "no weight axis");
|
||||
assert_eq!(regular_weight(photocraft_text::fonts::INTER_REGULAR.as_slice(), 0), None, "static font");
|
||||
for bad in [&thin[..thin.len() - 9], &thin[..30], &b"ttcf"[..], &[][..]] {
|
||||
assert_eq!(regular_weight(bad, 1), None);
|
||||
}
|
||||
// Registered as a fallback, a static face keeps the default (no variation) coordinates.
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
|
||||
add_to_all_families(&ctx, "test-static".into(), FontData::from_static(photocraft_text::fonts::INTER_REGULAR.as_slice()));
|
||||
ctx.run_ui(Default::default(), |_| {}).textures_delta.clear();
|
||||
let fonts = ctx.fonts(|f| f.definitions().clone());
|
||||
assert_eq!(fonts.font_data.get("test-static").map(|d| d.tweak.coords.clone()), Some(Default::default()));
|
||||
}
|
||||
|
||||
static DIR: Mutex<Option<PathBuf>> = Mutex::new(None);
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -686,7 +686,7 @@ fn fields(ui: &mut egui::Ui, f: &mut Map<String, Value>, mode: &str, now: &Compo
|
||||
ui.memory_mut(|m| m.request_focus(id));
|
||||
}
|
||||
let typing = if ui.memory(|m| m.has_focus(id)) { ui.data(|d| d.get_temp::<String>(id)) } else { None };
|
||||
let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_string());
|
||||
let mut h = typing.unwrap_or_else(|| hex(rgb).trim_start_matches('#').to_ascii_uppercase());
|
||||
let r = crate::widgets::text_field_ex(ui, id, &mut h, "", 64.0, true, Some(6));
|
||||
if r.gained_focus() {
|
||||
crate::field_tab::select_all(ui.ctx(), id, &h);
|
||||
@@ -859,6 +859,13 @@ mod tests {
|
||||
h.state().get("color").and_then(Value::as_str).unwrap().to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_field_shows_uppercase_without_rewriting_the_selected_color() {
|
||||
let h = picker("#12abef");
|
||||
assert_eq!(h.get_by_role(Role::TextInput).value().as_deref(), Some("12ABEF"));
|
||||
assert_eq!(color(&h), "#12abef", "casing is presentation only");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hex_field_takes_typed_digits() {
|
||||
let mut h = picker("#000000");
|
||||
|
||||
@@ -872,6 +872,23 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
wrap(crate::workspace_ui::confirm(app, ctx))
|
||||
}
|
||||
"ui.dialog.apply" if s("dialog") == Some(SHELL_DIALOG) => err("`ui.dialog.apply` is for Preferences; use `ui.dialog.confirm`"),
|
||||
// The unsaved-changes prompt (closing, Revert, quitting), listed by ui.inspect with the
|
||||
// id "discard" (#4920): confirm takes a `choice` (save, dontSave, cancel; default save).
|
||||
"ui.dialog.confirm" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => {
|
||||
let choice = s("choice").unwrap_or("save");
|
||||
if choice != "cancel"
|
||||
&& let Some((command, params)) = crate::discard_ui::pending_command(app)
|
||||
&& let Some(authorize) = app.services.automation_command.as_ref()
|
||||
&& let Err(error) = authorize(&command, ¶ms)
|
||||
{
|
||||
return err(error);
|
||||
}
|
||||
wrap(crate::discard_ui::answer_control(app, ctx, choice))
|
||||
}
|
||||
"ui.dialog.cancel" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => wrap(crate::discard_ui::answer_control(app, ctx, "cancel")),
|
||||
"ui.dialog.set" | "ui.dialog.apply" if s("dialog") == Some(crate::discard_ui::CONTROL_ID) => {
|
||||
err("the unsaved-changes prompt has no fields; use `ui.dialog.confirm` with a `choice`")
|
||||
}
|
||||
"ui.dialog.cancel" if s("dialog") == Some(SHELL_DIALOG) => match app.ui.shell.dialog.take() {
|
||||
Some(_) => ok(Value::Null),
|
||||
None => err("no such dialog"),
|
||||
@@ -1242,6 +1259,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
|
||||
if let Some((kind, fields)) = &app.ui.shell.dialog {
|
||||
dialogs.push(json!({"id": SHELL_DIALOG, "kind": kind, "title": crate::workspace_ui::title(kind), "fields": fields}));
|
||||
}
|
||||
dialogs.extend(crate::discard_ui::inspect(app));
|
||||
json!({
|
||||
"window": {"width": screen.width(), "height": screen.height(), "pixelsPerPoint": ctx.pixels_per_point()},
|
||||
"tool": app.ui.tool,
|
||||
@@ -1554,6 +1572,47 @@ mod tests {
|
||||
assert_eq!(app.ui.tool_options.stroke_width, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_unsaved_changes_prompt_is_listed_and_answered_through_ui_dialog() {
|
||||
// #4920: the prompt shown on quit or close with unsaved changes wasn't in ui.inspect, and a
|
||||
// control client couldn't answer it.
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
for _ in 0..2 {
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
}
|
||||
let prompt = |app: &mut PhotocraftApp| {
|
||||
let v = call(app, &ctx, "ui.inspect", json!({}));
|
||||
v["result"]["dialogs"].as_array().unwrap().iter().find(|d| d["id"] == "discard").cloned()
|
||||
};
|
||||
assert!(prompt(&mut app).is_none());
|
||||
// Closing a dirty document: listed with its choices; a bad choice and Cancel keep the document.
|
||||
crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
|
||||
let d = prompt(&mut app).expect("the prompt is listed");
|
||||
assert_eq!(d["fields"]["command"], "file.close");
|
||||
assert_eq!(d["fields"]["choices"], json!(["save", "dontSave", "cancel"]));
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "maybe"}))["ok"], false);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.set", json!({"dialog": "discard", "field": "x", "value": 1}))["ok"], false);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], true);
|
||||
assert!(prompt(&mut app).is_none() && app.session.documents().len() == 2);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.cancel", json!({"dialog": "discard"}))["ok"], false, "nothing left to answer");
|
||||
// Don't Save closes it.
|
||||
crate::menus::invoke(&mut app, &ctx, "file.close", json!({})).unwrap();
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["ok"], true);
|
||||
assert_eq!(app.session.documents().len(), 1);
|
||||
// Quitting asks about each dirty document, then lets the window close.
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
assert!(crate::discard_ui::intercept(&mut app, "file.exit", &Value::Null));
|
||||
let d = prompt(&mut app).expect("the quit prompt is listed");
|
||||
assert_eq!((d["fields"]["command"].as_str(), d["fields"]["remaining"].as_u64()), (Some("file.exit"), Some(2)));
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], true);
|
||||
assert_eq!(prompt(&mut app).unwrap()["fields"]["remaining"], 1);
|
||||
assert_eq!(call(&mut app, &ctx, "ui.dialog.confirm", json!({"dialog": "discard", "choice": "dontSave"}))["result"]["open"], false);
|
||||
assert!(app.allow_close && app.session.documents().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_dialogs_are_listed_and_driven_through_ui_dialog() {
|
||||
// #1004: Window › Workspace and View dialogs live in `ui.shell.dialog`, and ui.inspect and
|
||||
|
||||
@@ -14,6 +14,11 @@ fn rects(ctx: &egui::Context) -> Vec<egui::Rect> {
|
||||
ctx.data(|m| m.get_temp(egui::Id::new(RECTS))).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The window drag target must not cover a dialog which has been moved into the title bar.
|
||||
pub(crate) fn titlebar_drag_area_is_clear(ctx: &egui::Context, area: egui::Rect) -> bool {
|
||||
rects(ctx).iter().all(|dialog| !dialog.intersects(area))
|
||||
}
|
||||
|
||||
/// With a dialog open the rest of the window is inert (egui's modal layer), but like Photoshop the
|
||||
/// image can still be panned and zoomed under it. The pointer position when it is over `canvas`
|
||||
/// and not over a dialog or one of its popups.
|
||||
@@ -338,7 +343,14 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| {
|
||||
ui.spacing_mut().item_spacing.x = 10.0;
|
||||
if matches!(d.kind, DialogKind::About | DialogKind::Error) {
|
||||
if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() {
|
||||
// ↩ is OK too, as on every other dialog (#4872), from the frame after the
|
||||
// alert appeared: the ↩ that raised it (committing a locked layer's Free
|
||||
// Transform, say) must not close it again at once.
|
||||
let seen = id.with("alert-seen");
|
||||
let shown_before = ui.ctx().data(|m| m.get_temp::<bool>(seen).unwrap_or(false));
|
||||
ui.ctx().data_mut(|m| m.insert_temp(seen, true));
|
||||
let enter = interactive && shown_before && ui.input(|i| i.key_pressed(egui::Key::Enter));
|
||||
if dialog_buttons(ui, &[DialogButton::new(ButtonRole::Default, tl!("OK"), 84.0)]).is_some() || enter {
|
||||
outcome = Some(false);
|
||||
}
|
||||
} else {
|
||||
@@ -795,6 +807,32 @@ mod tests {
|
||||
assert_eq!(harness.state().ui.dialogs.len(), 1, "dragging must not close the dialog");
|
||||
}
|
||||
|
||||
/// #4872: an alert (Error, About) closes with ↩ as with OK, but not on the ↩ that raised it.
|
||||
#[test]
|
||||
fn enter_closes_an_alert_but_not_the_enter_that_opened_it() {
|
||||
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 600.0)).build_ui_state(|ui, app| show(app, ui.ctx()), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(2);
|
||||
let alert = |h: &mut egui_kittest::Harness<'static, PhotocraftApp>| {
|
||||
h.state_mut().ui.open_dialog(DialogKind::Error, json!({"message": crate::move_lock::MESSAGE}).as_object().cloned().unwrap_or_default())
|
||||
};
|
||||
// Raised in the frame its own ↩ arrives: that ↩ leaves it open.
|
||||
alert(&mut h);
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.dialogs.len(), 1, "the ↩ that raised the alert doesn't close it");
|
||||
h.key_press(egui::Key::Enter);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialogs.is_empty(), "↩ is OK");
|
||||
// A new alert starts over, and Esc still closes it.
|
||||
alert(&mut h);
|
||||
h.run_steps(2);
|
||||
h.key_press(egui::Key::Escape);
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.dialogs.is_empty(), "Esc too");
|
||||
}
|
||||
|
||||
fn dialog_harness(size: egui::Vec2, command: &str) -> egui_kittest::Harness<'static, PhotocraftApp> {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 64})).unwrap();
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
//! canvas to marquee-select anchors, click empty canvas to deselect.
|
||||
//! * Drag selected anchors to move them, a direction handle to turn it (a smooth point keeps its
|
||||
//! handles collinear; ⌥ breaks them apart), or a segment to bend it (straight segments move).
|
||||
//! The arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press.
|
||||
//! * Convert Point (the tool, or Pen + ⌥): click an anchor to make it a corner, drag from it to
|
||||
//! pull out smooth handles, drag a handle to move it alone. The tool selects the anchor it
|
||||
//! converts, so its handles show; a press on empty canvas or a segment does nothing, and ⌘/Ctrl
|
||||
@@ -346,6 +347,37 @@ fn marquee(app: &mut PhotocraftApp, start: [f64; 2], end: [f64; 2], add: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Arrow keys with Direct Selection and selected anchors (#4486), as in Photoshop: nudge them
|
||||
/// 1 px (⇧ 10 px) through `path.moveAnchors`, one history step per press. Not while a drag is
|
||||
/// in progress. Returns true when a key was used.
|
||||
pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
let ds = &app.ui.direct_selection;
|
||||
let Some(target) = ds.target.filter(|_| app.ui.tool == Tool::DirectSelection && !ds.anchors.is_empty() && ds.drag.is_none()) else {
|
||||
return false;
|
||||
};
|
||||
let anchors = ds.anchors.clone();
|
||||
use egui::Key;
|
||||
let keys = [(Key::ArrowLeft, -1.0, 0.0), (Key::ArrowRight, 1.0, 0.0), (Key::ArrowUp, 0.0, -1.0), (Key::ArrowDown, 0.0, 1.0)];
|
||||
for (key, ux, uy) in keys {
|
||||
// ⇧ first: `consume_key` ignores an extra ⇧.
|
||||
for mods in [Modifiers::SHIFT, Modifiers::NONE] {
|
||||
if ctx.input_mut(|i| i.consume_key(mods, key)) {
|
||||
let k = if mods.shift { 10.0 } else { 1.0 };
|
||||
let mut params = json!({"anchors": anchors, "move": [ux * k, uy * k]});
|
||||
if let (Some(p), Some(t)) = (params.as_object_mut(), target.params().as_object()) {
|
||||
p.extend(t.clone());
|
||||
}
|
||||
if let Err(e) = app.run("path.moveAnchors", params) {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Paths with their anchors (selected ones filled), the shown handles, the drag's preview in
|
||||
/// place of its path, and the marquee. `paths` false (View › Show › Target Path off) leaves only
|
||||
/// the marquee.
|
||||
|
||||
@@ -225,3 +225,39 @@ fn the_convert_point_tool_shows_the_path_overlay() {
|
||||
assert!(!super::shows(&app, Modifiers::NONE));
|
||||
assert!(super::shows(&app, Modifiers::COMMAND));
|
||||
}
|
||||
|
||||
/// One key press through the canvas arrow keys, as egui delivers it.
|
||||
fn press(app: &mut PhotocraftApp, key: egui::Key, mods: Modifiers) -> bool {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.input_mut(|i| {
|
||||
i.modifiers = mods;
|
||||
i.events.push(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: mods });
|
||||
});
|
||||
crate::move_mods::arrow_keys(app, &ctx)
|
||||
}
|
||||
|
||||
/// #4486: the arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press,
|
||||
/// as in Photoshop. With no anchor selected they leave the path alone.
|
||||
#[test]
|
||||
fn arrow_keys_nudge_the_selected_anchors() {
|
||||
let mut app = app(Tool::DirectSelection);
|
||||
with_path(&mut app);
|
||||
// The path stays targeted after a click on empty canvas, but no anchor is selected.
|
||||
click(&mut app, [40.0, 120.0], Modifiers::NONE);
|
||||
click(&mut app, [80.0, 80.0], Modifiers::NONE);
|
||||
assert_eq!(app.ui.direct_selection.target, Some(PathRef::Work));
|
||||
let n = steps(&app);
|
||||
assert!(!press(&mut app, egui::Key::ArrowRight, Modifiers::NONE), "no anchor selected: not Direct Selection's key");
|
||||
assert_eq!(steps(&app), n);
|
||||
click(&mut app, [40.0, 120.0], Modifiers::NONE);
|
||||
click(&mut app, [120.0, 120.0], Modifiers::SHIFT);
|
||||
let (before, n) = (work(&app), steps(&app));
|
||||
assert!(press(&mut app, egui::Key::ArrowRight, Modifiers::NONE));
|
||||
assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 120.0), Point::new(41.0, 120.0)));
|
||||
assert!(press(&mut app, egui::Key::ArrowDown, Modifiers::SHIFT));
|
||||
assert_eq!((anchor(&app, 2), anchor(&app, 3)), (Point::new(121.0, 130.0), Point::new(41.0, 130.0)), "⇧ nudges 10 px");
|
||||
assert_eq!(anchor(&app, 0), Point::new(40.0, 40.0), "unselected anchors stay");
|
||||
assert_eq!(steps(&app), n + 2, "one history step per press");
|
||||
assert!(app.session.undo() && app.session.undo());
|
||||
assert_eq!(work(&app), before);
|
||||
}
|
||||
@@ -288,14 +288,70 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if answer.is_none() && ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Enter)) {
|
||||
answer = buttons.iter().find(|b| b.0 == ButtonRole::Default).map(|b| b.4);
|
||||
}
|
||||
match answer {
|
||||
Some(Answer::Cancel) => app.discard = None,
|
||||
Some(Answer::Discard) => advance(app, ctx),
|
||||
Some(Answer::Save) if save(app, ctx, doc) => advance(app, ctx),
|
||||
_ => {}
|
||||
if let Some(answer) = answer {
|
||||
apply(app, ctx, doc, answer);
|
||||
}
|
||||
}
|
||||
|
||||
/// Acts on the answer about `doc`, the document the prompt is asking about.
|
||||
fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, doc: DocId, answer: Answer) {
|
||||
match answer {
|
||||
Answer::Cancel => app.discard = None,
|
||||
Answer::Discard => advance(app, ctx),
|
||||
Answer::Save if save(app, ctx, doc) => advance(app, ctx),
|
||||
Answer::Save => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The id `ui.inspect` lists the prompt under; `ui.dialog.confirm` and `ui.dialog.cancel` answer
|
||||
/// it by this id, so a control client can see and answer it like the window's buttons (#4920).
|
||||
pub const CONTROL_ID: &str = "discard";
|
||||
|
||||
/// The prompt as `ui.inspect` lists it among the dialogs: the command waiting on it, the document
|
||||
/// it asks about, how many are still to answer, and the choices `ui.dialog.confirm` takes.
|
||||
pub fn inspect(app: &PhotocraftApp) -> Option<Value> {
|
||||
let p = app.discard.as_ref()?;
|
||||
let doc = *p.docs.first()?;
|
||||
let name = index_of(app, doc).and_then(|i| app.session.documents().get(i)).map(|d| d.doc.name.clone())?;
|
||||
let reverts = p.id == "file.revert";
|
||||
let (choices, default): (&[&str], _) = if reverts { (&["dontSave", "cancel"], "dontSave") } else { (&["save", "dontSave", "cancel"], "save") };
|
||||
Some(json!({
|
||||
"id": CONTROL_ID,
|
||||
"kind": "unsavedChanges",
|
||||
"title": if reverts { "Revert" } else { "Unsaved changes" },
|
||||
"fields": {"command": p.id, "document": name, "remaining": p.docs.len(), "choices": choices, "default": default},
|
||||
}))
|
||||
}
|
||||
|
||||
/// The command the prompt holds back and its params, for the automation policy to see before a
|
||||
/// control client answers it.
|
||||
pub fn pending_command(app: &PhotocraftApp) -> Option<(String, Value)> {
|
||||
app.discard.as_ref().map(|p| (p.id.clone(), p.params.clone()))
|
||||
}
|
||||
|
||||
/// Answers the prompt for a control client: `save`, `dontSave` or `cancel` (Revert takes
|
||||
/// `dontSave` or `cancel`). Like the buttons, Save may first ask for a path in the save dialog.
|
||||
pub fn answer_control(app: &mut PhotocraftApp, ctx: &egui::Context, choice: &str) -> Result<Value, String> {
|
||||
let Some(doc) = app.discard.as_ref().and_then(|p| p.docs.first().copied()) else {
|
||||
return Err("no unsaved-changes prompt is open".into());
|
||||
};
|
||||
if app.file_dialog_open() || app.save_options_open() || app.saving() {
|
||||
return Err("the unsaved-changes prompt is waiting for a save to finish".into());
|
||||
}
|
||||
let reverts = app.discard.as_ref().is_some_and(|p| p.id == "file.revert");
|
||||
let answer = match choice {
|
||||
"save" if !reverts => Answer::Save,
|
||||
"dontSave" => Answer::Discard,
|
||||
"cancel" => Answer::Cancel,
|
||||
other => {
|
||||
let choices = if reverts { "dontSave or cancel" } else { "save, dontSave or cancel" };
|
||||
return Err(format!("unknown choice `{other}`: {choices}"));
|
||||
}
|
||||
};
|
||||
apply(app, ctx, doc, answer);
|
||||
Ok(json!({"open": app.discard.is_some(), "fileDialog": app.file_dialog_open()}))
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Answer {
|
||||
Save,
|
||||
|
||||
@@ -149,9 +149,17 @@ impl PhotocraftApp {
|
||||
{
|
||||
suggested = dir.join(suggested);
|
||||
}
|
||||
// The format comes from the extension, so a name typed without one (common where file
|
||||
// extensions are hidden, #5039) gets the suggested file's extension, as Photoshop's
|
||||
// Save As appends the extension of the chosen file type.
|
||||
let suggested_ext = suggested.extension().and_then(|e| e.to_str()).map(|e| e.to_ascii_lowercase());
|
||||
self.ask_file(FileDialogRequest::Save { suggested: suggested.to_string_lossy().into_owned() }, move |app, answer| match answer {
|
||||
FileDialogAnswer::SaveTo(path) => {
|
||||
let path = Self::lowercased_extension(app, path);
|
||||
let path = match &suggested_ext {
|
||||
Some(ext) if Path::new(&path).extension().is_none() => Path::new(&path).with_extension(ext).to_string_lossy().into_owned(),
|
||||
_ => path,
|
||||
};
|
||||
// The web answers a download name, which has no folder to remember.
|
||||
if let Some(doc) = doc
|
||||
&& let Some(dir) = Path::new(&path).parent().filter(|p| !p.as_os_str().is_empty())
|
||||
|
||||
@@ -290,6 +290,26 @@ fn save_paths_get_a_lowercase_extension_when_the_preference_is_on() {
|
||||
assert_eq!(*written.borrow(), ["/pics/CAT.PSD"], "off keeps the user's spelling");
|
||||
}
|
||||
|
||||
/// #5039: a name typed without an extension (where file extensions are hidden) gets the
|
||||
/// suggested file's extension, so the save picks its format instead of failing.
|
||||
#[test]
|
||||
fn save_paths_without_an_extension_get_the_suggested_one() {
|
||||
let (mut app, open, written) = app();
|
||||
let ctx = egui::Context::default();
|
||||
menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
answer(&open, Some(FileDialogAnswer::SaveTo("/pics/cat".into())));
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(*written.borrow(), ["/pics/cat.psd"]);
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("/pics/cat.psd"));
|
||||
// A name that already has an extension is left alone.
|
||||
menus::invoke(&mut app, &ctx, "file.saveAs", json!({})).unwrap();
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
answer(&open, Some(FileDialogAnswer::SaveTo("/pics/dog.png".into())));
|
||||
app.poll_file_dialog(&ctx, None);
|
||||
assert_eq!(*written.borrow(), ["/pics/cat.psd", "/pics/dog.png"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_and_export_dialogs_start_beside_the_document() {
|
||||
let (mut app, open, _) = app();
|
||||
|
||||
@@ -168,6 +168,12 @@ impl PhotocraftApp {
|
||||
DropTarget::Tabs(slot) => Some(slot),
|
||||
DropTarget::Canvas | DropTarget::Elsewhere => None,
|
||||
};
|
||||
// A box still open from an earlier drop (or any Free Transform) is applied first (#4833):
|
||||
// the queue below places the next file only once no box is open, so a separate drop
|
||||
// would otherwise wait unseen for ↩. Files dropped together still go one by one.
|
||||
if target == DropTarget::Canvas && self.ui.transform.is_some() && files.iter().any(|f| !crate::preset_files_ui::is_preset_file(&dropped_name(f))) {
|
||||
crate::transform_tool::commit(self);
|
||||
}
|
||||
for f in files {
|
||||
let name = dropped_name(&f);
|
||||
if target == DropTarget::Canvas && !crate::preset_files_ui::is_preset_file(&name) {
|
||||
|
||||
@@ -464,6 +464,29 @@ fn files_dropped_onto_the_canvas_are_placed_in_free_transform_one_by_one() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #4833: a file dropped on the canvas on its own while the previous one is still in Free
|
||||
/// Transform applies that box and is placed at once, instead of waiting unseen for ↩.
|
||||
#[test]
|
||||
fn a_separate_drop_applies_the_open_transform_and_places_at_once() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app_with_canvas();
|
||||
let (layers, steps) = (layer_count(&app), history_steps(&app));
|
||||
let at = Some(egui::pos2(400.0, 300.0));
|
||||
app.open_dropped(&ctx, vec![dropped("first.png", Ok(png_bytes(4, 4)))], at);
|
||||
app.place_next_dropped(&ctx);
|
||||
assert!(app.ui.transform.is_some(), "the first file is in Free Transform");
|
||||
app.open_dropped(&ctx, vec![dropped("second.png", Ok(png_bytes(2, 2)))], at);
|
||||
app.place_next_dropped(&ctx);
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.doc.layer(st.active_layer.unwrap()).unwrap().name, "second", "placed without waiting for ↩");
|
||||
assert_eq!(app.ui.transform.as_ref().and_then(|t| t.made), Some(crate::state::MadeLayer::Place));
|
||||
// The first place was applied, not taken back: both layers, one Place Embedded step each.
|
||||
assert_eq!(layer_count(&app), layers + 2);
|
||||
assert!(app.drop_places.is_empty());
|
||||
crate::transform_tool::commit(&mut app);
|
||||
assert_eq!(history_steps(&app), steps + 2);
|
||||
}
|
||||
|
||||
/// #1099: switching tabs after an actual canvas drop cancels the place in its source document.
|
||||
#[test]
|
||||
fn switching_documents_after_a_canvas_drop_undoes_only_the_place() {
|
||||
|
||||
@@ -385,6 +385,36 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map<S
|
||||
if command == "view.proofSetup" {
|
||||
proof_setup_defaults(app, fields);
|
||||
}
|
||||
if command == "edit.assignProfile" {
|
||||
assign_profile_defaults(app, fields);
|
||||
}
|
||||
}
|
||||
|
||||
/// Assign Profile offers only the profiles the document's colour mode can take (#4951): the
|
||||
/// command refuses one of another colour space. `__profiles` lists them for the `profile` menu,
|
||||
/// and a remembered choice that doesn't fit this document falls back to the working space.
|
||||
fn assign_profile_defaults(app: &PhotocraftApp, fields: &mut Map<String, Value>) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let Some(spec) = photocraft_engine::commands::find("edit.assignProfile") else { return };
|
||||
let space = photocraft_engine::color_cmds::mode_space(st.doc.mode);
|
||||
let fits = |name: &str| name == "none" || app.session.color.resolve(name, Some(&st.doc), None).is_ok_and(|p| p.color_space == space);
|
||||
let builtin: Vec<String> = parse_spec(spec.params)
|
||||
.into_iter()
|
||||
.filter(|p| p.key == "profile")
|
||||
.flat_map(|p| match p.kind {
|
||||
Kind::Choice { options, .. } => options,
|
||||
_ => Vec::new(),
|
||||
})
|
||||
.collect();
|
||||
let installed: Vec<_> = photocraft_engine::installed_profiles::installed().into_iter().filter(|i| i.is_destination()).collect();
|
||||
let allowed: Vec<String> =
|
||||
builtin.iter().filter(|name| fits(name)).cloned().chain(installed.iter().filter(|i| i.color_space == space).map(|i| i.path.clone())).collect();
|
||||
// A path nobody lists (typed by an agent) is left alone: the command decides about it.
|
||||
let listed = |cur: &str| builtin.iter().any(|name| name == cur) || installed.iter().any(|i| i.path == cur);
|
||||
if fields.get("profile").and_then(Value::as_str).is_some_and(|cur| listed(cur) && !allowed.iter().any(|name| name == cur)) {
|
||||
fields.insert("profile".into(), json!("working"));
|
||||
}
|
||||
fields.insert("__profiles".into(), json!(allowed));
|
||||
}
|
||||
|
||||
/// Alt+Cancel (Reset): schema defaults + command hooks, without last-used remembered prefs.
|
||||
@@ -665,6 +695,12 @@ pub fn body(ui: &mut egui::Ui, f: &mut Map<String, Value>) {
|
||||
Vec::new()
|
||||
};
|
||||
opts.extend(installed.iter().map(|i| (i.path.clone(), i.description.as_str())));
|
||||
// Assign Profile: only what the document's colour mode can take (#4951).
|
||||
if p.key == "profile"
|
||||
&& let Some(allowed) = f.get("__profiles").and_then(Value::as_array)
|
||||
{
|
||||
opts.retain(|(v, _)| allowed.iter().any(|a| a.as_str() == Some(v.as_str())));
|
||||
}
|
||||
// A profile given by path that isn't listed (typed by an agent, or spelled with
|
||||
// different case) still shows, by its file name, instead of a blank menu.
|
||||
let stem = std::path::Path::new(&cur).file_stem().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
@@ -801,10 +837,13 @@ pub fn preview_document_with(
|
||||
k: u32,
|
||||
cancel: Option<&photocraft_engine::jobs::JobCtx>,
|
||||
) -> Option<Document> {
|
||||
preview_document_for_target(doc, active, command, params, k, cancel, photocraft_engine::channel_cmds::ChannelTarget::Composite)
|
||||
preview_document_for_target(doc, active, command, params, k, cancel, photocraft_engine::channel_cmds::ChannelTarget::Composite, &[])
|
||||
}
|
||||
|
||||
/// Run the preview with the same pixel target as the final command, including individual channels.
|
||||
/// `documents` are the open documents in session order: document params (Match Color's Source,
|
||||
/// Displace's map) index into them.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn preview_document_for_target(
|
||||
doc: &Document,
|
||||
active: Option<photocraft_doc::LayerId>,
|
||||
@@ -813,6 +852,7 @@ pub(crate) fn preview_document_for_target(
|
||||
k: u32,
|
||||
cancel: Option<&photocraft_engine::jobs::JobCtx>,
|
||||
target: photocraft_engine::channel_cmds::ChannelTarget,
|
||||
documents: &[Arc<Document>],
|
||||
) -> Option<Document> {
|
||||
if command == crate::select_mask_view::COMMAND {
|
||||
return crate::select_mask_view::preview_document(doc, active, params, k, cancel);
|
||||
@@ -823,12 +863,14 @@ pub(crate) fn preview_document_for_target(
|
||||
let proxy = crate::proxy::proxy_document(doc, run_k);
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.set_inline_job_ctx(cancel.cloned());
|
||||
let doc_id = proxy.id;
|
||||
s.add_document(proxy, None);
|
||||
let mut p = params.clone();
|
||||
add_source_documents(&mut s, doc_id, command, &mut p, documents, run_k);
|
||||
if let Some(id) = active {
|
||||
s.select_layer(id).ok()?;
|
||||
}
|
||||
s.active_mut()?.channel_view.target = target;
|
||||
let mut p = params.clone();
|
||||
if run_k > 1
|
||||
&& let Some(o) = p.as_object_mut()
|
||||
{
|
||||
@@ -855,6 +897,34 @@ pub(crate) fn preview_document_for_target(
|
||||
s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))
|
||||
}
|
||||
|
||||
/// The preview session holds only the proxy of the edited document (index 0), so a document param
|
||||
/// pointing at another open document found nothing there: Match Color's preview with a Source
|
||||
/// document failed, or matched the image to itself (#4851). Add each referenced document (as a
|
||||
/// proxy at the same factor) and point the param at its index in the preview session.
|
||||
fn add_source_documents(s: &mut photocraft_engine::Session, doc_id: photocraft_doc::DocId, command: &str, p: &mut Value, documents: &[Arc<Document>], k: u32) {
|
||||
let Some(spec) = photocraft_engine::commands::find(command) else { return };
|
||||
let Some(o) = p.as_object_mut() else { return };
|
||||
let mut added: Vec<(usize, usize)> = Vec::new();
|
||||
for param in parse_spec(spec.params).into_iter().filter(|p| p.kind == Kind::Document) {
|
||||
let Some(v) = o.get_mut(¶m.key) else { continue };
|
||||
let Some(i) = v.as_u64().and_then(|i| usize::try_from(i).ok()) else { continue };
|
||||
// An index past the open documents stays as given, so the preview fails like OK would.
|
||||
let Some(src) = documents.get(i) else { continue };
|
||||
let at = if src.id == doc_id {
|
||||
0
|
||||
} else if let Some(&(_, at)) = added.iter().find(|(j, _)| *j == i) {
|
||||
at
|
||||
} else {
|
||||
let at = s.add_document(crate::proxy::proxy_document(src, k), None);
|
||||
added.push((i, at));
|
||||
at
|
||||
};
|
||||
*v = json!(at);
|
||||
}
|
||||
// Adding a document makes it active: the command still runs on the edited one.
|
||||
s.set_active(0);
|
||||
}
|
||||
|
||||
/// Cached preview state on the app.
|
||||
pub struct FilterPreview {
|
||||
pub key: FilterPreviewKey,
|
||||
@@ -1319,6 +1389,62 @@ mod tests {
|
||||
assert_eq!(label("wavelengthMin"), "Wavelength Min");
|
||||
}
|
||||
|
||||
/// Match Color's preview reads the Source document from the open documents, as OK does: the
|
||||
/// preview session held only the edited document, so a Source showed no change (#4851).
|
||||
#[test]
|
||||
fn match_color_preview_uses_the_source_document() {
|
||||
use photocraft_doc::{Color, ColorMode, SampleType, Size};
|
||||
let solid = |name: &str, c: [f32; 4]| {
|
||||
let mut d = Document::with_background(name, Size::new(32, 32), ColorMode::Rgb, SampleType::U8, Color::WHITE);
|
||||
d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 32, 32), &c);
|
||||
d.layers[0].surface_mut().unwrap().fill_rect(photocraft_geom::Rect::new(0, 0, 16, 32), &[c[0] * 0.5, c[1] * 0.5, c[2] * 0.5, 1.0]);
|
||||
d
|
||||
};
|
||||
// The source document is open before the edited one, so indices differ between sessions.
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.add_document(solid("reference", [0.1, 0.3, 0.9, 1.0]), None);
|
||||
s.add_document(solid("texture", [0.9, 0.5, 0.2, 1.0]), None);
|
||||
let doc = s.active().unwrap().doc.clone();
|
||||
let layer = doc.layers[0].id;
|
||||
let documents: Vec<_> = s.documents().iter().map(|d| d.doc.clone()).collect();
|
||||
for (source, label) in [(0, "another document"), (1, "the edited document itself")] {
|
||||
let p = json!({"source": source});
|
||||
let mut applied = photocraft_engine::Session::new();
|
||||
for d in &documents {
|
||||
applied.add_document((**d).clone(), None);
|
||||
}
|
||||
applied.execute("image.adjustments.matchColor", p.clone()).unwrap();
|
||||
let want = applied.active().unwrap().doc.layers[0].surface().unwrap().pixel(24, 16);
|
||||
let preview = preview_document_for_target(
|
||||
&doc,
|
||||
Some(layer),
|
||||
"image.adjustments.matchColor",
|
||||
&p,
|
||||
1,
|
||||
None,
|
||||
photocraft_engine::channel_cmds::ChannelTarget::Composite,
|
||||
&documents,
|
||||
)
|
||||
.unwrap_or_else(|| panic!("{label}: no preview"));
|
||||
let got = preview.layers[0].surface().unwrap().pixel(24, 16);
|
||||
assert!((0..3).all(|c| (got[c] - want[c]).abs() < 1.0 / 255.0 + 1e-4), "{label}: preview {got:?}, OK gives {want:?}");
|
||||
}
|
||||
// The preview is of the matched image: the orange texture took the reference's blue.
|
||||
let preview = preview_document_for_target(
|
||||
&doc,
|
||||
Some(layer),
|
||||
"image.adjustments.matchColor",
|
||||
&json!({"source": 0}),
|
||||
2,
|
||||
None,
|
||||
photocraft_engine::channel_cmds::ChannelTarget::Composite,
|
||||
&documents,
|
||||
)
|
||||
.unwrap();
|
||||
let px = preview.layers[0].surface().unwrap().pixel(12, 8);
|
||||
assert!(px[2] > px[0], "proxy preview matched to the reference: {px:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn core_filter_previews_keep_minimum_settings_after_downsampling() {
|
||||
use photocraft_doc::{Color, ColorMode, SampleType, Size};
|
||||
@@ -1931,6 +2057,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The profiles Assign Profile offers for a new document converted with `mode` (if any),
|
||||
/// and which of the command's built-in profiles the command itself accepts for it.
|
||||
fn assign_profile_offers(mode: Option<&str>) -> (Vec<String>, Vec<String>) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
if let Some(mode) = mode {
|
||||
app.run(mode, json!({})).unwrap();
|
||||
}
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
let offered: Vec<String> =
|
||||
app.ui.dialogs.last().unwrap().fields["__profiles"].as_array().unwrap().iter().filter_map(|v| v.as_str().map(str::to_owned)).collect();
|
||||
let spec = photocraft_engine::commands::find("edit.assignProfile").unwrap();
|
||||
let builtin = parse_spec(spec.params).into_iter().find(|p| p.key == "profile").unwrap();
|
||||
let Kind::Choice { options, .. } = builtin.kind else { panic!("profile is a menu") };
|
||||
let accepted = options.into_iter().filter(|name| app.session.execute("edit.assignProfile", json!({"profile": name})).is_ok()).collect();
|
||||
(offered, accepted)
|
||||
}
|
||||
|
||||
/// #4951: Assign Profile lists the profiles the command accepts for the document's colour
|
||||
/// mode, and none of the others.
|
||||
#[test]
|
||||
fn assign_profile_offers_only_profiles_of_the_documents_colour_mode() {
|
||||
for mode in [None, Some("image.mode.cmyk"), Some("image.mode.grayscale")] {
|
||||
let (offered, accepted) = assign_profile_offers(mode);
|
||||
for name in &accepted {
|
||||
assert!(offered.contains(name), "{mode:?}: {name} can be assigned, so it is offered");
|
||||
}
|
||||
for name in ["srgb", "coated-cmyk", "sgray"] {
|
||||
assert_eq!(offered.iter().any(|o| o == name), accepted.iter().any(|a| a == name), "{mode:?}: {name}");
|
||||
}
|
||||
assert!(offered.iter().any(|o| o == "working") && offered.iter().any(|o| o == "none"), "{mode:?}: working space and none always fit");
|
||||
}
|
||||
let (rgb, _) = assign_profile_offers(None);
|
||||
assert!(rgb.iter().any(|o| o == "srgb") && !rgb.iter().any(|o| o == "coated-cmyk"), "an RGB document gets RGB profiles");
|
||||
let (cmyk, _) = assign_profile_offers(Some("image.mode.cmyk"));
|
||||
assert!(cmyk.iter().any(|o| o == "coated-cmyk") && !cmyk.iter().any(|o| o == "srgb"), "a CMYK document gets CMYK profiles");
|
||||
}
|
||||
|
||||
/// #4951: a profile remembered from a document of another colour mode isn't preselected.
|
||||
#[test]
|
||||
fn assign_profile_drops_a_remembered_profile_that_does_not_fit() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "coated-cmyk"}));
|
||||
});
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("working"));
|
||||
app.session.prefs.edit(|prefs| {
|
||||
prefs.dialogs.insert("edit.assignProfile".into(), json!({"profile": "display-p3"}));
|
||||
});
|
||||
open(&mut app, "edit.assignProfile").unwrap();
|
||||
assert_eq!(app.ui.dialogs.last().unwrap().fields["profile"], json!("display-p3"), "one that fits is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schema_dialogs_respect_explicit_dropdown_defaults() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
|
||||
|
||||
@@ -323,6 +323,7 @@ mod tests {
|
||||
k,
|
||||
None,
|
||||
ChannelTarget::Alpha(0),
|
||||
&[],
|
||||
)
|
||||
.unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
|
||||
@@ -638,14 +638,14 @@ impl GpuCanvas {
|
||||
let mut renderer = self.rs.renderer.write();
|
||||
let Some(res) = renderer.callback_resources.get_mut::<Resources>() else { return };
|
||||
if res.docs.keys().any(|k| !live.contains(k)) {
|
||||
let gone: Vec<u64> = res.docs.keys().filter(|k| !live.contains(k)).copied().collect();
|
||||
if let Some(c) = res.compositor.as_mut() {
|
||||
for k in &gone {
|
||||
c.forget_doc(photocraft_doc::DocId(*k));
|
||||
}
|
||||
}
|
||||
res.docs.retain(|k, _| live.contains(k));
|
||||
}
|
||||
// Everything the compositor holds for documents that aren't open, also when their
|
||||
// texture entry was dropped earlier (over budget, a failed render), which used to leave
|
||||
// their pages and effect maps resident after closing (#4529).
|
||||
if let Some(c) = res.compositor.as_mut() {
|
||||
c.retain_docs(|d| live.contains(&d.0));
|
||||
}
|
||||
// LUTs and identity-transform signatures can outlive document textures. Prune both,
|
||||
// or a preserved-ID reopen can skip rebuilding a missing LUT.
|
||||
res.luts.retain(|k, _| live.contains(&k.0));
|
||||
|
||||
@@ -678,6 +678,25 @@ pub fn options_changed(app: &mut PhotocraftApp, before: &crate::state::ToolOptio
|
||||
let _ = app.run(cmds::SET, p);
|
||||
}
|
||||
|
||||
/// Live mode: the options bar's Opacity sets a selected gradient fill layer's opacity, as a
|
||||
/// drag's `opacity` does, live while it is scrubbed; `drag` numbers the scrub so it is one undo
|
||||
/// step, as in the Layers panel (#5012).
|
||||
pub fn opacity_changed(app: &mut PhotocraftApp, drag: Option<u64>) {
|
||||
let o = &app.ui.tool_options;
|
||||
if app.ui.tool != Tool::Gradient || o.gradient_classic {
|
||||
return;
|
||||
}
|
||||
let opacity = o.fill_opacity / 100.0;
|
||||
let Some((l, ..)) = active_gradient(app) else { return };
|
||||
if (l.opacity - opacity).abs() > 1e-6 {
|
||||
let mut p = json!({"layer": l.id.0, "opacity": opacity});
|
||||
if let Some(n) = drag {
|
||||
p["coalesce"] = json!(format!("gradient-tool-opacity:{n}"));
|
||||
}
|
||||
let _ = app.run("layer.setProps", p);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- Properties panel
|
||||
|
||||
/// Properties panel for a live gradient. Every change uses the existing gradient commands.
|
||||
@@ -1257,6 +1276,27 @@ mod tests {
|
||||
assert_eq!(layer.blend, BlendMode::Difference);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_live_gradient_opacity_updates_selected_fill_layer() {
|
||||
let mut app = app_with_gradient("linear");
|
||||
drag(&mut app, [20.0, 60.0], [180.0, 60.0]);
|
||||
let past = app.session.active().unwrap().history.past_len();
|
||||
// A scrub is live on every frame and one undo step.
|
||||
for pct in [70.0, 55.0, 40.0] {
|
||||
app.ui.tool_options.fill_opacity = pct;
|
||||
opacity_changed(&mut app, Some(7));
|
||||
}
|
||||
opacity_changed(&mut app, None);
|
||||
let st = app.session.active().unwrap();
|
||||
assert!((st.doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6);
|
||||
assert_eq!(st.history.past_len(), past + 1, "one undo step, none for an unchanged value");
|
||||
// Classic mode paints pixels: the options bar leaves the layer alone.
|
||||
app.ui.tool_options.gradient_classic = true;
|
||||
app.ui.tool_options.fill_opacity = 80.0;
|
||||
opacity_changed(&mut app, None);
|
||||
assert!((app.session.active().unwrap().doc.layers.last().unwrap().opacity - 0.4).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_shows_the_drag_before_commit() {
|
||||
let mut app = app_with_gradient("radial");
|
||||
|
||||
@@ -157,6 +157,10 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
|
||||
let color = rgb(color).ok_or("invalid guide color")?;
|
||||
let hex = format!("#{:02x}{:02x}{:02x}", color.r(), color.g(), color.b());
|
||||
let result = app.run(COMMAND, params(f))?;
|
||||
// The preview is visible even when guides were hidden. Keep a committed layout visible too.
|
||||
app.ui.view.extras = true;
|
||||
app.ui.view.show.canvas_guides = true;
|
||||
app.ui.extras.guides = true;
|
||||
app.session.prefs.edit(|prefs| prefs.guides_grid_and_slices.guide_color = hex);
|
||||
let mut remembered = f.clone();
|
||||
for key in [MARK, "__command", "__label", "__document", "__previewGuides", "__previewParams", "__previewSource"] {
|
||||
|
||||
@@ -1,5 +1,56 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn applying_a_previewed_layout_reveals_hidden_guides() {
|
||||
for hidden in ["extras", "canvas", "guides"] {
|
||||
let mut app = app();
|
||||
match hidden {
|
||||
"extras" => app.ui.view.extras = false,
|
||||
"canvas" => app.ui.view.show.canvas_guides = false,
|
||||
_ => app.ui.extras.guides = false,
|
||||
}
|
||||
let id = open(&mut app);
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert!(preview(&app, doc).is_some(), "the dialog shows a preview despite hidden {hidden}");
|
||||
crate::dialogs::confirm(&mut app, id).unwrap();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
assert!(!doc.guides.vertical.is_empty(), "the layout was actually created");
|
||||
assert!(preview(&app, doc).is_none(), "the temporary preview is gone");
|
||||
assert!(app.ui.view.shows(app.ui.view.show.canvas_guides) && app.ui.extras.guides, "applied guides must remain visible when {hidden} was hidden");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancelling_invalid_and_empty_layouts_keep_guides_hidden() {
|
||||
for action in ["cancel", "invalid", "empty"] {
|
||||
let mut app = app();
|
||||
app.ui.view.extras = false;
|
||||
app.ui.view.show.canvas_guides = false;
|
||||
app.ui.extras.guides = false;
|
||||
let id = open(&mut app);
|
||||
match action {
|
||||
"cancel" => {
|
||||
crate::dialogs::cancel(&mut app, id).unwrap();
|
||||
}
|
||||
"invalid" => {
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("color".into(), json!("invalid"));
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err());
|
||||
}
|
||||
_ => {
|
||||
let f = &mut app.ui.dialog_mut(id).unwrap().fields;
|
||||
for key in ["__columnsEnabled", "__rowsEnabled", "__marginEnabled"] {
|
||||
f.insert(key.into(), json!(false));
|
||||
}
|
||||
f.insert("clearExisting".into(), json!(true));
|
||||
assert!(crate::dialogs::confirm(&mut app, id).is_err(), "an empty layout is rejected");
|
||||
}
|
||||
}
|
||||
let guides = &app.session.active().unwrap().doc.guides;
|
||||
assert!(guides.vertical.is_empty() && guides.horizontal.is_empty(), "{action}");
|
||||
assert!(!app.ui.view.extras && !app.ui.view.show.canvas_guides && !app.ui.extras.guides, "{action} must not change visibility");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tab_includes_optional_sizes_and_shift_tab_selects_their_text() {
|
||||
let mut app = app();
|
||||
|
||||
@@ -885,6 +885,7 @@
|
||||
Background Pozadí
|
||||
Background Color Barva pozadí
|
||||
Background Contents Obsah pozadí
|
||||
Custom background color Vlastní barva pozadí
|
||||
Balance Vyvážení
|
||||
Baseline Účaří
|
||||
Baseline shift Posun účaří
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -865,6 +865,7 @@
|
||||
Background Hintergrund
|
||||
Background Color Hintergrundfarbe
|
||||
Background Contents Hintergrundinhalte
|
||||
Custom background color Benutzerdefinierte Hintergrundfarbe
|
||||
Balance Balance
|
||||
Baseline Grundlinie
|
||||
Baseline shift Grundlinienverschiebung
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2085,6 +2085,7 @@
|
||||
Avoid Widows/Orphans Αποφυγή μονών γραμμών στην αρχή ή στο τέλος σελίδας
|
||||
BLANK DOCUMENT PRESETS ({n}) ΠΡΟΕΠΙΛΟΓΕΣ ΚΕΝΟΥ ΕΓΓΡΑΦΟΥ ({n})
|
||||
Background Contents Περιεχόμενα φόντου
|
||||
Custom background color Προσαρμοσμένο χρώμα φόντου
|
||||
Background from Layer Φόντο από επίπεδο
|
||||
Baseline Γραμμή βάσης
|
||||
Baseline shift Μετατόπιση γραμμής βάσης
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1029 and column 18.
|
@@ -874,6 +874,7 @@
|
||||
Background Fondo
|
||||
Background Color Color de fondo
|
||||
Background Contents Contenido del fondo
|
||||
Custom background color Color de fondo personalizado
|
||||
Balance Balance
|
||||
Baseline Línea de base
|
||||
Baseline shift Desplazamiento de línea de base
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -860,6 +860,7 @@
|
||||
Background Arrière-plan
|
||||
Background Color Couleur d'arrière-plan
|
||||
Background Contents Contenu de l'arrière-plan
|
||||
Custom background color Couleur d'arrière-plan personnalisée
|
||||
Balance Balance
|
||||
Baseline Ligne de base
|
||||
Baseline shift Décalage de la ligne de base
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -2644,6 +2644,7 @@ cameraRaw Yellow Sárga
|
||||
Autosave minutes Automatikus mentés gyakorisága (perc)
|
||||
Background Color Háttérszín
|
||||
Background Contents Háttér tartalma
|
||||
Custom background color Egyéni háttérszín
|
||||
Batch Kötegelt feldolgozás
|
||||
Binary assets added Hozzáadott bináris elemek
|
||||
Binary assets removed Eltávolított bináris elemek
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -854,6 +854,7 @@
|
||||
Background Background
|
||||
Background Color Warna Background
|
||||
Background Contents Isi Background
|
||||
Custom background color Warna background kustom
|
||||
Balance Keseimbangan
|
||||
Baseline Baseline
|
||||
Baseline shift Geser baseline
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 4 and column 47.
|
@@ -869,6 +869,7 @@
|
||||
Background Sfondo
|
||||
Background Color Colore sfondo
|
||||
Background Contents Contenuto sfondo
|
||||
Custom background color Colore sfondo personalizzato
|
||||
Balance Bilanciamento
|
||||
Baseline Linea base
|
||||
Baseline shift Scostamento linea base
|
||||
|
||||
|
@@ -873,6 +873,7 @@
|
||||
Background 背景
|
||||
Background Color 背景色
|
||||
Background Contents 背景の内容
|
||||
Custom background color カスタム背景色
|
||||
Balance バランス
|
||||
Baseline ベースライン
|
||||
Baseline shift ベースラインシフト
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -848,6 +848,7 @@
|
||||
Background 배경
|
||||
Background Color 배경색
|
||||
Background Contents 배경 내용
|
||||
Custom background color 사용자 정의 배경색
|
||||
Balance 균형
|
||||
Baseline 기준선
|
||||
Baseline shift 기준선 이동
|
||||
|
||||
|
@@ -93,7 +93,8 @@ fn dynamic_brush_sections_have_translations_and_draw_in_the_selected_language()
|
||||
h.state_mut().ui.panels.brush_settings = true;
|
||||
h.run_steps(4);
|
||||
let text = drawn_text(&h);
|
||||
assert!(text.iter().filter(|text| text.as_str() == "画笔笔尖形状").count() >= 2, "both the section row and heading must be translated");
|
||||
// The section row is the only place the name is drawn: the options pane has no heading (#3477).
|
||||
assert_eq!(text.iter().filter(|text| text.as_str() == "画笔笔尖形状").count(), 1, "the section row must be translated");
|
||||
assert!(!text.iter().any(|text| text == "Brush Tip Shape"));
|
||||
});
|
||||
}
|
||||
@@ -388,7 +389,8 @@ fn czech_status_notices_and_navigator_draw_translated_text() {
|
||||
});
|
||||
h.run_steps(4);
|
||||
let text = drawn_text(&h);
|
||||
for want in ["Zvětšení", "Soubor English file.psd se nepodařilo otevřít: disk full", "Předvolby nelze uložit"] {
|
||||
// The Navigator's own text is its tab title now: its zoom row has no label (#4840).
|
||||
for want in ["Navigátor", "Soubor English file.psd se nepodařilo otevřít: disk full", "Předvolby nelze uložit"] {
|
||||
assert!(text.iter().any(|text| text == want), "missing {want}: {text:?}");
|
||||
}
|
||||
// Czech text must be drawable by the bundled fonts, including the new notices.
|
||||
|
||||
@@ -1201,6 +1201,25 @@ mod tests {
|
||||
assert_eq!(tr(Lang::EN, "Seafoam"), "Seafoam");
|
||||
}
|
||||
|
||||
/// These labels are passed to `tl!` dynamically, so the literal coverage scan misses them.
|
||||
#[test]
|
||||
fn russian_dynamic_selection_theme_and_measurement_labels_are_translated() {
|
||||
let ru = Lang::from_code("ru").expect("ru registered");
|
||||
let (inverse_label, _) =
|
||||
crate::canvas_tool_menu::SELECTION_MENU.iter().flatten().find(|(_, id)| *id == "select.inverse").expect("selection menu has Select Inverse");
|
||||
assert_eq!(tr(ru, inverse_label), "Инвертировать выделение");
|
||||
for kind in [crate::theme::ThemeKind::ProLight, crate::theme::ThemeKind::ProLightGray] {
|
||||
assert!(has(ru, kind.label()), "Russian theme label missing {}", kind.label());
|
||||
}
|
||||
for (_, label) in photocraft_engine::analysis_cmds::COLUMNS {
|
||||
assert!(has(ru, label), "Russian measurement header missing {label}");
|
||||
}
|
||||
assert_eq!(tr(ru, "Pro (Light)"), "Pro (светлая)");
|
||||
assert_eq!(tr(ru, "Pro (Light Gray)"), "Pro (светло-серая)");
|
||||
assert_eq!(tr(ru, "Date and Time"), "Дата и время");
|
||||
assert_eq!(tr(ru, "Integrated Density"), "Интегральная плотность");
|
||||
}
|
||||
|
||||
/// Font style labels are built from dynamic words (weights, "Italic"), so the literal
|
||||
/// scanner cannot cover them; "Light" there is a weight, distinct from the Camera Raw
|
||||
/// "Light" section (`type_tool::style_label`).
|
||||
|
||||
@@ -852,6 +852,7 @@
|
||||
Background Achtergrond
|
||||
Background Color Achtergrondkleur
|
||||
Background Contents Achtergrondinhoud
|
||||
Custom background color Aangepaste achtergrondkleur
|
||||
Balance Balans
|
||||
Baseline Basislijn
|
||||
Baseline shift Basislijnverschuiving
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -871,6 +871,7 @@
|
||||
Background Tło
|
||||
Background Color Kolor tła
|
||||
Background Contents Zawartość tła
|
||||
Custom background color Niestandardowy kolor tła
|
||||
Balance Balans
|
||||
Baseline Linia bazowa
|
||||
Baseline shift Przesunięcie linii bazowej
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -854,6 +854,7 @@
|
||||
Background Plano de fundo
|
||||
Background Color Cor de fundo
|
||||
Background Contents Conteúdo do plano de fundo
|
||||
Custom background color Cor de fundo personalizada
|
||||
Balance Equilíbrio
|
||||
Baseline Linha de base
|
||||
Baseline shift Deslocamento da linha de base
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -1527,6 +1527,7 @@
|
||||
Preset Name: Имя набора:
|
||||
Width and Height Ширина и высота
|
||||
Background Contents Содержимое фона
|
||||
Custom background color Свой цвет фона
|
||||
White Белый
|
||||
Background Color Цвет фона
|
||||
Transparent Прозрачный
|
||||
@@ -3071,3 +3072,23 @@ curves Smooth Сгладить
|
||||
@plural {n} action|{n} actions {n} операция|{n} операции|{n} операций
|
||||
Auto Add/Delete Автодобавление/удаление
|
||||
ICO is limited to 256 × 256 pixels ICO ограничен размером 256 × 256 пикселей
|
||||
|
||||
# Dynamic selection context menu and appearance favorites
|
||||
Select Inverse Инвертировать выделение
|
||||
Pro (Light) Pro (светлая)
|
||||
Pro (Light Gray) Pro (светло-серая)
|
||||
|
||||
# Measurement Log column headers (analysis_cmds::COLUMNS)
|
||||
Label Метка
|
||||
Date and Time Дата и время
|
||||
Scale Units Единицы масштаба
|
||||
Scale Factor Коэффициент масштаба
|
||||
Area Площадь
|
||||
Perimeter Периметр
|
||||
Circularity Круглость
|
||||
Gray Value (Minimum) Уровень серого (минимум)
|
||||
Gray Value (Maximum) Уровень серого (максимум)
|
||||
Gray Value (Mean) Уровень серого (среднее)
|
||||
Gray Value (Median) Уровень серого (медиана)
|
||||
Integrated Density Интегральная плотность
|
||||
Length Длина
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -850,6 +850,7 @@
|
||||
Background Pozadina
|
||||
Background Color Boja pozadine
|
||||
Background Contents Sadržaj pozadine
|
||||
Custom background color Prilagođena boja pozadine
|
||||
Balance Balans
|
||||
Baseline Osnovna linija
|
||||
Baseline shift Pomak osnovne linije
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -841,6 +841,7 @@
|
||||
Background Arka plan
|
||||
Background Color Arka Plan Rengi
|
||||
Background Contents Arka Plan İçeriği
|
||||
Custom background color Özel Arka Plan Rengi
|
||||
Balance Bakiye
|
||||
Baseline Temel
|
||||
Baseline shift Taban çizgisi kayması
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 8 and column 34.
|
@@ -1508,6 +1508,7 @@
|
||||
Preset Name: Назва набору:
|
||||
Width and Height Ширина та висота
|
||||
Background Contents Вміст фону
|
||||
Custom background color Довільний колір фону
|
||||
White Білий
|
||||
Background Color Колір фону
|
||||
Transparent Прозорий
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1384 and column 18.
|
@@ -1731,6 +1731,7 @@ cameraRaw Size Kích thước
|
||||
Resolution: Độ phân giải:
|
||||
Color Mode Chế độ màu
|
||||
Background Contents Nội dung nền
|
||||
Custom background color Màu nền tùy chỉnh
|
||||
Pixels/Inch Pixel/inch
|
||||
Pixels/Centimeter Pixel/centimet
|
||||
White Trắng
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -877,6 +877,7 @@
|
||||
Background 背景
|
||||
Background Color 背景颜色
|
||||
Background Contents 背景内容
|
||||
Custom background color 自定背景颜色
|
||||
Balance 平衡
|
||||
Baseline 基线
|
||||
Baseline shift 基线偏移
|
||||
|
||||
|
@@ -880,6 +880,7 @@
|
||||
Background 背景
|
||||
Background Color 背景色
|
||||
Background Contents 背景內容
|
||||
Custom background color 自訂背景色
|
||||
Balance 平衡
|
||||
Baseline 基線
|
||||
Baseline shift 基線位移
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 6 and column 47.
|
@@ -503,6 +503,14 @@ pub fn initial_fields(layer: &Layer, select: Option<&str>, light: f32) -> Map<St
|
||||
}
|
||||
|
||||
pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option<u64> {
|
||||
// An open Free Transform box is applied first, as in Photoshop (#4821): the canvas shows the
|
||||
// box's preview while it is open, so the dialog's preview would not show until Enter.
|
||||
if app.ui.transform.is_some() {
|
||||
crate::transform_tool::commit(app);
|
||||
if app.ui.transform.is_some() && crate::transform_tool::committing(app).is_none() {
|
||||
return None; // refused: the box stays open, with the reason in the status bar
|
||||
}
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
let layer = st.doc.layer(st.active_layer?)?.clone();
|
||||
let light = st.doc.global_light.angle;
|
||||
|
||||
@@ -502,6 +502,11 @@ pub struct PhotocraftApp {
|
||||
/// `canvas::display_doc`'s live-adjust and Duotone documents per document: (snapshot,
|
||||
/// preview key, the document shown).
|
||||
display_memo: HashMap<DocId, (std::sync::Weak<Document>, u64, std::sync::Arc<Document>)>,
|
||||
/// The main canvas's last GPU view of each document while it shows the plain document on
|
||||
/// the GPU canvas: the Navigator draws the same texture at its own size (#4518).
|
||||
navigator_gpu: HashMap<DocId, crate::gpu_canvas::ViewParams>,
|
||||
/// Documents whose GPU canvas texture holds the plain document (`canvas::ensure_gpu`).
|
||||
navigator_plain: std::collections::HashSet<DocId>,
|
||||
/// Display profile readings (#569).
|
||||
monitors: monitor_status::State,
|
||||
checker: Option<egui::TextureHandle>,
|
||||
@@ -755,6 +760,8 @@ impl PhotocraftApp {
|
||||
canvases: HashMap::new(),
|
||||
navigator_textures: HashMap::new(),
|
||||
display_memo: HashMap::new(),
|
||||
navigator_gpu: HashMap::new(),
|
||||
navigator_plain: std::collections::HashSet::new(),
|
||||
monitors: Default::default(),
|
||||
checker: None,
|
||||
drag: None,
|
||||
@@ -1116,6 +1123,8 @@ impl PhotocraftApp {
|
||||
self.ui.polygon.clear();
|
||||
self.ui.polygon_mode.clear();
|
||||
}
|
||||
// ... and to the document it was started on.
|
||||
crate::canvas::polygon_cancel_stale(self);
|
||||
crate::crop_ui::cancel_stale(self);
|
||||
let ids: Vec<DocId> = self.session.documents().iter().map(|d| d.doc.id).collect();
|
||||
// Where the document of view `i` is now. Views not tracked yet keep their index.
|
||||
@@ -1840,6 +1849,9 @@ impl eframe::App for PhotocraftApp {
|
||||
notices::show(self, &ctx);
|
||||
gpu_status::show_fallback(self, &ctx);
|
||||
kys_import::show_offer(self, &ctx);
|
||||
if chrome && self.ui.panels.menu_bar && self.custom_titlebar && !self.ui.dialogs.is_empty() {
|
||||
titlebar::modal_drag_overlay(&ctx);
|
||||
}
|
||||
if self.custom_titlebar {
|
||||
titlebar::resize_zones(ui);
|
||||
}
|
||||
@@ -2432,6 +2444,9 @@ impl PhotocraftApp {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod navigator_gpu_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod color_swatch_tests;
|
||||
|
||||
|
||||
@@ -1118,6 +1118,17 @@ pub fn menu_items(app: &PhotocraftApp) -> Vec<MenuItem> {
|
||||
it.color = prefs.menus.colors.get(&it.id).cloned();
|
||||
}
|
||||
}
|
||||
// Layer › Create Clipping Mask is Photoshop's one Create / Release item: when its shortcut
|
||||
// would release ([`crate::shortcut_dispatch::clip_key_releases`]) it reads Release Clipping
|
||||
// Mask and runs it, keeping that shortcut. The engine's own Release item lives in that slot.
|
||||
items.retain(|i| i.id != "layer.releaseClippingMask");
|
||||
if crate::shortcut_dispatch::clip_key_releases(app)
|
||||
&& let Some(item) = items.iter_mut().find(|i| i.id == "layer.createClippingMask")
|
||||
{
|
||||
item.id = "layer.releaseClippingMask".into();
|
||||
item.label = "Release Clipping Mask".into();
|
||||
item.enabled = is_enabled(app, &item.id);
|
||||
}
|
||||
items
|
||||
}
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ pub fn arrow_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
use egui::{Key, Modifiers};
|
||||
let cmd = ctx.input(|i| i.modifiers.command) && crate::hold_keys::cmd_nudges(app);
|
||||
if app.ui.tool != Tool::Move && app.ui.transform.is_none() && !cmd {
|
||||
return selection_arrow_keys(app, ctx) || brush_arrow_keys(app, ctx);
|
||||
return selection_arrow_keys(app, ctx) || crate::direct_select::arrow_keys(app, ctx) || brush_arrow_keys(app, ctx);
|
||||
}
|
||||
// `consume_key` never ignores an extra ⌘, so it is part of every pattern while it moves.
|
||||
let base = if cmd { Modifiers::COMMAND } else { Modifiers::NONE };
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
//! The Navigator draws the GPU canvas's own texture while the canvas is on the GPU (#4518), so an
|
||||
//! edit costs it no CPU composite; elsewhere (a flipped view draws on the CPU) it keeps the CPU
|
||||
//! thumbnail. Renders the real app offscreen; skips without a GPU adapter.
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
type Harness = egui_kittest::Harness<'static, PhotocraftApp>;
|
||||
|
||||
fn harness() -> Option<Harness> {
|
||||
let built = std::panic::catch_unwind(|| {
|
||||
egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_pixels_per_point(1.0).with_max_steps(64).wgpu().build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
if let Some(rs) = cc.wgpu_render_state.as_ref() {
|
||||
app.set_wgpu(rs.clone());
|
||||
}
|
||||
app.ui.panels.navigator = true;
|
||||
app.run("file.new", json!({"width": 400, "height": 300, "background": "white"})).unwrap();
|
||||
app.run("select.rect", json!({"x": 0, "y": 0, "width": 200, "height": 300})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
app.run("select.deselect", json!({})).unwrap();
|
||||
app.sync_views();
|
||||
app
|
||||
})
|
||||
});
|
||||
match built {
|
||||
Ok(h) => Some(h),
|
||||
Err(_) => {
|
||||
eprintln!("skipping: no GPU adapter");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour at fractions (`fx`, `fy`) of the Navigator preview.
|
||||
fn preview_px(h: &mut Harness, fx: f32, fy: f32) -> [u8; 4] {
|
||||
let r = crate::panels::last_navigator_preview(&h.ctx).expect("navigator preview drawn");
|
||||
let img = h.render().expect("render");
|
||||
let (x, y) = ((r.left() + r.width() * fx) as u32, (r.top() + r.height() * fy) as u32);
|
||||
img.get_pixel(x, y).0
|
||||
}
|
||||
|
||||
fn near(a: [u8; 4], b: [u8; 3]) -> bool {
|
||||
(0..3).all(|i| a[i].abs_diff(b[i]) <= 8)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn navigator_draws_the_gpu_canvas_texture_and_follows_edits() {
|
||||
let Some(mut h) = harness() else { return };
|
||||
h.run_steps(8);
|
||||
if !h.state().perf.gpu {
|
||||
eprintln!("skipping: the canvas fell back to the CPU here");
|
||||
return;
|
||||
}
|
||||
let id = h.state().session.active().expect("doc").doc.id;
|
||||
assert!(h.state().navigator_gpu.contains_key(&id), "the Navigator uses the GPU canvas view");
|
||||
assert!(!h.state().navigator_textures.contains_key(&id), "no CPU thumbnail was built");
|
||||
assert!(near(preview_px(&mut h, 0.25, 0.5), [255, 0, 0]), "left half red");
|
||||
assert!(near(preview_px(&mut h, 0.75, 0.5), [255, 255, 255]), "right half white");
|
||||
|
||||
// An edit shows in the Navigator, still without a CPU thumbnail.
|
||||
h.state_mut().run("select.rect", json!({"x": 200, "y": 0, "width": 200, "height": 300})).unwrap();
|
||||
h.state_mut().run("edit.fill", json!({"color": "#0000ff"})).unwrap();
|
||||
h.run_steps(6);
|
||||
assert!(near(preview_px(&mut h, 0.75, 0.5), [0, 0, 255]), "right half now blue");
|
||||
assert!(!h.state().navigator_textures.contains_key(&id));
|
||||
|
||||
// A flipped view draws on the CPU: the Navigator goes back to its CPU thumbnail.
|
||||
h.state_mut().ui.view.flip_horizontal = true;
|
||||
h.run_steps(6);
|
||||
assert!(!h.state().navigator_gpu.contains_key(&id), "no GPU view while the canvas draws on the CPU");
|
||||
assert!(h.state().navigator_textures.contains_key(&id), "the CPU thumbnail again");
|
||||
assert!(near(preview_px(&mut h, 0.25, 0.5), [255, 0, 0]) && near(preview_px(&mut h, 0.75, 0.5), [0, 0, 255]), "same picture, unflipped");
|
||||
}
|
||||
@@ -285,6 +285,31 @@ fn page_icon(ui: &egui::Ui, r: Rect, w: u32, h: u32, t: &Tokens) {
|
||||
ui.painter().rect_stroke(page, 1.0, Stroke::new(1.2, t.text_dim), StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// The Background Contents menu's entry for a colour of the user's own ([`body`]).
|
||||
const CUSTOM: &str = "custom";
|
||||
/// Side of the Background Contents colour swatch.
|
||||
const SWATCH: f32 = 22.0;
|
||||
|
||||
/// The colour the new document's background starts with: white, black, the captured or current
|
||||
/// toolbox background colour, or a custom `"#rrggbb"`; `None` for Transparent.
|
||||
fn background_rgb(app: &crate::PhotocraftApp, f: &Map<String, Value>) -> Option<[f32; 3]> {
|
||||
let bg = get_s(f, "background", "white");
|
||||
match bg.as_str() {
|
||||
"transparent" => None,
|
||||
"black" => Some([0.0; 3]),
|
||||
"backgroundColor" => Some(
|
||||
f.get("backgroundColor")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|a| Some([a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32, a.get(2)?.as_f64()? as f32]))
|
||||
.unwrap_or_else(|| {
|
||||
let b = app.session.tools.background;
|
||||
[b[0], b[1], b[2]]
|
||||
}),
|
||||
),
|
||||
hex => Some(crate::color_picker_ui::parse_hex(hex).unwrap_or([1.0; 3])),
|
||||
}
|
||||
}
|
||||
|
||||
/// Restore a snapshot without replacing the new document's name or its clipboard offer.
|
||||
pub fn apply_saved_preset(f: &mut Map<String, Value>, preset: &photocraft_engine::document_preset_cmds::DocumentPreset) {
|
||||
apply_settings(f, &preset.settings);
|
||||
@@ -681,19 +706,57 @@ pub fn body(app: &mut crate::PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<Strin
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
small_label(ui, tl!("Background Contents"));
|
||||
let mut bg = get_s(f, "background", "white");
|
||||
// A custom colour is kept as its "#rrggbb", which `file.new` takes as is (#4789).
|
||||
let current = get_s(f, "background", "white");
|
||||
let mut bg = if crate::color_picker_ui::parse_hex(¤t).is_some() { CUSTOM.to_string() } else { current.clone() };
|
||||
let opts = [
|
||||
("white".to_string(), tl!("White")),
|
||||
("black".to_string(), tl!("Black")),
|
||||
("backgroundColor".to_string(), tl!("Background Color")),
|
||||
("transparent".to_string(), tl!("Transparent")),
|
||||
(CUSTOM.to_string(), tl!("Custom…")),
|
||||
];
|
||||
if widgets::dropdown(ui, "nd-bg", &mut bg, &opts, 240.0) {
|
||||
f.insert("background".into(), json!(bg));
|
||||
f.remove("__savedPreset");
|
||||
// A fresh choice of Background Color uses today's toolbox colour. Selecting a
|
||||
// saved preset instead restores the colour captured when it was saved.
|
||||
let shown = background_rgb(app, f);
|
||||
let mut pick = false;
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::dropdown(ui, "nd-bg", &mut bg, &opts, 240.0 - SWATCH - 6.0) {
|
||||
if bg == CUSTOM {
|
||||
// Custom… opens the Color Picker on the colour shown so far.
|
||||
pick = true;
|
||||
} else {
|
||||
f.insert("background".into(), json!(bg));
|
||||
}
|
||||
f.remove("__savedPreset");
|
||||
// A fresh choice of Background Color uses today's toolbox colour. Selecting a
|
||||
// saved preset instead restores the colour captured when it was saved.
|
||||
f.remove("backgroundColor");
|
||||
}
|
||||
// Photoshop's swatch beside the menu: the colour the canvas starts with; a click
|
||||
// opens the Color Picker, as Custom… does.
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(SWATCH, SWATCH), Sense::click());
|
||||
match shown {
|
||||
Some(c) => {
|
||||
ui.painter().rect_filled(
|
||||
r,
|
||||
2.0,
|
||||
egui::Color32::from_rgb((c[0] * 255.0).round() as u8, (c[1] * 255.0).round() as u8, (c[2] * 255.0).round() as u8),
|
||||
);
|
||||
}
|
||||
None => widgets::checker(ui.painter(), r, 4.0),
|
||||
}
|
||||
ui.painter().rect_stroke(r, 2.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), StrokeKind::Inside);
|
||||
let resp = resp.on_hover_text(tl!("Custom background color")).on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Custom background color")));
|
||||
if resp.clicked() {
|
||||
pick = true;
|
||||
f.remove("__savedPreset");
|
||||
}
|
||||
});
|
||||
if pick {
|
||||
let start = shown.unwrap_or([1.0; 3]);
|
||||
f.insert("background".into(), json!(crate::color_picker_ui::hex(start)));
|
||||
f.remove("backgroundColor");
|
||||
crate::color_picker_ui::request_field(f, "background", &crate::color_picker_ui::title_for(tl!("Background Contents")));
|
||||
}
|
||||
save_preset(app, ui, f);
|
||||
});
|
||||
@@ -977,6 +1040,48 @@ mod tests {
|
||||
h
|
||||
}
|
||||
|
||||
/// #4789: the swatch beside Background Contents (and Custom…) opens the Color Picker; its
|
||||
/// colour becomes the new document's background (kept as its "#rrggbb").
|
||||
#[test]
|
||||
fn a_custom_background_color_is_picked_and_used() {
|
||||
let mut h = harness_with_store(&Arc::new(Mutex::new(None)));
|
||||
let nd = h.state().ui.dialogs[0].id;
|
||||
assert!(h.query_by_label("Custom background color").is_some());
|
||||
h.get_by_label("Custom background color").click();
|
||||
h.run_steps(3);
|
||||
let picker = h
|
||||
.state()
|
||||
.ui
|
||||
.dialogs
|
||||
.iter()
|
||||
.find(|d| d.fields.get("__dialog").and_then(serde_json::Value::as_u64) == Some(nd))
|
||||
.map(|d| d.id)
|
||||
.expect("the Color Picker opens over the dialog");
|
||||
h.state_mut().ui.dialog_mut(picker).unwrap().fields.insert("color".into(), serde_json::json!("#336699"));
|
||||
crate::dialogs::confirm(h.state_mut(), picker).unwrap();
|
||||
h.run_steps(3);
|
||||
let bg = h.state().ui.dialogs.iter().find(|d| d.id == nd).unwrap().fields["background"].clone();
|
||||
assert_eq!(bg, "#336699");
|
||||
crate::dialogs::confirm(h.state_mut(), nd).unwrap();
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
let px = photocraft_compose::flatten(doc).px[0];
|
||||
assert!((px[0] * 255.0 - 51.0).abs() < 1.0 && (px[1] * 255.0 - 102.0).abs() < 1.0 && (px[2] * 255.0 - 153.0).abs() < 1.0, "{px:?}");
|
||||
}
|
||||
|
||||
/// #4789: the swatch shows what each Background Contents choice paints, Background Color included.
|
||||
#[test]
|
||||
fn the_swatch_shows_each_background_choice() {
|
||||
let mut h = harness_with_store(&Arc::new(Mutex::new(None)));
|
||||
h.state_mut().run("tools.setColors", serde_json::json!({"foreground": "#000000", "background": "#336699"})).unwrap();
|
||||
let rgb = |bg: &str| super::super::background_rgb(h.state(), serde_json::json!({ "background": bg }).as_object().unwrap());
|
||||
assert_eq!(rgb("white"), Some([1.0; 3]));
|
||||
assert_eq!(rgb("black"), Some([0.0; 3]));
|
||||
assert_eq!(rgb("transparent"), None);
|
||||
assert_eq!(rgb("#ff0000"), Some([1.0, 0.0, 0.0]));
|
||||
let c = rgb("backgroundColor").expect("Background Color shows the toolbox colour");
|
||||
assert!((c[0] * 255.0 - 51.0).abs() < 1.0 && (c[1] * 255.0 - 102.0).abs() < 1.0 && (c[2] * 255.0 - 153.0).abs() < 1.0, "{c:?}");
|
||||
}
|
||||
|
||||
fn name_preset(h: &mut Harness<'static, PhotocraftApp>, name: &str) {
|
||||
h.get_by_label("Save Preset…").click();
|
||||
h.run_steps(2);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The Layers panel New Layer button: a click makes a layer at once, ⌥-click opens the New Layer
|
||||
//! dialog first, as in Photoshop.
|
||||
//! dialog first, as in Photoshop. Its shortcut is the same pair the other way round: ⇧⌘N asks
|
||||
//! first, ⌥⇧⌘N makes the layer at once (#4794).
|
||||
|
||||
use egui::Modifiers;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
@@ -41,3 +42,46 @@ fn alt_click_opens_the_new_layer_dialog() {
|
||||
crate::dialogs::confirm(h.state_mut(), id).unwrap();
|
||||
assert_eq!(layers(&h), 2);
|
||||
}
|
||||
|
||||
fn dialog_open(h: &egui_kittest::Harness<'static, PhotocraftApp>) -> bool {
|
||||
h.state().ui.dialogs.iter().any(|d| crate::new_layer_ui::owns(&d.fields))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_asks_first_and_alt_shortcut_makes_a_layer_at_once() {
|
||||
let mut h = panel();
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 1, "⇧⌘N asks first");
|
||||
assert!(dialog_open(&h), "the New Layer dialog");
|
||||
|
||||
let mut h = panel();
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2, "⌥⇧⌘N makes the layer");
|
||||
assert!(!dialog_open(&h));
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 3, "once per press");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_shortcut_follows_a_custom_new_layer_shortcut_and_yields_to_a_bound_command() {
|
||||
// Rebound to F2: ⌥F2 makes the layer at once.
|
||||
let mut h = panel();
|
||||
h.state_mut().session.prefs.edit(|p| p.shortcuts.insert("layer.new.layer".into(), "F2".into()));
|
||||
h.key_press_modifiers(Modifiers::ALT, egui::Key::F2);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2);
|
||||
assert!(!dialog_open(&h));
|
||||
// A command bound to ⌥⇧⌘N itself keeps the key.
|
||||
let mut h = panel();
|
||||
h.state_mut().session.prefs.edit(|p| p.shortcuts.insert("layer.new.layerViaCopy".into(), "Cmd+Alt+Shift+N".into()));
|
||||
h.key_press_modifiers(Modifiers::COMMAND | Modifiers::SHIFT | Modifiers::ALT, egui::Key::N);
|
||||
h.run_steps(4);
|
||||
assert_eq!(layers(&h), 2);
|
||||
assert!(!dialog_open(&h));
|
||||
let doc = &h.state().session.active().unwrap().doc;
|
||||
let top = doc.layers.last().unwrap().surface().unwrap();
|
||||
assert!(!top.content_bounds().is_empty(), "Layer via Copy ran (the white background copied), not New Layer");
|
||||
}
|
||||
+126
-29
@@ -189,7 +189,14 @@ pub fn toolbar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(0.35 - seconds));
|
||||
}
|
||||
let long_press = held_for.is_some_and(|seconds| seconds >= 0.35);
|
||||
if slot.len() > 1 && (resp.secondary_clicked() || long_press) {
|
||||
// Clicking the button of its open flyout again, with either button, closes
|
||||
// it (#4932); the release that ends the long press that opened it doesn't.
|
||||
let open_here = ui.data(|d| d.get_temp::<(egui::Id, Rect)>(flyout_id)).is_some_and(|(k, _)| k == key);
|
||||
let reclicked = open_here
|
||||
&& (resp.secondary_clicked() || (resp.clicked() && ui.data(|d| d.get_temp::<egui::Id>(held_id)) != Some(key)));
|
||||
if reclicked {
|
||||
ui.data_mut(|d| d.remove::<(egui::Id, Rect)>(flyout_id));
|
||||
} else if slot.len() > 1 && (resp.secondary_clicked() || long_press) {
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(flyout_id, (key, resp.rect));
|
||||
if long_press {
|
||||
@@ -580,6 +587,7 @@ pub fn title_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let span_id = ui.id().with("titledrag-span");
|
||||
let (gap_l, gap_r) = ui.ctx().data(|d| d.get_temp::<(f32, f32)>(span_id)).unwrap_or((full.right(), full.right()));
|
||||
let gap = egui::Rect::from_x_y_ranges(gap_l.max(full.left())..=gap_r.min(full.right()).max(gap_l), full.y_range());
|
||||
ui.ctx().data_mut(|d| d.insert_temp(crate::titlebar::modal_drag_area_id(), gap));
|
||||
let drag = ui.interact(gap, ui.id().with("titledrag"), Sense::click_and_drag());
|
||||
if drag.drag_started() {
|
||||
ui.ctx().send_viewport_cmd(egui::ViewportCommand::StartDrag);
|
||||
@@ -956,7 +964,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
crate::transform_tool::options_bar(app, ui);
|
||||
return;
|
||||
}
|
||||
if crate::distort_ui::options_bar(app, ui) {
|
||||
if crate::symmetry_ui::options_bar(app, ui) || crate::distort_ui::options_bar(app, ui) {
|
||||
return;
|
||||
}
|
||||
let tool = app.ui.tool;
|
||||
@@ -1257,7 +1265,17 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
// The wheel over it steps the mode, as over the Layers panel's (#2061).
|
||||
widgets::dropdown_wheel_hovered(ui, "gradient-blend-mode", &mut app.ui.tool_options.gradient_blend_mode, &opts, 96.0);
|
||||
opt_label(ui, tl!("Opacity"));
|
||||
widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);
|
||||
let r = widgets::value_field(ui, &mut app.ui.tool_options.fill_opacity, 1.0..=100.0, "%", 62.0);
|
||||
// Live while scrubbed, one undo step per scrub (#5012).
|
||||
let drag_key = r.id.with("gradient-opacity-drag");
|
||||
if r.drag_started() {
|
||||
let n = ui.ctx().cumulative_pass_nr();
|
||||
ui.data_mut(|d| d.insert_temp(drag_key, n));
|
||||
}
|
||||
if r.changed() {
|
||||
let drag = if r.dragged() { ui.data(|d| d.get_temp::<u64>(drag_key)) } else { None };
|
||||
crate::gradient_ui::opacity_changed(app, drag);
|
||||
}
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.gradient_reverse, tl!("Reverse"));
|
||||
widgets::checkbox(ui, &mut app.ui.tool_options.gradient_dither, tl!("Dither"));
|
||||
// Live mode: the options also change a selected gradient fill layer.
|
||||
@@ -1861,7 +1879,6 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
return;
|
||||
};
|
||||
let ctx = ui.ctx().clone();
|
||||
let Some(tex) = crate::canvas::navigator_texture(app, &ctx, idx) else { return };
|
||||
let size = app.session.documents()[idx].doc.size;
|
||||
let avail = ui.available_width();
|
||||
// The preview fills the group's height above the zoom controls (their height as measured
|
||||
@@ -1873,8 +1890,16 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
ui.painter().rect_filled(frame, t.radius_sm, t.canvas);
|
||||
let rect = navigator_fit(frame, size.width, size.height);
|
||||
ui.data_mut(|d| d.insert_temp(navigator_preview_id(), rect));
|
||||
widgets::checker(ui.painter(), rect, 6.0);
|
||||
ui.painter().image(tex, rect, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
|
||||
// On the GPU canvas, its own texture at this size (#4518); otherwise the CPU thumbnail.
|
||||
if let Some(params) = crate::canvas::navigator_gpu_view(app, idx, rect, &ctx) {
|
||||
crate::gpu_canvas::GpuCanvas::paint(ui.painter(), rect, params);
|
||||
} else if crate::canvas::navigator_waits_for_gpu(app, idx, &ctx) {
|
||||
widgets::checker(ui.painter(), rect, 6.0);
|
||||
} else {
|
||||
let Some(tex) = crate::canvas::navigator_texture(app, &ctx, idx) else { return };
|
||||
widgets::checker(ui.painter(), rect, 6.0);
|
||||
ui.painter().image(tex, rect, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
let s = rect.width() / size.width.max(1) as f32;
|
||||
if (resp.clicked() || resp.dragged())
|
||||
&& let Some(pp) = resp.interact_pointer_pos()
|
||||
@@ -1908,29 +1933,38 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let c = pos2(rect.min.x + v.center[0] * s, rect.min.y + v.center[1] * s);
|
||||
let vr = Rect::from_center_size(c, vec2(vw, vh)).intersect(frame.shrink(1.0));
|
||||
ui.painter().rect_stroke(vr, 2.0, Stroke::new(1.5, Color32::from_rgb(255, 84, 84)), StrokeKind::Middle);
|
||||
// Photoshop's one row under the preview (#4840): the zoom, typed in percent, then Zoom Out,
|
||||
// the slider and Zoom In.
|
||||
let controls = ui.vertical(|ui| {
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
label(ui, crate::i18n::tr_ctx(crate::i18n::current(), "navigator", "Zoom"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
for (lbl, z) in [("200%", 2.0), ("100%", 1.0)] {
|
||||
if widgets::pill_tab(ui, lbl, (v.zoom - z).abs() < 1e-3).clicked() {
|
||||
app.ui.views[idx].zoom = z;
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
}
|
||||
}
|
||||
if widgets::pill_tab(ui, tl!("Fit"), false).clicked() {
|
||||
app.ui.views[idx].fit_pending = true;
|
||||
}
|
||||
});
|
||||
ui.spacing_mut().item_spacing.x = 4.0;
|
||||
let set = |app: &mut PhotocraftApp, zoom: f32| {
|
||||
app.ui.views[idx].zoom = crate::zoom_levels::clamp(zoom, v.doc_size);
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
};
|
||||
let mut pct = v.zoom * 100.0;
|
||||
let field = widgets::compact_wrapping_value_field(ui, &mut pct, crate::zoom_levels::percent_range(&app.ui.views[idx]), "%", vec2(64.0, NAV_ROW_H));
|
||||
if field.changed() {
|
||||
set(app, pct / 100.0);
|
||||
}
|
||||
let out = crate::brush_picker::named(icons::button(ui, "minus", NAV_ROW_H, false, tl!("Zoom Out")), "Zoom Out");
|
||||
if out.clicked() {
|
||||
set(app, crate::zoom_levels::step(v.zoom, -1, v.doc_size));
|
||||
}
|
||||
// The whole zoom range, and always the current zoom: a narrower slider would pull it back.
|
||||
let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2());
|
||||
let mut lz = v.zoom.log2();
|
||||
let slider_w = (ui.available_width() - NAV_ROW_H - 4.0).max(60.0);
|
||||
let slid = ui.allocate_ui(vec2(slider_w, NAV_ROW_H), |ui| lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed()).inner;
|
||||
if slid {
|
||||
set(app, 2f32.powf(lz));
|
||||
}
|
||||
let zin = crate::brush_picker::named(icons::button(ui, "plus", NAV_ROW_H, false, tl!("Zoom In")), "Zoom In");
|
||||
if zin.clicked() {
|
||||
set(app, crate::zoom_levels::step(v.zoom, 1, v.doc_size));
|
||||
}
|
||||
});
|
||||
// The whole zoom range, and always the current zoom: a narrower slider would pull it back.
|
||||
let (lo, hi) = (crate::zoom_levels::min(v.doc_size).min(v.zoom).log2(), crate::zoom_levels::MAX.max(v.zoom).log2());
|
||||
let mut lz = v.zoom.log2();
|
||||
if lz.is_finite() && widgets::slider(ui, &mut lz, lo..=hi, None).changed() {
|
||||
app.ui.views[idx].zoom = crate::zoom_levels::clamp(2f32.powf(lz), v.doc_size);
|
||||
app.ui.views[idx].fit_pending = false;
|
||||
}
|
||||
});
|
||||
// From the preview's bottom, so the spacing above the controls counts too.
|
||||
let controls = Rect::from_min_max(pos2(frame.left(), frame.bottom()), pos2(frame.right(), controls.response.rect.bottom()));
|
||||
@@ -1940,6 +1974,9 @@ fn navigator(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
});
|
||||
}
|
||||
|
||||
/// Height of the Navigator's zoom row: its field, buttons and slider.
|
||||
const NAV_ROW_H: f32 = 22.0;
|
||||
|
||||
/// The document's `w` × `h` fitted inside the Navigator's `frame` with an 8 pt inset, centred and
|
||||
/// keeping its aspect.
|
||||
fn navigator_fit(frame: Rect, w: u32, h: u32) -> Rect {
|
||||
@@ -2010,6 +2047,33 @@ mod navigator_wheel_tests {
|
||||
frame(&mut app, &ctx, below, 1.0);
|
||||
assert!((app.ui.views[0].zoom - 1.0).abs() < 1e-4, "wheel outside preview leaves zoom unchanged");
|
||||
}
|
||||
|
||||
/// #4840: under the preview, one row as in Photoshop: the zoom in percent, Zoom Out, the
|
||||
/// slider and Zoom In. The buttons step the zoom like View › Zoom In / Out.
|
||||
#[test]
|
||||
fn navigator_zoom_row_is_one_line_and_its_buttons_step_the_zoom() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
app.sync_views();
|
||||
app.ui.views[0].zoom = 1.0;
|
||||
app.ui.views[0].fit_pending = false;
|
||||
let mut h = egui_kittest::Harness::builder().with_size(vec2(360.0, 300.0)).build_ui_state(|ui, app: &mut PhotocraftApp| navigator(app, ui), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h.run_steps(4);
|
||||
let row = last_navigator_controls(&h.ctx).expect("the zoom row");
|
||||
assert!(row.height() <= NAV_ROW_H + 14.0, "one row (with the gap above it): {row:?}");
|
||||
let zoom = |h: &egui_kittest::Harness<'_, PhotocraftApp>| h.state().ui.views[0].zoom;
|
||||
h.get_by_label("Zoom In").click();
|
||||
h.run_steps(2);
|
||||
assert!((zoom(&h) - crate::zoom_levels::step(1.0, 1, [200, 100])).abs() < 1e-4, "{}", zoom(&h));
|
||||
h.get_by_label("Zoom Out").click();
|
||||
h.run_steps(2);
|
||||
h.get_by_label("Zoom Out").click();
|
||||
h.run_steps(2);
|
||||
assert!((zoom(&h) - crate::zoom_levels::step(1.0, -1, [200, 100])).abs() < 1e-4, "{}", zoom(&h));
|
||||
assert!(!h.state().ui.views[0].fit_pending);
|
||||
}
|
||||
}
|
||||
|
||||
fn empty(ui: &mut egui::Ui, s: &str) {
|
||||
@@ -2382,7 +2446,14 @@ fn layers(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
("layer.delete", "Delete layer")
|
||||
};
|
||||
let trash = icons::button(ui, "trash", 26.0, false, tl!(label));
|
||||
if trash.clicked() {
|
||||
// A selected smart filter row is what Delete removes, as in Photoshop (#4751).
|
||||
let picked_filter = crate::smart_ui::selected(&ctx, &doc, active);
|
||||
if trash.clicked()
|
||||
&& let Some(picked) = picked_filter
|
||||
{
|
||||
actions.push(crate::smart_ui::trash_action(picked));
|
||||
crate::smart_ui::deselect(&ctx, doc.id);
|
||||
} else if trash.clicked() {
|
||||
// Like Photoshop, ⌥/Alt-click deletes without asking.
|
||||
let confirm = delete == "layer.delete" && !ui.input(|i| i.modifiers.alt);
|
||||
let params = if confirm { json!({"__trash": true}) } else { json!({}) };
|
||||
@@ -2837,6 +2908,7 @@ fn layer_row(
|
||||
} else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked {
|
||||
let mode = select_mode(ui.input(|i| i.modifiers));
|
||||
actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode})));
|
||||
crate::smart_ui::deselect(ctx, doc.id);
|
||||
// A thumbnail explicitly selects content or a mask. Selecting an adjustment/fill row
|
||||
// defaults to its mask, but clicking its content thumbnail must leave the mask target.
|
||||
let pos = resp.interact_pointer_pos();
|
||||
@@ -4901,6 +4973,7 @@ mod type_flyout_tests {
|
||||
|
||||
/// #4460: a press outside an open flyout closes it, even when it becomes a drag (cropping or
|
||||
/// painting on the canvas) rather than a click; a press on the flyout keeps it for its pick.
|
||||
/// #4932: so does a click on its own tool button.
|
||||
#[test]
|
||||
fn a_drag_outside_closes_the_tool_flyout() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
@@ -4924,10 +4997,13 @@ mod type_flyout_tests {
|
||||
let flyout = |ctx: &egui::Context| ctx.data(|d| d.get_temp::<(egui::Id, Rect)>(egui::Id::new("tool-flyout"))).is_some();
|
||||
let secondary = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Default::default() };
|
||||
let primary = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
// A right-click on the button of an open flyout closes it (#4932), so open only a closed one.
|
||||
let open = |app: &mut PhotocraftApp, t: f64| {
|
||||
frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]);
|
||||
frame(app, &ctx, t + 0.05, vec![secondary(false)]);
|
||||
frame(app, &ctx, t + 0.1, vec![]);
|
||||
if !flyout(&ctx) {
|
||||
frame(app, &ctx, t, vec![egui::Event::PointerMoved(at), secondary(true)]);
|
||||
frame(app, &ctx, t + 0.05, vec![secondary(false)]);
|
||||
frame(app, &ctx, t + 0.1, vec![]);
|
||||
}
|
||||
assert!(flyout(&ctx), "right-click opens it");
|
||||
};
|
||||
// A press on the flyout itself keeps it open (the row picks on release).
|
||||
@@ -4944,6 +5020,27 @@ mod type_flyout_tests {
|
||||
assert!(!flyout(&ctx), "a press outside closes it, even one that becomes a drag");
|
||||
frame(&mut app, &ctx, 2.6, vec![primary(canvas + vec2(80.0, 60.0), false)]);
|
||||
assert!(!flyout(&ctx));
|
||||
// #4932: clicking its own tool button again closes it, with either button.
|
||||
open(&mut app, 3.0);
|
||||
frame(&mut app, &ctx, 3.5, vec![egui::Event::PointerMoved(at), secondary(true)]);
|
||||
frame(&mut app, &ctx, 3.55, vec![secondary(false)]);
|
||||
frame(&mut app, &ctx, 3.6, vec![]);
|
||||
assert!(!flyout(&ctx), "a second right-click on the button closes it");
|
||||
open(&mut app, 4.0);
|
||||
app.ui.tool = Tool::Move;
|
||||
frame(&mut app, &ctx, 4.5, vec![egui::Event::PointerMoved(at), primary(at, true)]);
|
||||
frame(&mut app, &ctx, 4.55, vec![primary(at, false)]);
|
||||
frame(&mut app, &ctx, 4.6, vec![]);
|
||||
assert!(!flyout(&ctx), "a click on the button closes it");
|
||||
assert_eq!(app.ui.tool, Tool::Brush, "and picks the tool, as any click on it does");
|
||||
// The release that ends a long press keeps the flyout it opened.
|
||||
frame(&mut app, &ctx, 5.0, vec![egui::Event::PointerMoved(at), primary(at, true)]);
|
||||
frame(&mut app, &ctx, 5.2, vec![]);
|
||||
frame(&mut app, &ctx, 5.5, vec![]);
|
||||
assert!(flyout(&ctx), "a long press opens it");
|
||||
frame(&mut app, &ctx, 5.55, vec![primary(at, false)]);
|
||||
frame(&mut app, &ctx, 5.6, vec![]);
|
||||
assert!(flyout(&ctx), "releasing the long press keeps it open");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -146,7 +146,10 @@ fn dragging_on_the_first_anchor_closes_with_its_handles_in_one_step() {
|
||||
click(&mut h, [120.0, 20.0]);
|
||||
click(&mut h, [120.0, 100.0]);
|
||||
click(&mut h, [20.0, 20.0]);
|
||||
let sp = h.state().session.active().unwrap().doc.work_path.clone().unwrap().subpaths.remove(0);
|
||||
// The second path joins the Work Path as its last subpath (#4721).
|
||||
let subs = h.state().session.active().unwrap().doc.work_path.clone().unwrap().subpaths;
|
||||
assert_eq!(subs.len(), 2, "the first path stays");
|
||||
let sp = subs.last().unwrap();
|
||||
let k = &sp.knots[0];
|
||||
assert!(sp.closed && sp.knots.len() == 3);
|
||||
assert!(near([k.in_ctrl.x, k.in_ctrl.y], [0.0, 20.0]) && near([k.out_ctrl.x, k.out_ctrl.y], [40.0, 20.0]), "{k:?}");
|
||||
|
||||
@@ -405,3 +405,98 @@ fn shift_polygonal_lasso_snap_has_all_eight_directions_and_handles_zero_length()
|
||||
}
|
||||
assert_eq!(crate::canvas::constrained_polygon_point(origin, origin), origin);
|
||||
}
|
||||
|
||||
/// Two vertices placed with the Polygonal Lasso, well apart in time so they aren't a double-click.
|
||||
fn two_vertices(h: &mut Harness<'static, PhotocraftApp>) {
|
||||
click(h, 50.0, 50.0, Modifiers::NONE);
|
||||
h.run_steps(30);
|
||||
click(h, 150.0, 50.0, Modifiers::NONE);
|
||||
h.run_steps(30);
|
||||
assert_eq!(h.state().ui.polygon.len(), 2);
|
||||
}
|
||||
|
||||
/// The polygon, its mode and its document are all gone, and the selection it would have replaced
|
||||
/// is shown again.
|
||||
fn assert_polygon_dropped(h: &Harness<'static, PhotocraftApp>, what: &str) {
|
||||
let app = h.state();
|
||||
assert!(app.ui.polygon.is_empty(), "{what}: the outline is gone: {:?}", app.ui.polygon);
|
||||
assert!(app.ui.polygon_mode.is_empty(), "{what}: the mode is gone");
|
||||
assert!(app.ui.polygon_doc.is_none(), "{what}: the document is forgotten");
|
||||
assert!(!crate::canvas::polygon_replaces_selection(app), "{what}: the old outline is shown again");
|
||||
}
|
||||
|
||||
/// Every other tool drops the polygon in progress, not just the Quick Selection tool, and coming
|
||||
/// back to the Polygonal Lasso starts a new one.
|
||||
#[test]
|
||||
fn every_other_tool_drops_the_polygon_in_progress() {
|
||||
let tools = [
|
||||
Tool::QuickSelection,
|
||||
Tool::ObjectSelection,
|
||||
Tool::MagicWand,
|
||||
Tool::RectMarquee,
|
||||
Tool::EllipseMarquee,
|
||||
Tool::Lasso,
|
||||
Tool::MagneticLasso,
|
||||
Tool::Move,
|
||||
Tool::Brush,
|
||||
];
|
||||
for tool in tools {
|
||||
let mut h = harness();
|
||||
h.state_mut().run("select.rect", json!({"x": 200, "y": 150, "width": 100, "height": 100})).unwrap();
|
||||
h.run_steps(1);
|
||||
let before = steps(&h);
|
||||
two_vertices(&mut h);
|
||||
assert!(crate::canvas::polygon_replaces_selection(h.state()), "{tool:?}: the old outline is hidden while drawing");
|
||||
h.state_mut().ui.tool = tool;
|
||||
h.state_mut().sync_views();
|
||||
assert_polygon_dropped(&h, &format!("{tool:?}"));
|
||||
assert!(selection(&h).is_some_and(|r| near(r, 200, 150, 300, 250)), "{tool:?}: {:?}", selection(&h));
|
||||
assert_eq!(steps(&h), before, "{tool:?}: nothing was recorded");
|
||||
h.state_mut().ui.tool = Tool::PolygonLasso;
|
||||
h.state_mut().sync_views();
|
||||
assert!(h.state().ui.polygon.is_empty(), "{tool:?}: coming back starts a new polygon");
|
||||
}
|
||||
}
|
||||
|
||||
/// The polygon belongs to the document it was started on: another document becoming active drops
|
||||
/// it, while the tool stays the Polygonal Lasso (its outline would otherwise show on the other
|
||||
/// document).
|
||||
#[test]
|
||||
fn switching_documents_drops_the_polygon_in_progress() {
|
||||
let mut h = harness();
|
||||
two_vertices(&mut h);
|
||||
let first = h.state().session.active().map(|st| st.doc.id);
|
||||
assert!(first.is_some());
|
||||
assert_eq!(h.state().ui.polygon_doc, first, "the polygon remembers its document");
|
||||
h.state_mut().run("file.new", json!({"width": 200, "height": 100})).unwrap();
|
||||
assert_ne!(h.state().session.active().map(|st| st.doc.id), first, "another document is active");
|
||||
assert_polygon_dropped(&h, "new document");
|
||||
assert_eq!(h.state().ui.tool, Tool::PolygonLasso, "the tool stays");
|
||||
// Back on the first document, nothing is left of it.
|
||||
h.state_mut().run("document.activate", json!({"document": 0})).unwrap();
|
||||
h.state_mut().sync_views();
|
||||
assert!(h.state().ui.polygon.is_empty());
|
||||
}
|
||||
|
||||
/// A held temporary tool (Space is the Hand, ⌘ the Move tool) doesn't change the selected tool, so
|
||||
/// the polygon being drawn stays.
|
||||
#[test]
|
||||
fn a_held_temporary_tool_keeps_the_polygon() {
|
||||
let mut h = harness();
|
||||
two_vertices(&mut h);
|
||||
h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
h.state_mut().sync_views();
|
||||
assert_eq!(h.state().ui.tool, Tool::PolygonLasso);
|
||||
assert_eq!(h.state().ui.polygon.len(), 2, "Space held");
|
||||
h.event(egui::Event::Key { key: egui::Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::NONE });
|
||||
h.run_steps(3);
|
||||
h.event(egui::Event::ModifiersChanged(Modifiers::COMMAND));
|
||||
h.run_steps(3);
|
||||
h.state_mut().sync_views();
|
||||
assert_eq!(h.state().ui.tool, Tool::PolygonLasso);
|
||||
assert_eq!(h.state().ui.polygon.len(), 2, "⌘ held");
|
||||
h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().ui.polygon.len(), 2, "released");
|
||||
}
|
||||
@@ -129,9 +129,9 @@ pub(crate) fn cycle_appearance(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
const LIGHT_THEME_OPTIONS: &[(&str, ThemeKind)] = &[
|
||||
("studioLight", ThemeKind::StudioLight),
|
||||
("proLightGray", ThemeKind::ProLightGray),
|
||||
("proLight", ThemeKind::ProLight),
|
||||
("proLightGray", ThemeKind::ProLightGray),
|
||||
("studioLight", ThemeKind::StudioLight),
|
||||
("classic", ThemeKind::Classic),
|
||||
("adwaita", ThemeKind::Adwaita),
|
||||
("breezeLight", ThemeKind::BreezeLight),
|
||||
@@ -2078,7 +2078,7 @@ mod tests {
|
||||
fn appearance_resolves_both_saved_themes_and_follows_system() {
|
||||
let mut interface = prefs::Interface { appearance_mode: AppearanceMode::Auto, ..prefs::Interface::default() };
|
||||
assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::ProMedium);
|
||||
assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::StudioLight);
|
||||
assert_eq!(selected_theme(&interface, Some(egui::Theme::Light)), ThemeKind::ProLight);
|
||||
interface.dark_theme = DarkTheme::Studio;
|
||||
interface.light_theme = LightTheme::Classic;
|
||||
assert_eq!(selected_theme(&interface, Some(egui::Theme::Dark)), ThemeKind::Studio);
|
||||
@@ -2119,7 +2119,7 @@ mod tests {
|
||||
app.run("prefs.set", json!({"path": "interface.appearanceMode", "value": "auto"})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
tick(&mut app, &ctx);
|
||||
assert_eq!(app.ui.theme, ThemeKind::StudioLight);
|
||||
assert_eq!(app.ui.theme, ThemeKind::ProLight);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2232,13 +2232,13 @@ mod tests {
|
||||
ctx.set_theme(egui::ThemePreference::Dark);
|
||||
assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::Dark);
|
||||
appearance_frame(&mut app, &ctx, Some(egui::Theme::Light));
|
||||
assert_palette(&ctx, ThemeKind::StudioLight);
|
||||
assert_palette(&ctx, ThemeKind::ProLight);
|
||||
assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto);
|
||||
// A restored pin must also clear when the concrete PhotoCraft palette stays the same.
|
||||
ctx.set_theme(egui::ThemePreference::Dark);
|
||||
appearance_frame(&mut app, &ctx, Some(egui::Theme::Light));
|
||||
assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System);
|
||||
assert_palette(&ctx, ThemeKind::StudioLight);
|
||||
assert_palette(&ctx, ThemeKind::ProLight);
|
||||
appearance_frame(&mut app, &ctx, Some(egui::Theme::Dark));
|
||||
assert_palette(&ctx, ThemeKind::ProMedium);
|
||||
assert_eq!(app.session.prefs().interface.appearance_mode, AppearanceMode::Auto);
|
||||
|
||||
+144
-127
@@ -329,6 +329,9 @@ fn group_open(st: &PresetUi, panel: &str, gi: usize, name: &str) -> bool {
|
||||
(gi == 0 || panel == crate::swatches_ui::PANEL) != st.toggled.contains(&format!("{panel}/{name}"))
|
||||
}
|
||||
|
||||
/// The footer's height (gap, size slider and buttons) before it has been measured.
|
||||
const FOOTER_GUESS: f32 = 32.0;
|
||||
|
||||
/// Draws the folders and footer; `thumb` paints item `(group, item)` into a rect.
|
||||
/// Where a browser sits: the canvas (drop target), its height cap and the New button's tooltip.
|
||||
pub(crate) struct Place<'a> {
|
||||
@@ -383,143 +386,151 @@ pub(crate) fn browser(
|
||||
let mut released: Option<(usize, Pos2)> = None;
|
||||
let group_names: Vec<String> = groups.iter().map(|g| g.name.clone()).collect();
|
||||
let display = st.display_order(panel, &group_names);
|
||||
egui::ScrollArea::vertical().id_salt(("preset-scroll", panel)).max_height(max_h).auto_shrink([false, true]).show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 2.0);
|
||||
for &gi in &display {
|
||||
let Some(g) = groups.get(gi) else { continue };
|
||||
let open = group_open(st, panel, gi, &g.name);
|
||||
let (hr, hresp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
|
||||
if hresp.hovered() || hresp.dragged() {
|
||||
ui.painter().rect_filled(hr, 2.0, t.hover.gamma_multiply(0.5));
|
||||
}
|
||||
let tri = Rect::from_center_size(pos2(hr.left() + 9.0, hr.center().y), vec2(12.0, 12.0));
|
||||
crate::icons::paint(ui, tri, if open { "chevron-down" } else { "chevron-right" }, 10.0, t.text_dim);
|
||||
let fold = Rect::from_center_size(pos2(hr.left() + 25.0, hr.center().y), vec2(14.0, 14.0));
|
||||
crate::icons::paint(ui, fold, if open { "folder-open" } else { "folder" }, 12.0, t.icon);
|
||||
ui.painter().text(pos2(hr.left() + 37.0, hr.center().y), Align2::LEFT_CENTER, &g.name, FontId::proportional(11.5), t.text);
|
||||
if hresp.clicked() {
|
||||
let k = format!("{panel}/{}", g.name);
|
||||
if !st.toggled.remove(&k) {
|
||||
st.toggled.insert(k);
|
||||
// The footer stays in view: the list gets the height left after it (as measured last frame)
|
||||
// and scrolls, rather than pushing the footer out of a short dock group (#4790).
|
||||
let footer_id = egui::Id::new(("preset-footer", panel));
|
||||
let footer_h = ui.data(|d| d.get_temp::<f32>(footer_id)).unwrap_or(FOOTER_GUESS);
|
||||
let max_h = max_h.min((ui.available_height() - footer_h).max(0.0));
|
||||
egui::ScrollArea::vertical().id_salt(("preset-scroll", panel)).max_height(max_h).min_scrolled_height(max_h.min(64.0)).auto_shrink([false, true]).show(
|
||||
ui,
|
||||
|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(0.0, 2.0);
|
||||
for &gi in &display {
|
||||
let Some(g) = groups.get(gi) else { continue };
|
||||
let open = group_open(st, panel, gi, &g.name);
|
||||
let (hr, hresp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
|
||||
if hresp.hovered() || hresp.dragged() {
|
||||
ui.painter().rect_filled(hr, 2.0, t.hover.gamma_multiply(0.5));
|
||||
}
|
||||
}
|
||||
hresp.context_menu(|ui| {
|
||||
if ui.button(tl!("Rename Group…")).clicked() {
|
||||
st.renaming = Some((panel.to_string(), format!("group:{}", g.name), g.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tl!("Delete Group")).clicked() {
|
||||
ev.push(Ev::DeleteGroup(g.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
if hresp.dragged()
|
||||
&& let Some(p) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
drag = Some((gi, p));
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
if hresp.drag_stopped()
|
||||
&& let Some(p) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
released = Some((gi, p));
|
||||
}
|
||||
headers.push((gi, hr, g.name.clone()));
|
||||
if !open {
|
||||
continue;
|
||||
}
|
||||
let w = ui.available_width();
|
||||
let (cell, cols) = if list {
|
||||
(vec2(w, 24.0), 1)
|
||||
} else {
|
||||
let cols = ((w - 8.0 + 4.0) / (size + 4.0)).floor().max(1.0) as usize;
|
||||
(vec2(size, size), cols)
|
||||
};
|
||||
let rows = g.items.len().div_ceil(cols);
|
||||
let pad = if list { 0.0 } else { 8.0 };
|
||||
let gap = if list { 0.0 } else { 4.0 };
|
||||
let (area, _) = ui.allocate_exact_size(vec2(w, rows as f32 * (cell.y + gap) + 2.0), Sense::hover());
|
||||
for (ii, it) in g.items.iter().enumerate() {
|
||||
let (cx, cy) = ((ii % cols) as f32, (ii / cols) as f32);
|
||||
let r = Rect::from_min_size(area.min + vec2(pad + cx * (cell.x + gap), cy * (cell.y + gap)), cell);
|
||||
let resp = ui.interact(r, ui.id().with((panel, gi, ii)), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &it.name));
|
||||
let is_sel = selected.as_deref() == Some(&it.key);
|
||||
if list {
|
||||
if is_sel {
|
||||
ui.painter().rect_filled(r, 0.0, t.row_selected);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
|
||||
let tri = Rect::from_center_size(pos2(hr.left() + 9.0, hr.center().y), vec2(12.0, 12.0));
|
||||
crate::icons::paint(ui, tri, if open { "chevron-down" } else { "chevron-right" }, 10.0, t.text_dim);
|
||||
let fold = Rect::from_center_size(pos2(hr.left() + 25.0, hr.center().y), vec2(14.0, 14.0));
|
||||
crate::icons::paint(ui, fold, if open { "folder-open" } else { "folder" }, 12.0, t.icon);
|
||||
ui.painter().text(pos2(hr.left() + 37.0, hr.center().y), Align2::LEFT_CENTER, &g.name, FontId::proportional(11.5), t.text);
|
||||
if hresp.clicked() {
|
||||
let k = format!("{panel}/{}", g.name);
|
||||
if !st.toggled.remove(&k) {
|
||||
st.toggled.insert(k);
|
||||
}
|
||||
let tr = Rect::from_min_size(r.min + vec2(24.0, 2.0), vec2(20.0, 20.0));
|
||||
thumb(ui, tr, gi, ii);
|
||||
ui.painter().text(pos2(tr.right() + 8.0, r.center().y), Align2::LEFT_CENTER, &it.name, FontId::proportional(11.5), t.text);
|
||||
} else {
|
||||
thumb(ui, r, gi, ii);
|
||||
let (stroke, kind) = if is_sel {
|
||||
(Stroke::new(2.0, t.accent), egui::StrokeKind::Outside)
|
||||
} else if resp.hovered() {
|
||||
(Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside)
|
||||
} else {
|
||||
(Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside)
|
||||
};
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(2), stroke, kind);
|
||||
}
|
||||
let resp = if list { resp } else { resp.on_hover_text(&it.name) };
|
||||
if resp.double_clicked() {
|
||||
ev.push(Ev::Activate(it.key.clone()));
|
||||
} else if resp.clicked() {
|
||||
ev.push(Ev::Select(it.key.clone()));
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let Some(pp) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
// A ghost of the swatch follows the pointer.
|
||||
let lp = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("preset-drag")));
|
||||
let gr = Rect::from_center_size(pp, vec2(28.0, 28.0));
|
||||
lp.rect_filled(gr, 3.0, t.card.gamma_multiply(0.8));
|
||||
lp.rect_stroke(gr, 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Outside);
|
||||
lp.text(gr.center(), Align2::CENTER_CENTER, "+", FontId::proportional(16.0), t.accent);
|
||||
}
|
||||
if resp.drag_stopped()
|
||||
&& let Some(pp) = ui.ctx().pointer_interact_pos()
|
||||
&& !r.contains(pp)
|
||||
{
|
||||
dropped = Some((it.key.clone(), pp));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tl!("Rename…")).clicked() {
|
||||
st.renaming = Some((panel.to_string(), it.key.clone(), it.name.clone()));
|
||||
hresp.context_menu(|ui| {
|
||||
if ui.button(tl!("Rename Group…")).clicked() {
|
||||
st.renaming = Some((panel.to_string(), format!("group:{}", g.name), g.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tl!("Delete")).clicked() {
|
||||
ev.push(Ev::Delete(it.key.clone()));
|
||||
if ui.button(tl!("Delete Group")).clicked() {
|
||||
ev.push(Ev::DeleteGroup(g.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
ui.menu_button(tl!("Move to"), |ui| {
|
||||
for gname in group_names.iter().filter(|n| **n != g.name) {
|
||||
if ui.button(gname).clicked() {
|
||||
ev.push(Ev::Move(it.key.clone(), gname.clone()));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if hresp.dragged()
|
||||
&& let Some(p) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
drag = Some((gi, p));
|
||||
ui.ctx().set_cursor_icon(egui::CursorIcon::Grabbing);
|
||||
}
|
||||
if hresp.drag_stopped()
|
||||
&& let Some(p) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
released = Some((gi, p));
|
||||
}
|
||||
headers.push((gi, hr, g.name.clone()));
|
||||
if !open {
|
||||
continue;
|
||||
}
|
||||
let w = ui.available_width();
|
||||
let (cell, cols) = if list {
|
||||
(vec2(w, 24.0), 1)
|
||||
} else {
|
||||
let cols = ((w - 8.0 + 4.0) / (size + 4.0)).floor().max(1.0) as usize;
|
||||
(vec2(size, size), cols)
|
||||
};
|
||||
let rows = g.items.len().div_ceil(cols);
|
||||
let pad = if list { 0.0 } else { 8.0 };
|
||||
let gap = if list { 0.0 } else { 4.0 };
|
||||
let (area, _) = ui.allocate_exact_size(vec2(w, rows as f32 * (cell.y + gap) + 2.0), Sense::hover());
|
||||
for (ii, it) in g.items.iter().enumerate() {
|
||||
let (cx, cy) = ((ii % cols) as f32, (ii / cols) as f32);
|
||||
let r = Rect::from_min_size(area.min + vec2(pad + cx * (cell.x + gap), cy * (cell.y + gap)), cell);
|
||||
let resp = ui.interact(r, ui.id().with((panel, gi, ii)), Sense::click_and_drag());
|
||||
resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &it.name));
|
||||
let is_sel = selected.as_deref() == Some(&it.key);
|
||||
if list {
|
||||
if is_sel {
|
||||
ui.painter().rect_filled(r, 0.0, t.row_selected);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
|
||||
}
|
||||
let tr = Rect::from_min_size(r.min + vec2(24.0, 2.0), vec2(20.0, 20.0));
|
||||
thumb(ui, tr, gi, ii);
|
||||
ui.painter().text(pos2(tr.right() + 8.0, r.center().y), Align2::LEFT_CENTER, &it.name, FontId::proportional(11.5), t.text);
|
||||
} else {
|
||||
thumb(ui, r, gi, ii);
|
||||
let (stroke, kind) = if is_sel {
|
||||
(Stroke::new(2.0, t.accent), egui::StrokeKind::Outside)
|
||||
} else if resp.hovered() {
|
||||
(Stroke::new(1.0, t.text_dim), egui::StrokeKind::Outside)
|
||||
} else {
|
||||
(Stroke::new(1.0, t.card_border), egui::StrokeKind::Inside)
|
||||
};
|
||||
ui.painter().rect_stroke(r, CornerRadius::same(2), stroke, kind);
|
||||
}
|
||||
let resp = if list { resp } else { resp.on_hover_text(&it.name) };
|
||||
if resp.double_clicked() {
|
||||
ev.push(Ev::Activate(it.key.clone()));
|
||||
} else if resp.clicked() {
|
||||
ev.push(Ev::Select(it.key.clone()));
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let Some(pp) = ui.ctx().pointer_interact_pos()
|
||||
{
|
||||
// A ghost of the swatch follows the pointer.
|
||||
let lp = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, egui::Id::new("preset-drag")));
|
||||
let gr = Rect::from_center_size(pp, vec2(28.0, 28.0));
|
||||
lp.rect_filled(gr, 3.0, t.card.gamma_multiply(0.8));
|
||||
lp.rect_stroke(gr, 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Outside);
|
||||
lp.text(gr.center(), Align2::CENTER_CENTER, "+", FontId::proportional(16.0), t.accent);
|
||||
}
|
||||
if resp.drag_stopped()
|
||||
&& let Some(pp) = ui.ctx().pointer_interact_pos()
|
||||
&& !r.contains(pp)
|
||||
{
|
||||
dropped = Some((it.key.clone(), pp));
|
||||
}
|
||||
resp.context_menu(|ui| {
|
||||
if ui.button(tl!("Rename…")).clicked() {
|
||||
st.renaming = Some((panel.to_string(), it.key.clone(), it.name.clone()));
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(tl!("Delete")).clicked() {
|
||||
ev.push(Ev::Delete(it.key.clone()));
|
||||
ui.close();
|
||||
}
|
||||
ui.menu_button(tl!("Move to"), |ui| {
|
||||
for gname in group_names.iter().filter(|n| **n != g.name) {
|
||||
if ui.button(gname).clicked() {
|
||||
ev.push(Ev::Move(it.key.clone(), gname.clone()));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Insertion line while a folder is dragged by its header.
|
||||
if let Some((from, p)) = drag {
|
||||
let before = group_drop_before(&headers, from, p.y);
|
||||
let anchor = match before {
|
||||
Some(i) => headers.iter().find(|(x, _, _)| *x == i).map(|(_, r, _)| *r),
|
||||
None => headers.last().map(|(_, r, _)| *r),
|
||||
};
|
||||
if let Some(r) = anchor {
|
||||
let y = if before.is_some() { r.top() - 1.0 } else { r.bottom() + 1.0 };
|
||||
ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
|
||||
// Insertion line while a folder is dragged by its header.
|
||||
if let Some((from, p)) = drag {
|
||||
let before = group_drop_before(&headers, from, p.y);
|
||||
let anchor = match before {
|
||||
Some(i) => headers.iter().find(|(x, _, _)| *x == i).map(|(_, r, _)| *r),
|
||||
None => headers.last().map(|(_, r, _)| *r),
|
||||
};
|
||||
if let Some(r) = anchor {
|
||||
let y = if before.is_some() { r.top() - 1.0 } else { r.bottom() + 1.0 };
|
||||
ui.painter().line_segment([pos2(r.left(), y), pos2(r.right(), y)], Stroke::new(2.0, t.accent));
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
// Apply the drop now every header rect is known; the next frame draws the new order.
|
||||
if let Some((from, p)) = released {
|
||||
let before = group_drop_before(&headers, from, p.y);
|
||||
@@ -539,6 +550,7 @@ pub(crate) fn browser(
|
||||
}
|
||||
}
|
||||
// Footer: thumbnail size | New Group, New, Delete.
|
||||
let footer_top = ui.min_rect().bottom();
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
@@ -561,6 +573,11 @@ pub(crate) fn browser(
|
||||
}
|
||||
});
|
||||
});
|
||||
let measured = ui.min_rect().bottom() - footer_top;
|
||||
if measured.is_finite() && (measured - footer_h).abs() > 0.5 {
|
||||
ui.data_mut(|d| d.insert_temp(footer_id, measured));
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
ev
|
||||
}
|
||||
|
||||
|
||||
@@ -317,6 +317,25 @@ mod tests {
|
||||
assert!(huge.is_finite() && huge.abs() <= 180.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_rotate_event_reaches_canvas_when_trackpad_rotation_is_enabled() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut enabled = None;
|
||||
let mut disabled = None;
|
||||
let raw = egui::RawInput {
|
||||
events: vec![Event::Rotate(std::f32::consts::FRAC_PI_6)],
|
||||
..Default::default()
|
||||
};
|
||||
let mut output = ctx.run_ui(raw, |ui| {
|
||||
enabled = trackpad_delta(ui.ctx(), true);
|
||||
disabled = trackpad_delta(ui.ctx(), false);
|
||||
});
|
||||
output.textures_delta.clear();
|
||||
|
||||
assert!(enabled.is_some_and(|degrees| (degrees - 30.0).abs() < 1e-3), "{enabled:?}");
|
||||
assert_eq!(disabled, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trackpad_pref_gates_rotation() {
|
||||
assert_eq!(apply_trackpad(10.0, false, 0.5), None);
|
||||
|
||||
@@ -241,7 +241,7 @@ pub fn dispatch_pressed(app: &mut PhotocraftApp, ctx: &egui::Context, focus: Foc
|
||||
// panels instead, #1313): the shortcut took it, so cancel that move.
|
||||
ctx.memory_mut(|m| m.move_focus(egui::FocusDirection::None));
|
||||
}
|
||||
let id = delete_key_command(app, id);
|
||||
let id = clip_key_command(app, delete_key_command(app, id));
|
||||
let owner = key_owner(app, ctx);
|
||||
dispatch(app, ctx, &id);
|
||||
ran = true;
|
||||
@@ -284,6 +284,26 @@ fn delete_key_command(app: &PhotocraftApp, id: String) -> String {
|
||||
"layer.delete".into()
|
||||
}
|
||||
|
||||
/// Create Clipping Mask's key (⌥⌘G) releases when there is nothing left to clip, as in Photoshop,
|
||||
/// whose Layer menu has one item that reads Create or Release Clipping Mask with the same
|
||||
/// shortcut: pressing it again takes the clip off. That is when the layers Create Clipping Mask
|
||||
/// would clip are all clipped already: the selected layer, or with several selected, every one
|
||||
/// above the lowest.
|
||||
pub(crate) fn clip_key_releases(app: &PhotocraftApp) -> bool {
|
||||
let Some(st) = app.session.active() else { return false };
|
||||
let selected = st.selected_layers();
|
||||
let clips = match selected.as_slice() {
|
||||
[] => return false,
|
||||
[one] => std::slice::from_ref(one),
|
||||
[_lowest, above @ ..] => above,
|
||||
};
|
||||
clips.iter().all(|id| st.doc.layer(*id).is_some_and(|l| l.clipped))
|
||||
}
|
||||
|
||||
fn clip_key_command(app: &PhotocraftApp, id: String) -> String {
|
||||
if id == "layer.createClippingMask" && clip_key_releases(app) { "layer.releaseClippingMask".into() } else { id }
|
||||
}
|
||||
|
||||
/// Why `id` can't run now (the engine's reason when it has one).
|
||||
pub fn disabled_reason(app: &PhotocraftApp, id: &str) -> String {
|
||||
photocraft_engine::commands::find(id).and_then(|_| app.session.disabled_reason_with(id, &app.with_mask_target(id, serde_json::Value::Null))).unwrap_or_else(
|
||||
|
||||
@@ -135,9 +135,13 @@ fn put_focus(h: &mut Harness<'_, PhotocraftApp>, place: Place) {
|
||||
}
|
||||
|
||||
/// Is `bound` the same action as the menu item `shown`? (Window › Layers is `window.panel.layers`
|
||||
/// in the catalogue and `window.toggle.layers` in the shell.)
|
||||
/// in the catalogue and `window.toggle.layers` in the shell; Release Clipping Mask shows Create
|
||||
/// Clipping Mask's key, which releases while it reads so.)
|
||||
fn same(shown: &str, bound: &str) -> bool {
|
||||
shown == bound || crate::menus::panel_alias(shown) == Some(bound) || crate::menus::panel_alias(bound) == Some(shown)
|
||||
shown == bound
|
||||
|| crate::menus::panel_alias(shown) == Some(bound)
|
||||
|| crate::menus::panel_alias(bound) == Some(shown)
|
||||
|| (shown == "layer.releaseClippingMask" && bound == "layer.createClippingMask")
|
||||
}
|
||||
|
||||
/// Every shortcut shown in the menus (and the shell's unlisted ones), with whether it is live.
|
||||
@@ -566,6 +570,65 @@ fn delete_with_a_selection_clears_it() {
|
||||
assert_eq!(names(&h), before, "no layer was deleted");
|
||||
}
|
||||
|
||||
fn is_clipped(h: &Harness<'_, PhotocraftApp>, id: photocraft_doc::LayerId) -> bool {
|
||||
h.state().session.active().unwrap().doc.layer(id).unwrap().clipped
|
||||
}
|
||||
|
||||
/// The Layer menu's clipping mask items: (id, label, shortcut, enabled).
|
||||
fn clip_items(h: &Harness<'_, PhotocraftApp>) -> Vec<(String, String, Option<String>, bool)> {
|
||||
crate::menus::menu_items(h.state()).into_iter().filter(|i| i.id.ends_with("ClippingMask")).map(|i| (i.id, i.label, i.shortcut, i.enabled)).collect()
|
||||
}
|
||||
|
||||
fn clip_item(id: &str, label: &str) -> Vec<(String, String, Option<String>, bool)> {
|
||||
vec![(id.into(), label.into(), Some("Cmd+Alt+G".into()), true)]
|
||||
}
|
||||
|
||||
/// ⌥⌘G clips the selected layer and pressing it again releases it, as Photoshop's one Create /
|
||||
/// Release Clipping Mask item does; the Layer menu reads Release Clipping Mask, with the same
|
||||
/// shortcut, while the key would release.
|
||||
#[test]
|
||||
fn clip_key_toggles_the_clipping_mask() {
|
||||
let mut h = harness();
|
||||
put_focus(&mut h, Place::Canvas);
|
||||
let paint = h.state().session.active().unwrap().active_layer.unwrap();
|
||||
assert_eq!(clip_items(&h), clip_item("layer.createClippingMask", "Create Clipping Mask"));
|
||||
press(&mut h, "Cmd+Alt+G");
|
||||
assert_eq!(logged(&h), ["layer.createClippingMask"]);
|
||||
assert!(is_clipped(&h, paint));
|
||||
assert_eq!(clip_items(&h), clip_item("layer.releaseClippingMask", "Release Clipping Mask"));
|
||||
press(&mut h, "Cmd+Alt+G");
|
||||
assert_eq!(logged(&h), ["layer.releaseClippingMask"]);
|
||||
assert!(!is_clipped(&h, paint), "the second press releases it");
|
||||
assert_eq!(clip_items(&h), clip_item("layer.createClippingMask", "Create Clipping Mask"));
|
||||
press(&mut h, "Cmd+Z");
|
||||
assert!(is_clipped(&h, paint), "one undo puts the clip back");
|
||||
}
|
||||
|
||||
/// With several layers selected the key clips every one above the lowest, and releases them once
|
||||
/// they all are: a selection where only some are clipped clips the rest first.
|
||||
#[test]
|
||||
fn clip_key_toggles_several_selected_layers() {
|
||||
let mut h = harness();
|
||||
put_focus(&mut h, Place::Canvas);
|
||||
let s = &mut h.state_mut().session;
|
||||
let paint = s.active().unwrap().active_layer.unwrap();
|
||||
let base = s.active().unwrap().doc.walk().into_iter().find(|(_, _, l)| l.name == "Hello").unwrap().2.id;
|
||||
let top = photocraft_doc::LayerId(s.execute("layer.new.layer", json!({"name": "top"})).unwrap()["layer"].as_u64().unwrap());
|
||||
s.execute("layer.createClippingMask", json!({"layer": paint.0})).unwrap();
|
||||
s.execute("layer.select", json!({"layer": base.0, "mode": "replace"})).unwrap();
|
||||
for id in [paint, top] {
|
||||
s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();
|
||||
}
|
||||
assert_eq!(s.active().unwrap().selected_layers().len(), 3);
|
||||
h.run_steps(2);
|
||||
press(&mut h, "Cmd+Alt+G");
|
||||
assert_eq!(logged(&h), ["layer.createClippingMask"], "the top layer isn't clipped yet");
|
||||
assert!(is_clipped(&h, paint) && is_clipped(&h, top) && !is_clipped(&h, base));
|
||||
press(&mut h, "Cmd+Alt+G");
|
||||
assert_eq!(logged(&h), ["layer.releaseClippingMask"]);
|
||||
assert!(!is_clipped(&h, paint) && !is_clipped(&h, top) && !is_clipped(&h, base));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_action_function_key_replays_and_survives_preferences_roundtrip() {
|
||||
let mut h = harness();
|
||||
|
||||
@@ -162,6 +162,31 @@ pub fn consume(ctx: &egui::Context, sc: &KeyboardShortcut) -> bool {
|
||||
pub const NAV_COMMANDS: [&str; 4] = ["view.zoomIn", "view.zoomOut", "view.fitOnScreen", "view.actualPixels"];
|
||||
|
||||
/// ⌘+ / ⌘- / ⌘0 / ⌘1 (or their Edit › Keyboard Shortcuts overrides). Returns true when one ran.
|
||||
/// Layer › New › Layer's shortcut with ⌥ added (⌥⇧⌘N by default) makes the layer at once, as in
|
||||
/// Photoshop: the plain shortcut asks with the New Layer dialog first, like the menu item, and
|
||||
/// the Layers panel button's click and ⌥-click are the same pair the other way round (#4794).
|
||||
/// A command bound to that key itself keeps it.
|
||||
fn new_layer_without_dialog(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
const NEW_LAYER: &str = crate::new_layer_ui::COMMAND;
|
||||
let Some(mut sc) = effective_shortcut(app, NEW_LAYER, default_shortcut(NEW_LAYER).as_deref()).and_then(|s| parse(&s)) else {
|
||||
return false;
|
||||
};
|
||||
if sc.modifiers.alt {
|
||||
return false;
|
||||
}
|
||||
sc.modifiers.alt = true;
|
||||
let pressed =
|
||||
ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } if key_matches(&sc, *key, *modifiers))));
|
||||
if !pressed || crate::shortcut_dispatch::bindings(app).iter().any(|(_, b)| *b == sc) || !consume(ctx, &sc) {
|
||||
return false;
|
||||
}
|
||||
if let Err(e) = app.run(NEW_LAYER, json!({})) {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn nav_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
for id in NAV_COMMANDS {
|
||||
let sc = crate::menus::UI_COMMANDS.iter().find(|c| c.0 == id).and_then(|c| parse(app.session.prefs().shortcut(id, c.3)?));
|
||||
@@ -480,6 +505,10 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
// Inline type editing eats text and navigation keys; ⌘-shortcuts still reach the menus.
|
||||
let editing = crate::type_tool::handle_keys(app, ctx);
|
||||
// ⌥⇧⌘N: a new layer at once, without the New Layer dialog ⇧⌘N opens (#4794).
|
||||
if new_layer_without_dialog(app, ctx) {
|
||||
return;
|
||||
}
|
||||
// Registry, UI and menu-catalogue shortcuts (see [`crate::shortcut_dispatch::bindings`]).
|
||||
if dispatch_pressed(app, ctx, focus, editing) {
|
||||
return;
|
||||
|
||||
@@ -162,3 +162,70 @@ fn a_camera_raw_filter_copies_and_its_copy_opens_on_the_target() {
|
||||
let dialog = h.state().camera_raw.as_ref().expect("Camera Raw opened");
|
||||
assert_eq!(dialog.layer, LayerId(b));
|
||||
}
|
||||
|
||||
/// Dragging a filter up or down its own stack reorders it (Photoshop), which changes the result:
|
||||
/// the bottom filter is applied first (`smart_cmds::tests::filter_stack_order_blend_disable_and_clear`). A drop on the upper half of a row lands above it, on the
|
||||
/// lower half below it, on the Smart Filters row on top; the moved filter stays selected.
|
||||
#[test]
|
||||
fn dragging_a_filter_up_or_down_its_stack_reorders_it() {
|
||||
let (mut h, a, _, _) = panel();
|
||||
let (blur, offset) = ("filter.blur.gaussianBlur", "filter.other.offset");
|
||||
let half = |p: Pos2, up: bool| p + egui::vec2(0.0, if up { -6.0 } else { 6.0 });
|
||||
// Gaussian Blur (bottom) onto the upper half of Offset's row: blur now on top.
|
||||
let (from, to) = (at(&h, "Gaussian Blur"), at(&h, "Offset"));
|
||||
drag(&mut h, from, half(to, true), Modifiers::NONE);
|
||||
assert_eq!(filters(&h, a), [offset, blur]);
|
||||
assert!(selected(&h, "Gaussian Blur"), "the moved filter stays selected");
|
||||
assert!(!h.state().ui.status_error, "{}", h.state().ui.status);
|
||||
// Its lower half: back under it.
|
||||
let (from, to) = (at(&h, "Gaussian Blur"), at(&h, "Offset"));
|
||||
drag(&mut h, from, half(to, false), Modifiers::NONE);
|
||||
assert_eq!(filters(&h, a), [blur, offset]);
|
||||
// The Smart Filters row: on top again.
|
||||
let (from, to) = (at(&h, "Gaussian Blur"), at(&h, "Smart Filters"));
|
||||
drag(&mut h, from, to, Modifiers::NONE);
|
||||
assert_eq!(filters(&h, a), [offset, blur]);
|
||||
// Each drag is one undo step.
|
||||
h.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
h.run_steps(4);
|
||||
assert_eq!(filters(&h, a), [blur, offset]);
|
||||
}
|
||||
|
||||
fn click_at(h: &mut egui_kittest::Harness<'static, PhotocraftApp>, p: Pos2) {
|
||||
h.hover_at(p);
|
||||
h.run_steps(1);
|
||||
h.drag_at(p);
|
||||
h.run_steps(1);
|
||||
h.drop_at(p);
|
||||
h.run_steps(4);
|
||||
}
|
||||
|
||||
/// #4751: with a filter's row selected, clicking Delete removes that filter, not the smart object.
|
||||
#[test]
|
||||
fn clicking_delete_removes_the_selected_filter() {
|
||||
let (mut h, a, _, _) = panel();
|
||||
let blur = at(&h, "Gaussian Blur");
|
||||
click_at(&mut h, blur);
|
||||
let trash = at(&h, "Delete layer");
|
||||
click_at(&mut h, trash);
|
||||
assert_eq!(filters(&h, a), ["filter.other.offset"]);
|
||||
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), 4, "no layer was deleted");
|
||||
// The deleted row's selection doesn't carry over to Offset, now at its index.
|
||||
click_at(&mut h, trash);
|
||||
assert_eq!(filters(&h, a), ["filter.other.offset"]);
|
||||
}
|
||||
|
||||
/// Clicking the smart object's own row leaves its filters: Delete then deletes the layer as usual.
|
||||
#[test]
|
||||
fn clicking_the_smart_object_row_deselects_its_filter() {
|
||||
let (mut h, a, _, _) = panel();
|
||||
let offset = at(&h, "Offset");
|
||||
click_at(&mut h, offset);
|
||||
let row = at(&h, "Smart A");
|
||||
click_at(&mut h, row);
|
||||
assert_eq!(h.state().session.active().unwrap().active_layer, Some(LayerId(a)));
|
||||
assert!(!selected(&h, "Offset"));
|
||||
let trash = at(&h, "Delete layer");
|
||||
click_at(&mut h, trash);
|
||||
assert_eq!(filters(&h, a).len(), 2, "the filters stay");
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Layers-panel pieces for smart objects: the thumbnail badge and the Smart Filters sub-rows
|
||||
//! (eye toggles; double-click a filter to re-open its dialog with the recorded parameters; click
|
||||
//! to select one; drag onto another smart object to move it there, ⌥-drag to copy it, #4271).
|
||||
//! to select one; drag onto another smart object to move it there, ⌥-drag to copy it, #4271;
|
||||
//! drag it up or down its own stack to reorder it).
|
||||
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
|
||||
use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartObject};
|
||||
@@ -87,6 +88,14 @@ pub fn filter_rows(app: &mut PhotocraftApp, ui: &mut egui::Ui, l: &Layer, depth:
|
||||
if resp.drag_started() {
|
||||
ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(drag_key(), (l.id.0, index)));
|
||||
}
|
||||
if let Some((to, action)) = reorder_drop(ui, l, sm.smart_filters.len(), index, rect) {
|
||||
// The moved filter ends up selected, with its smart object active, as after a click.
|
||||
ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(selected_key(doc), (l.id.0, Some(to))));
|
||||
actions.push(action);
|
||||
if !active {
|
||||
actions.push(("layer.select".into(), json!({"layer": l.id.0})));
|
||||
}
|
||||
}
|
||||
// Selected as in Photoshop: the row stays highlighted while its smart object is active.
|
||||
let selected = active && picked == Some((l.id.0, index));
|
||||
if selected {
|
||||
@@ -151,6 +160,26 @@ fn selected_key(doc: photocraft_doc::DocId) -> egui::Id {
|
||||
egui::Id::new(("smart-filter-selected", doc))
|
||||
}
|
||||
|
||||
/// The selected smart filter row, while its smart object is active and the filter still exists.
|
||||
pub(crate) fn selected(ctx: &egui::Context, doc: &Document, active: Option<LayerId>) -> Option<FilterDrag> {
|
||||
let (layer, filter) = ctx.data(|d| d.get_temp::<FilterDrag>(selected_key(doc.id)))?;
|
||||
if active != Some(LayerId(layer)) {
|
||||
return None;
|
||||
}
|
||||
let LayerContent::Smart(sm) = &doc.layer(LayerId(layer))?.content else { return None };
|
||||
let exists = match filter {
|
||||
Some(i) => i < sm.smart_filters.len(),
|
||||
None => !sm.smart_filters.is_empty(),
|
||||
};
|
||||
exists.then_some((layer, filter))
|
||||
}
|
||||
|
||||
/// Forgets the selected smart filter row: its smart object's own row was clicked, or the filter
|
||||
/// was deleted (its index would now name the next one).
|
||||
pub(crate) fn deselect(ctx: &egui::Context, doc: photocraft_doc::DocId) {
|
||||
ctx.data_mut(|d| d.remove::<FilterDrag>(selected_key(doc)));
|
||||
}
|
||||
|
||||
/// While smart filters are dragged: their name by the pointer, and the copy cursor while ⌥ is held.
|
||||
pub(crate) fn drag_feedback(ctx: &egui::Context, doc: &Document) {
|
||||
let Some((from, filter)) = ctx.data(|d| d.get_temp::<FilterDrag>(drag_key())) else { return };
|
||||
@@ -190,6 +219,53 @@ pub(crate) fn drop_on_row(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: R
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `layer.smartFilter.move` puts filter `src` (stack index, 0 = bottom) dropped on the row
|
||||
/// of filter `row` (`None`: the Smart Filters row, i.e. on top of the stack), `above` or below
|
||||
/// it, in a stack of `n`. `None` when the filter would stay where it is.
|
||||
fn reorder_target(src: usize, row: Option<usize>, above: bool, n: usize) -> Option<usize> {
|
||||
let to = match row {
|
||||
None => n.checked_sub(1)?,
|
||||
Some(i) if i == src => return None,
|
||||
// Above a row is just over it in the stack, below a row just under it. `move` removes
|
||||
// the filter first, so the filters over `src` shift down by one.
|
||||
Some(i) if above => {
|
||||
if src < i {
|
||||
i
|
||||
} else {
|
||||
i + 1
|
||||
}
|
||||
}
|
||||
Some(i) => {
|
||||
if src < i {
|
||||
i - 1
|
||||
} else {
|
||||
i
|
||||
}
|
||||
}
|
||||
};
|
||||
(to < n && to != src).then_some(to)
|
||||
}
|
||||
|
||||
/// A filter dragged up or down its own smart object's stack (Photoshop): over another row of the
|
||||
/// stack a line marks where it lands, above or below that row (the Smart Filters row: on top),
|
||||
/// and the release moves it there. The bottom filter is applied first, so the order changes the
|
||||
/// result (Unsharp Mask over a blur sharpens the blurred image; under it, the sharpening is
|
||||
/// blurred). Returns the filter's new index and the command.
|
||||
fn reorder_drop(ui: &egui::Ui, l: &Layer, n: usize, row: Option<usize>, rect: Rect) -> Option<(usize, (String, Value))> {
|
||||
let ctx = ui.ctx();
|
||||
let (from, src) = ctx.data(|d| d.get_temp::<FilterDrag>(drag_key()))?;
|
||||
let (src, p) = (src?, ctx.input(|i| i.pointer.interact_pos())?);
|
||||
if from != l.id.0 || !rect.contains(p) {
|
||||
return None;
|
||||
}
|
||||
let above = p.y < rect.center().y;
|
||||
let to = reorder_target(src, row, above, n)?;
|
||||
let t = Tokens::get(ctx);
|
||||
let y = if above && row.is_some() { rect.top() } else { rect.bottom() };
|
||||
ui.painter().line_segment([pos2(rect.left() + 30.0, y), pos2(rect.right(), y)], Stroke::new(2.0, t.accent));
|
||||
ctx.input(|i| i.pointer.any_released()).then(|| (to, ("layer.smartFilter.move".into(), json!({"layer": l.id.0, "index": src, "to": to}))))
|
||||
}
|
||||
|
||||
/// Smart filters dropped on the footer's Delete button: a filter's row deletes that filter, the
|
||||
/// Smart Filters row clears them all.
|
||||
pub(crate) fn trash_action((layer, filter): FilterDrag) -> (String, Value) {
|
||||
@@ -255,6 +331,25 @@ mod tests {
|
||||
[pixel, shape, smart].map(|id| doc.layer(photocraft_doc::LayerId(id)).unwrap().clone())
|
||||
}
|
||||
|
||||
/// Stack [A, B, C] (A at the bottom, drawn last): where a dragged filter lands.
|
||||
#[test]
|
||||
fn a_filter_dropped_above_or_below_a_row_lands_next_to_it() {
|
||||
// A over C: [B, C, A]. A under C: [B, A, C].
|
||||
assert_eq!(reorder_target(0, Some(2), true, 3), Some(2));
|
||||
assert_eq!(reorder_target(0, Some(2), false, 3), Some(1));
|
||||
// C under A: [C, A, B]. C over A: [A, C, B].
|
||||
assert_eq!(reorder_target(2, Some(0), false, 3), Some(0));
|
||||
assert_eq!(reorder_target(2, Some(0), true, 3), Some(1));
|
||||
// The Smart Filters row: on top.
|
||||
assert_eq!(reorder_target(0, None, false, 3), Some(2));
|
||||
// Next to where it already is, or on itself: nothing to do.
|
||||
assert_eq!(reorder_target(1, Some(2), false, 3), None);
|
||||
assert_eq!(reorder_target(1, Some(0), true, 3), None);
|
||||
assert_eq!(reorder_target(1, Some(1), true, 3), None);
|
||||
assert_eq!(reorder_target(2, None, true, 3), None);
|
||||
assert_eq!(reorder_target(0, None, true, 0), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shape_layers_and_smart_objects_carry_a_thumbnail_badge() {
|
||||
let [pixel, shape, smart] = layers();
|
||||
|
||||
@@ -1222,6 +1222,10 @@ pub struct UiState {
|
||||
/// modifiers held at its first click.
|
||||
#[serde(default)]
|
||||
pub polygon_mode: String,
|
||||
/// The document the polygon is drawn on (set at its first click): another document becoming
|
||||
/// active drops it (`canvas::polygon_cancel_stale`).
|
||||
#[serde(default)]
|
||||
pub polygon_doc: Option<photocraft_doc::DocId>,
|
||||
/// Magnetic Lasso border in progress (`magnetic_lasso_ui`).
|
||||
#[serde(default)]
|
||||
pub magnetic: crate::magnetic_lasso_ui::MagneticLasso,
|
||||
@@ -1329,6 +1333,7 @@ impl Default for UiState {
|
||||
tool_options: ToolOptions::default(),
|
||||
polygon: Vec::new(),
|
||||
polygon_mode: String::new(),
|
||||
polygon_doc: None,
|
||||
magnetic: Default::default(),
|
||||
crop_rect: None,
|
||||
crop_angle: 0.0,
|
||||
|
||||
@@ -196,3 +196,25 @@ fn fullscreen_status_zoom_preserves_shift_precision_and_recovers_from_the_minimu
|
||||
h.run_steps(1);
|
||||
assert!(h.state().ui.views[0].zoom > minimum, "reversing direction responds immediately after reaching a bound");
|
||||
}
|
||||
|
||||
/// #5016: toggling appearance between dark and light with default settings preserves the Pro
|
||||
/// layout and does not make a Fit button appear.
|
||||
#[test]
|
||||
fn appearance_toggle_preserves_pro_layout_and_has_no_fit_button() {
|
||||
let mut h = harness(ThemeKind::ProMedium);
|
||||
assert!(h.query_by_label("Fit").is_none());
|
||||
assert!(Tokens::get(&h.ctx).pro);
|
||||
|
||||
// Switch to Light mode (top-bar appearance button).
|
||||
let ctx = h.ctx.clone();
|
||||
crate::prefs_ui::cycle_appearance(h.state_mut(), &ctx);
|
||||
if h.state().session.prefs().interface.appearance_mode == photocraft_engine::prefs::AppearanceMode::Auto {
|
||||
crate::prefs_ui::cycle_appearance(h.state_mut(), &ctx);
|
||||
}
|
||||
crate::prefs_ui::tick(h.state_mut(), &ctx);
|
||||
h.run_steps(3);
|
||||
assert_eq!(h.state().session.prefs().interface.appearance_mode, photocraft_engine::prefs::AppearanceMode::Light);
|
||||
assert_eq!(h.state().ui.theme, ThemeKind::ProLight);
|
||||
assert!(Tokens::get(&h.ctx).pro);
|
||||
assert!(h.query_by_label("Fit").is_none(), "Fit button must not appear in light mode (#5016)");
|
||||
}
|
||||
@@ -339,6 +339,23 @@ mod tests {
|
||||
assert_eq!(runs[1].style.color.to_rgba8(), [255, 255, 255, 255]);
|
||||
}
|
||||
|
||||
/// #4790: the footer (size slider, New Group, New, Delete) stays inside the panel however short
|
||||
/// the dock makes it: the list scrolls instead of pushing the footer out of view.
|
||||
#[test]
|
||||
fn the_footer_fits_below_a_full_list() {
|
||||
use egui_kittest::kittest::Queryable;
|
||||
for h_px in [80.0, 100.0, 120.0, 160.0, 300.0] {
|
||||
let app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let mut h = Harness::builder().with_size(vec2(260.0, h_px)).build_ui_state(|ui, app: &mut PhotocraftApp| panel(app, ui), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, Default::default());
|
||||
h.run_steps(3);
|
||||
let bottom = h.ctx.input(|i| i.viewport_rect()).max.y;
|
||||
let slider = h.get_by_role(egui::accesskit::Role::Slider).rect().max.y;
|
||||
let delete = h.get_by_label("Delete").rect().max.y;
|
||||
assert!(slider <= bottom + 0.5 && delete <= bottom + 0.5, "{h_px} px panel: slider ends at {slider}, Delete at {delete}, panel at {bottom}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alt_click_sets_the_background_and_selects() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
|
||||
@@ -83,6 +83,44 @@ pub fn commit(app: &mut PhotocraftApp) {
|
||||
let _ = app.run("paint.setSymmetry", json!({"mode":t.preview.mode.id(), "center":t.preview.center,"rotation":t.preview.rotation}));
|
||||
}
|
||||
}
|
||||
/// While the symmetry is being transformed, the options bar names the edit and gives it ✓ and ⊘
|
||||
/// buttons, as Free Transform's bar does: Enter and Esc aren't the only ways out, which a pen or
|
||||
/// touch user may have no key for (#4495). False (nothing drawn) when no transform is open.
|
||||
pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) -> bool {
|
||||
if app.ui.symmetry_transform.is_none() {
|
||||
return false;
|
||||
}
|
||||
ui.label(egui::RichText::new(tl!("Transform Symmetry")).color(Tokens::get(ui.ctx()).text_dim));
|
||||
widgets::vline(ui, 22.0);
|
||||
let tip = crate::i18n::fmt(tl!("Commit transform ({key})"), &[("key", &crate::shortcuts::pretty("Enter"))]);
|
||||
let commit_btn = icons::button(ui, "check", 26.0, false, &tip);
|
||||
commit_btn.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Commit transform"));
|
||||
if commit_btn.clicked() {
|
||||
commit(app);
|
||||
}
|
||||
let cancel = icons::button(ui, "ban", 26.0, false, tl!("Cancel transform (Esc)"));
|
||||
cancel.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Cancel transform"));
|
||||
if cancel.clicked() {
|
||||
app.ui.symmetry_transform = None;
|
||||
}
|
||||
true
|
||||
}
|
||||
/// The canvas cursor while the symmetry is being transformed: the move cursor over the centre,
|
||||
/// the rotate cursor over the rotation handle and the arrow elsewhere, never the brush outline,
|
||||
/// since a press there doesn't paint (#4495). `None` when no transform is open on this document.
|
||||
pub fn cursor(app: &PhotocraftApp, xf: &ViewXform, p: [f64; 2]) -> Option<egui::CursorIcon> {
|
||||
let t = app.ui.symmetry_transform.as_ref().filter(|t| app.session.active_index() == Some(t.document))?;
|
||||
let size = app.session.active().map(|s| [f64::from(s.doc.size.width), f64::from(s.doc.size.height)]).unwrap_or([1.0, 1.0]);
|
||||
let tol = 8.0 / f64::from(xf.zoom.max(0.001));
|
||||
let distance = |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).hypot(a[1] - b[1]);
|
||||
Some(match t.gesture {
|
||||
Some(Gesture::Move { .. }) => egui::CursorIcon::Move,
|
||||
Some(Gesture::Rotate { .. }) => egui::CursorIcon::Alias,
|
||||
None if distance(p, t.preview.center) <= tol => egui::CursorIcon::Move,
|
||||
None if distance(p, rotation_handle(t.preview, size)) <= tol => egui::CursorIcon::Alias,
|
||||
None => egui::CursorIcon::Default,
|
||||
})
|
||||
}
|
||||
fn valid(app: &PhotocraftApp, t: &Transform) -> bool {
|
||||
app.session.active_index() == Some(t.document)
|
||||
&& app.ui.tool == t.tool
|
||||
|
||||
@@ -188,3 +188,56 @@ fn overlays_follow_document_view_transforms_in_every_theme() {
|
||||
assert_eq!(crate::i18n::tr(de, "Dual Axis"), "Duale Achse");
|
||||
assert_eq!(crate::i18n::tr(de, "Transform Symmetry"), "Symmetrie transformieren");
|
||||
}
|
||||
/// #4495: while the symmetry is transformed the options bar has ✓ and ⊘ (Enter and Esc were the
|
||||
/// only ways out), and the canvas shows the move, rotate or arrow cursor instead of the brush.
|
||||
#[test]
|
||||
fn transform_has_commit_and_cancel_buttons_and_its_own_cursors() {
|
||||
let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(64).build_eframe(|cc| {
|
||||
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
|
||||
PhotocraftApp::new(Session::new(), crate::Services::default())
|
||||
});
|
||||
h.state_mut().run("file.new", json!({"width":400,"height":300})).unwrap();
|
||||
h.state_mut().ui.tool = Tool::Brush;
|
||||
h.state_mut().run("paint.setSymmetry", json!({"mode":"dual"})).unwrap();
|
||||
h.run_steps(4);
|
||||
let cursor = |h: &Harness<'_, PhotocraftApp>| h.output().platform_output.cursor_icon;
|
||||
let begin_transform = |h: &mut Harness<'_, PhotocraftApp>| {
|
||||
let ctx = h.ctx.clone();
|
||||
crate::menus::invoke(h.state_mut(), &ctx, "ui.symmetryTransform", json!({})).unwrap();
|
||||
h.run_steps(3);
|
||||
};
|
||||
let xf = ViewXform::active(h.state()).expect("a canvas");
|
||||
let off_handles = xf.to_screen(40.0, 260.0);
|
||||
// Painting: the brush outline replaces the pointer.
|
||||
h.hover_at(off_handles);
|
||||
h.run_steps(2);
|
||||
assert_ne!(cursor(&h), egui::CursorIcon::Default, "the brush cursor while painting");
|
||||
assert!(h.query_by_label("Commit transform").is_none(), "no ✓ outside the transform");
|
||||
|
||||
begin_transform(&mut h);
|
||||
h.hover_at(off_handles);
|
||||
h.run_steps(2);
|
||||
assert_eq!(cursor(&h), egui::CursorIcon::Default, "an arrow, not the brush, away from the handles");
|
||||
let p = h.state().ui.symmetry_transform.as_ref().unwrap().preview;
|
||||
h.hover_at(xf.to_screen(p.center[0] as f32, p.center[1] as f32));
|
||||
h.run_steps(2);
|
||||
assert_eq!(cursor(&h), egui::CursorIcon::Move, "the centre moves");
|
||||
let r = rotation_handle(p, [400.0, 300.0]);
|
||||
h.hover_at(xf.to_screen(r[0] as f32, r[1] as f32));
|
||||
h.run_steps(2);
|
||||
assert_eq!(cursor(&h), egui::CursorIcon::Alias, "the handle rotates");
|
||||
|
||||
// ⊘ drops the preview; ✓ applies it.
|
||||
h.state_mut().ui.symmetry_transform.as_mut().unwrap().preview = PresetSymmetry::new(p.mode, [120.0, 90.0], 30.0).unwrap();
|
||||
h.get_by_label("Cancel transform").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.symmetry_transform.is_none());
|
||||
assert_eq!(preset(h.state()).unwrap().center, [200.0, 150.0], "cancel keeps the original");
|
||||
begin_transform(&mut h);
|
||||
h.state_mut().ui.symmetry_transform.as_mut().unwrap().preview = PresetSymmetry::new(p.mode, [120.0, 90.0], 30.0).unwrap();
|
||||
h.get_by_label("Commit transform").click();
|
||||
h.run_steps(3);
|
||||
assert!(h.state().ui.symmetry_transform.is_none());
|
||||
let done = preset(h.state()).unwrap();
|
||||
assert_eq!((done.center, done.rotation), ([120.0, 90.0], 30.0), "commit applies the preview");
|
||||
}
|
||||
@@ -122,9 +122,9 @@ impl ThemeKind {
|
||||
"pro" | "prodark" | "photoshop" | "dark" => Some(ThemeKind::Pro),
|
||||
"promedium" | "promediumgray" | "medium" | "mediumgray" => Some(ThemeKind::ProMedium),
|
||||
"prolightgray" | "lightgray" | "mediumlight" => Some(ThemeKind::ProLightGray),
|
||||
"prolight" | "prolightest" | "lightest" => Some(ThemeKind::ProLight),
|
||||
"prolight" | "prolightest" | "lightest" | "light" => Some(ThemeKind::ProLight),
|
||||
"studio" | "studiodark" => Some(ThemeKind::Studio),
|
||||
"studiolight" | "light" => Some(ThemeKind::StudioLight),
|
||||
"studiolight" => Some(ThemeKind::StudioLight),
|
||||
"classic" | "win2000" | "retro" => Some(ThemeKind::Classic),
|
||||
"adwaita" | "adwaitalight" | "gnome" | "gnomelight" => Some(ThemeKind::Adwaita),
|
||||
"adwaitadark" | "gnomedark" => Some(ThemeKind::AdwaitaDark),
|
||||
@@ -1202,6 +1202,7 @@ mod tests {
|
||||
assert_eq!(ThemeKind::from_name("Classic"), Some(ThemeKind::Classic));
|
||||
assert_eq!(ThemeKind::from_name("studio (light)"), Some(ThemeKind::StudioLight));
|
||||
assert_eq!(ThemeKind::from_name("dark"), Some(ThemeKind::Pro));
|
||||
assert_eq!(ThemeKind::from_name("light"), Some(ThemeKind::ProLight));
|
||||
assert_eq!(ThemeKind::from_name("studio"), Some(ThemeKind::Studio));
|
||||
assert_eq!(ThemeKind::from_name("Pro (Medium Gray)"), Some(ThemeKind::ProMedium));
|
||||
assert_eq!(ThemeKind::from_name("Solarized Dark"), Some(ThemeKind::SolarizedDark));
|
||||
|
||||
@@ -22,6 +22,7 @@ pub const BUTTON_WIDTH: f32 = 46.0;
|
||||
/// (#1581); 8 pt is about a native resize border, and only trims the toolbar buttons' outer 3 pt.
|
||||
const EDGE: f32 = 8.0;
|
||||
const CORNER: f32 = 12.0;
|
||||
const MODAL_DRAG_AREA: &str = "titlebar-modal-drag-area";
|
||||
/// Breeze's Close button on hover and press (KDE's Breeze decoration colours).
|
||||
const BREEZE_CLOSE_HOVER: Color32 = Color32::from_rgb(0xff, 0x98, 0xa2);
|
||||
const BREEZE_CLOSE_PRESSED: Color32 = Color32::from_rgb(0x6d, 0x22, 0x29);
|
||||
@@ -50,6 +51,32 @@ pub enum CaptionFamily {
|
||||
Generic,
|
||||
}
|
||||
|
||||
/// The title bar's unused gap, saved by `panels::title_bar` for drags that begin while a modal
|
||||
/// backdrop is on top of the normal title-bar widgets.
|
||||
pub(crate) fn modal_drag_area_id() -> Id {
|
||||
Id::new(MODAL_DRAG_AREA)
|
||||
}
|
||||
|
||||
/// Restore window dragging over the title bar's empty gap after a modal has blocked the normal
|
||||
/// title-bar layer. The hit target stays limited to the same gap, so menus and caption controls
|
||||
/// remain owned by their widgets.
|
||||
pub(crate) fn modal_drag_overlay(ctx: &egui::Context) {
|
||||
let Some(area) = ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id())) else { return };
|
||||
if !area.is_positive() || egui::Popup::is_any_open(ctx) || !crate::dialogs::titlebar_drag_area_is_clear(ctx, area) {
|
||||
return;
|
||||
}
|
||||
egui::Area::new(Id::new("titlebar-modal-drag-overlay")).order(Order::Tooltip).fixed_pos(area.min).movable(false).sense(Sense::hover()).show(ctx, |ui| {
|
||||
let response = ui.allocate_rect(area, Sense::click_and_drag());
|
||||
if response.drag_started() {
|
||||
ctx.send_viewport_cmd(ViewportCommand::StartDrag);
|
||||
}
|
||||
if response.double_clicked() {
|
||||
let max = ctx.input(|i| i.viewport().maximized.unwrap_or(false));
|
||||
ctx.send_viewport_cmd(ViewportCommand::Maximized(!max));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
impl CaptionFamily {
|
||||
/// `windows`, `adwaita`, `breeze` or `generic`, in any case.
|
||||
pub fn parse(name: &str) -> Option<Self> {
|
||||
@@ -530,6 +557,10 @@ mod tests {
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
|
||||
self.frame_with_modal(events, false)
|
||||
}
|
||||
|
||||
fn frame_with_modal(&mut self, events: Vec<Event>, modal: bool) -> egui::FullOutput {
|
||||
self.time += 0.05;
|
||||
let mut input =
|
||||
RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(self.width, 600.0))), time: Some(self.time), events, ..Default::default() };
|
||||
@@ -541,6 +572,12 @@ mod tests {
|
||||
let app = &mut self.app;
|
||||
let mut out = self.ctx.run_ui(input, |ui| {
|
||||
crate::panels::title_bar(app, ui);
|
||||
if modal {
|
||||
egui::Modal::new(Id::new("titlebar-drag-test-modal")).backdrop_color(Color32::TRANSPARENT).show(ui.ctx(), |ui| {
|
||||
ui.label("Modal dialog");
|
||||
});
|
||||
modal_drag_overlay(ui.ctx());
|
||||
}
|
||||
resize_zones(ui);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
@@ -550,10 +587,17 @@ mod tests {
|
||||
/// Frames for a pointer gesture: move to `path[0]`, press, move along `path`, release. The
|
||||
/// viewport commands the frames sent.
|
||||
fn gesture(&mut self, path: &[Pos2]) -> Vec<ViewportCommand> {
|
||||
self.gesture_with_modal(path, false)
|
||||
}
|
||||
|
||||
fn gesture_with_modal(&mut self, path: &[Pos2], modal: bool) -> Vec<ViewportCommand> {
|
||||
let mut events = vec![vec![Event::PointerMoved(path[0])], vec![button(path[0], true)]];
|
||||
events.extend(path[1..].iter().map(|p| vec![Event::PointerMoved(*p)]));
|
||||
events.push(vec![button(*path.last().unwrap_or(&path[0]), false)]);
|
||||
events.into_iter().flat_map(|e| self.frame(e).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default()).collect()
|
||||
events
|
||||
.into_iter()
|
||||
.flat_map(|e| self.frame_with_modal(e, modal).viewport_output.remove(&ViewportId::ROOT).map(|v| v.commands).unwrap_or_default())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn click(&mut self, p: Pos2) -> Vec<ViewportCommand> {
|
||||
@@ -675,6 +719,31 @@ mod tests {
|
||||
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_bar_space_still_drags_with_a_modal_open() {
|
||||
let mut w = Win::new(1440.0);
|
||||
w.frame(vec![]);
|
||||
w.frame_with_modal(vec![], true);
|
||||
let empty = pos2(980.0, 16.0);
|
||||
let drag_area = w.ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id()));
|
||||
assert!(drag_area.is_some_and(|r| r.contains(empty)), "the test point must be in the current title-bar gap: {drag_area:?}");
|
||||
assert!(w.bar_widgets().iter().all(|r| !r.contains(empty)), "the probe point must be empty bar space");
|
||||
let cmds = w.gesture_with_modal(&[empty, empty + vec2(12.0, 4.0), empty + vec2(30.0, 8.0)], true);
|
||||
assert_eq!(cmds.iter().filter(|c| matches!(c, ViewportCommand::StartDrag)).count(), 1, "{cmds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modal_drag_overlay_does_not_cover_a_dialog_moved_into_the_gap() {
|
||||
let mut w = Win::new(1440.0);
|
||||
w.frame(vec![]);
|
||||
w.frame_with_modal(vec![], true);
|
||||
let area = w.ctx.data(|d| d.get_temp::<Rect>(modal_drag_area_id())).unwrap_or(Rect::NOTHING);
|
||||
assert!(area.contains(pos2(980.0, 16.0)), "the probe point must be in the gap: {area:?}");
|
||||
w.ctx.data_mut(|d| d.insert_temp(Id::new("pc-dialog-rects"), vec![area]));
|
||||
let cmds = w.gesture_with_modal(&[area.center(), area.center() + vec2(12.0, 4.0)], true);
|
||||
assert!(!cmds.iter().any(|c| matches!(c, ViewportCommand::StartDrag)), "{cmds:?}");
|
||||
}
|
||||
|
||||
/// #1581: KDE Wayland keeps the button release of an OS resize. egui then kept the edge
|
||||
/// pressed (no hover until the next click) and egui-winit never re-sent the resize cursor that
|
||||
/// the compositor had replaced: the cursor came back only on every other press.
|
||||
|
||||
Loaded 100 of 119 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user