mirror of
https://github.com/storytold/photocraft.git
synced 2026-11-16 15:14:38 +00:00
Merge main into control-prefs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
152e8d8518
43 files changed
+3189
-119
No files matched your search
@@ -0,0 +1,87 @@
|
||||
//! Pressure for Size starts off (#11809). The reference application leaves both pressure toggles
|
||||
//! in the options bar unhighlighted after Reset Tool, so a fresh brush has neither on — and the
|
||||
//! brush Reset Tool hands back is `BrushSettings::default()` plus smoothing
|
||||
//! (`crates/ui-egui/src/canvas/paint_mouse.rs::fresh_brush`), so the default is what the tool
|
||||
//! reset reports through `brush.get`. The options bar's two `circle-dot` buttons are drawn from
|
||||
//! these same two fields (`crates/ui-egui/src/panels/options_bar.rs`), so off here means drawn
|
||||
//! off there.
|
||||
|
||||
use crate::Session;
|
||||
use photocraft_paint::brush::BrushSettings;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// The brush a fresh session starts with: neither pressure toggle on.
|
||||
#[test]
|
||||
fn the_default_brush_has_neither_pressure_toggle_on() {
|
||||
let b = BrushSettings::default();
|
||||
assert!(!b.pressure_size, "Pressure for Size is off by default, as the reference leaves it after Reset Tool (#11809)");
|
||||
assert!(!b.pressure_opacity, "Pressure for Opacity stays off");
|
||||
}
|
||||
|
||||
/// What `brush.get` answers on a fresh session, which is what the options bar reads to draw the
|
||||
/// two toggles.
|
||||
#[test]
|
||||
fn brush_get_reports_both_pressure_toggles_off() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
let got = s.execute("brush.get", json!({})).unwrap();
|
||||
assert_eq!(got["pressureSize"], json!(false), "brush.get reports Pressure for Size off (#11809)");
|
||||
assert_eq!(got["pressureOpacity"], json!(false), "brush.get reports Pressure for Opacity off");
|
||||
// The session's own starting brush is the default brush at Photoshop's 10 % smoothing — the
|
||||
// same brush Reset Tool hands back — so only the smoothing differs.
|
||||
assert_eq!(
|
||||
s.tools.brush,
|
||||
BrushSettings { smoothing: photocraft_paint::brush::Smoothing { amount: 0.1, ..Default::default() }, ..BrushSettings::default() }
|
||||
);
|
||||
}
|
||||
|
||||
/// A brush that does not name the field — a preset saved before #11809, an older recorded
|
||||
/// command — takes the off default rather than the old on one.
|
||||
#[test]
|
||||
fn a_brush_that_omits_the_field_takes_the_off_default() {
|
||||
let b: BrushSettings = serde_json::from_value(json!({"size": 30.0, "hardness": 1.0})).unwrap();
|
||||
assert!(!b.pressure_size, "an omitted pressureSize reads as off (#11809)");
|
||||
assert!(!b.pressure_opacity, "an omitted pressureOpacity reads as off");
|
||||
assert_eq!(b.size, 30.0, "the fields that are there still apply");
|
||||
}
|
||||
|
||||
/// Switching it on still works: `tools.setBrush` writes the field `brush.get` reads back, and the
|
||||
/// same field the options-bar button is drawn from.
|
||||
#[test]
|
||||
fn pressure_for_size_still_switches_on_and_off() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 32, "height": 32})).unwrap();
|
||||
s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap();
|
||||
assert!(s.tools.brush.pressure_size, "the toggle still turns on");
|
||||
assert_eq!(s.execute("brush.get", json!({})).unwrap()["pressureSize"], json!(true));
|
||||
s.execute("tools.setBrush", json!({"brush": {"pressureSize": false}})).unwrap();
|
||||
assert!(!s.tools.brush.pressure_size, "and off again");
|
||||
assert!(!s.tools.brush.pressure_opacity, "it never touches Pressure for Opacity");
|
||||
}
|
||||
|
||||
/// One stroke of a pressure ramp (0.3 → 0.65 → 1.0) across a new empty layer with `brush`: the
|
||||
/// layer's pixels and what the stroke covers.
|
||||
fn ramp(brush: Value) -> (Vec<f32>, photocraft_geom::Rect) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 80, "height": 40})).unwrap();
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
s.execute("paint.stroke", json!({"points": [[20.0, 20.0, 0.3], [40.0, 20.0, 0.65], [60.0, 20.0, 1.0]], "size": 24.0, "color": "#ff0000", "brush": brush}))
|
||||
.unwrap();
|
||||
let st = s.active().unwrap();
|
||||
let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
|
||||
(surf.read_region(st.doc.bounds()), surf.content_bounds())
|
||||
}
|
||||
|
||||
/// Done when 2: a pen stroke with varying pressure and the default brush keeps a constant size,
|
||||
/// so it paints exactly what the same stroke with Pressure for Size turned off does — and
|
||||
/// something else with it turned on, which is what makes this say anything.
|
||||
#[test]
|
||||
fn a_default_brush_stroke_keeps_its_size_under_a_pressure_ramp() {
|
||||
let (off, off_box) = ramp(json!({"spacing": 0.25, "pressureSize": false}));
|
||||
let (on, on_box) = ramp(json!({"spacing": 0.25, "pressureSize": true}));
|
||||
let (dflt, dflt_box) = ramp(json!({"spacing": 0.25}));
|
||||
assert_ne!(on, off, "the ramp alone does not change the stroke: Pressure for Size has to");
|
||||
assert_eq!(dflt, off, "the default brush paints like Pressure for Size off (#11809)");
|
||||
assert_eq!(dflt_box, off_box, "and reaches as far under the whole ramp");
|
||||
assert_ne!(dflt_box, on_box, "the turned-on brush still tapers the stroke's ends");
|
||||
}
|
||||
@@ -67,6 +67,8 @@ pub mod color_cmds;
|
||||
pub mod color_to_alpha_cmds;
|
||||
pub mod comps_cmds;
|
||||
pub mod contour_lib_cmds;
|
||||
#[cfg(test)]
|
||||
mod count_delete_group_tests;
|
||||
pub mod cutout_cmds;
|
||||
pub mod distort_cmds;
|
||||
pub mod document_preset_cmds;
|
||||
|
||||
@@ -896,9 +896,15 @@ fn count_delete_group(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.edit("Delete Count Group", |d, _| {
|
||||
d.measurement.count_groups.remove(g);
|
||||
let n = d.measurement.count_groups.len();
|
||||
// Removing a group before the active one shifts it down a slot.
|
||||
// Deleting the current group makes the first one current (#11771); removing a group
|
||||
// before the current one shifts it down a slot (#5654).
|
||||
let a = d.measurement.active_count_group;
|
||||
d.measurement.active_count_group = (if g < a { a - 1 } else { a }).min(n.saturating_sub(1));
|
||||
let next = match g.cmp(&a) {
|
||||
std::cmp::Ordering::Equal => 0,
|
||||
std::cmp::Ordering::Less => a - 1,
|
||||
std::cmp::Ordering::Greater => a,
|
||||
};
|
||||
d.measurement.active_count_group = next.min(n.saturating_sub(1));
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(count_json(doc(s)?.as_ref()))
|
||||
|
||||
@@ -26,8 +26,9 @@ fn stroke_backwards_compatible() {
|
||||
assert_eq!(r["damage"].as_array().unwrap().len(), 4);
|
||||
assert_eq!(rgba(&s, 30, 20), [0.0, 0.0, 1.0, 1.0]);
|
||||
assert_eq!(rgba(&s, 30, 30)[3], 0.0);
|
||||
// [x, y, pressure] with the default pressure-size brush: light pressure → thinner line.
|
||||
s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10})).unwrap();
|
||||
// [x, y, pressure] with Pressure for Size on: light pressure → a thinner line. The default
|
||||
// brush has it off since #11809, so this stroke asks for it.
|
||||
s.execute("paint.stroke", json!({"points": [[4, 5, 0.2], [60, 5, 0.2]], "size": 10, "brush": {"pressureSize": true}})).unwrap();
|
||||
assert!(rgba(&s, 30, 5)[3] > 0.9 && rgba(&s, 30, 8)[3] < 0.01);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! #11771: deleting the current count group makes the first remaining group current. Deleting
|
||||
//! another group by index keeps the current one (#5654), and the last group goes without error.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::Session;
|
||||
|
||||
/// Three groups, each with one marker, and the second one current.
|
||||
fn three_groups() -> Session {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
for (i, name) in ["One", "Two", "Three"].iter().enumerate() {
|
||||
s.execute("count.newGroup", json!({"name": name})).unwrap();
|
||||
s.execute("count.add", json!({"x": 10 + 10 * i, "y": 10})).unwrap();
|
||||
}
|
||||
s.execute("count.setGroup", json!({"group": 1})).unwrap();
|
||||
assert_eq!(current(&mut s), (1, "Two".to_string()));
|
||||
s
|
||||
}
|
||||
|
||||
/// The current group's index and name.
|
||||
fn current(s: &mut Session) -> (u64, String) {
|
||||
let c = s.execute("image.analysis.countTool", json!({})).unwrap();
|
||||
let i = c["activeGroup"].as_u64().unwrap();
|
||||
let name = c["groups"].get(i as usize).and_then(|g| g["name"].as_str()).unwrap_or_default().to_string();
|
||||
(i, name)
|
||||
}
|
||||
|
||||
fn groups(s: &mut Session) -> usize {
|
||||
s.execute("image.analysis.countTool", json!({})).unwrap()["groups"].as_array().map_or(0, Vec::len)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_current_group_makes_the_first_one_current() {
|
||||
for params in [json!({}), json!({"group": 1})] {
|
||||
let mut s = three_groups();
|
||||
s.execute("count.deleteGroup", params.clone()).unwrap();
|
||||
assert_eq!(groups(&mut s), 2, "{params}");
|
||||
assert_eq!(current(&mut s), (0, "One".to_string()), "{params}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_another_group_keeps_the_current_one() {
|
||||
let mut s = three_groups();
|
||||
s.execute("count.deleteGroup", json!({"group": 2})).unwrap();
|
||||
assert_eq!(current(&mut s), (1, "Two".to_string()));
|
||||
let mut s = three_groups();
|
||||
s.execute("count.deleteGroup", json!({"group": 0})).unwrap();
|
||||
assert_eq!(current(&mut s), (0, "Two".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_last_group_leaves_none() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", json!({"width": 100, "height": 100})).unwrap();
|
||||
s.execute("count.newGroup", json!({"name": "Only"})).unwrap();
|
||||
s.execute("count.deleteGroup", json!({})).unwrap();
|
||||
let c: Value = s.execute("image.analysis.countTool", json!({})).unwrap();
|
||||
assert_eq!(c["groups"].as_array().map(Vec::len), Some(0));
|
||||
}
|
||||
@@ -653,6 +653,9 @@ fn stroke_path_simulate_pressure_tapers_both_ends() {
|
||||
let coverage = |simulate: bool, x: i32| -> usize {
|
||||
let mut s = session(200, 60, 8);
|
||||
s.execute("layer.new.layer", json!({})).unwrap();
|
||||
// Simulate Pressure tapers a brush that follows pen pressure; the default brush stopped
|
||||
// doing that on its own (#11809).
|
||||
s.execute("tools.setBrush", json!({"brush": {"pressureSize": true}})).unwrap();
|
||||
s.execute("path.set", json!({"path": {"subpaths": [{"closed": false, "knots": [[20, 30], [180, 30]]}]}})).unwrap();
|
||||
let p = json!({"tool": "brush", "size": 20, "hardness": 1.0, "color": "#000000", "opacity": 100, "simulatePressure": simulate});
|
||||
s.execute("path.stroke", p).unwrap();
|
||||
|
||||
@@ -339,6 +339,8 @@ pub struct Session {
|
||||
pub damage_misses: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod brush_pressure_size_default_tests;
|
||||
#[cfg(test)]
|
||||
mod embed_all_linked_tests;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -630,7 +630,8 @@ impl Default for BrushSettings {
|
||||
spacing_enabled: true,
|
||||
opacity: 1.0,
|
||||
flow: 1.0,
|
||||
pressure_size: true,
|
||||
// Off, as the reference application leaves it after Reset Tool (#11809).
|
||||
pressure_size: false,
|
||||
pressure_opacity: false,
|
||||
color: [0.0, 0.0, 0.0, 1.0],
|
||||
color_cmyk: None,
|
||||
|
||||
@@ -72,7 +72,7 @@ camera colour tables were copied.
|
||||
| DNG | Uncompressed (8–16 bit, packed or not), Deflate (compression 8, predictors 1 and 2), lossless JPEG, lossy JPEG (DNG 1.4 compression 34892: 8-bit baseline JPEG tiles or strips, gray for CFA, YCbCr-coded RGB for LinearRaw; decoded by `zune-jpeg`, the stored 8-bit values then go through the same LinearizationTable / BlackLevel / WhiteLevel as every other depth) and JPEG XL (DNG 1.7, e.g. Samsung Expert RAW; decoded by `jxl-oxide`; not in wasm32 builds, where it is `Unsupported`); strips and tiles; CFA (Bayer) and LinearRaw (three-sample colour, or one-sample monochrome such as Leica Monochrom and film-scanner DNGs, developed as neutral grey with no white balance or colour matrix); LinearizationTable, BlackLevel (+ repeat, DeltaH/V), WhiteLevel, ActiveArea, DefaultCrop, ColorMatrix1/2, CameraCalibration, ForwardMatrix, AnalogBalance, AsShotNeutral / AsShotWhiteXY, BaselineExposure, Orientation, floating-point JPEG XL raw data (DNG 1.7 lossy LinearRaw, as Adobe DNG Converter writes it; scaled by the highest WhiteLevel), OpcodeList2 GainMap (lens shading) and MapPolynomial |
|
||||
| DNG (floating point other than JPEG XL; opcodes other than OpcodeList2 GainMap and MapPolynomial; ProfileGainTableMap) | Unsupported / not applied (reported) |
|
||||
| CR2 | Lossless JPEG with slices, borders and as-shot white balance from the maker note, black measured on the masked border. CR2 has no CFA tag and the row phase varies by model, so it is measured from the data (the green diagonal), with a Canon model-ID table as the fallback (see `src/cr2.rs`) |
|
||||
| CR2 sRAW / mRAW | Unsupported |
|
||||
| CR2 sRAW / mRAW (subsampled YCbCr) | Decoded to camera RGB and developed like LinearRaw: Canon's subsampled lossless JPEG (Y 2×2 or 2×1), BT.601 inverse, bilinear chroma, the per-shot sRAW gains from ColorData (version 15: EOS 6D Mark II, 77D, 200D, 800D; other bodies warn and rely on the fitted camera look). See `src/sraw.rs` |
|
||||
| NEF / NRW, ARW, PEF and other TIFF/EP raws | Uncompressed and lossless-JPEG (incl. Sony lossless ARW) CFA data |
|
||||
| Nikon compressed NEF (compression 34713): lossless and lossy type 1 / 2, 12 and 14 bit | Decoded: fixed Huffman tables + maker-note `0x0096` seeds and curve (see `src/nefc.rs`). BlackLevel `0x003d` is read in 14-bit units. "Lossy after split" files are unsupported (preview fallback) |
|
||||
| Sony compressed ARW ("cRAW", SonyRawFileType 2) | Decoded: 11-bit min/max + 7-bit delta blocks, SonyToneCurve to 14 bits; applied WB and black from plain tags or encrypted SR2SubIFD with the measured common key. If metadata is unreadable, black falls back to 512 and WB to grey-world. Measured ILCE-7 / ILCE-6000 image area; camera colour calibration remains incomplete |
|
||||
|
||||
+121
-41
@@ -5,7 +5,8 @@
|
||||
//! lossless JPEG (T.81 process 14) whose decoded sample sequence fills the
|
||||
//! sensor image in vertical slices: the private tag 0xC640 gives the slice
|
||||
//! count, slice width and last slice width; slice 0 is filled row by row,
|
||||
//! then slice 1, and so on. sRAW/mRAW (subsampled YCbCr) is not supported.
|
||||
//! then slice 1, and so on. sRAW / mRAW (subsampled YCbCr) is decoded to
|
||||
//! camera RGB by `sraw.rs`.
|
||||
//!
|
||||
//! Sensor geometry and the as-shot white balance come from the Canon maker
|
||||
//! note (an IFD at the MakerNote offset, values relative to the TIFF header):
|
||||
@@ -45,7 +46,7 @@
|
||||
use crate::error::{RawError, Result};
|
||||
use crate::sensor::{BlackLevels, Cfa, Rect, Sensor};
|
||||
use crate::tiff::{Ifd, Tiff, tag};
|
||||
use crate::{Limits, RawFormat, ljpeg};
|
||||
use crate::{Limits, RawFormat, ljpeg, sraw};
|
||||
|
||||
const CANON_SENSOR_INFO: u16 = 0x00E0;
|
||||
const CANON_COLOR_DATA: u16 = 0x4001;
|
||||
@@ -115,26 +116,38 @@ pub(crate) fn maker_note(t: &Tiff, ifds: &[Ifd]) -> Option<Ifd> {
|
||||
|
||||
/// As-shot white-balance multipliers (R, G, B) from ColorData.
|
||||
fn as_shot_wb(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> {
|
||||
let e = mn.get(CANON_COLOR_DATA)?;
|
||||
// The entry is UNDEFINED: its bytes are a table of 16-bit words (file byte order), and the
|
||||
// offsets below count words, not bytes. Reads stay inside the entry's own byte count.
|
||||
let bytes = e.unit().checked_mul(e.count as usize)?;
|
||||
let word = |off: usize| {
|
||||
let at = off.checked_mul(2)?.checked_add(e.at)?;
|
||||
(at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten().map(f64::from)
|
||||
};
|
||||
// Word offsets of WB_RGGBLevelsAsShot used by the ColorData versions.
|
||||
for off in [0x3F, 0x47, 0x19, 0x22] {
|
||||
let (Some(r), Some(g1), Some(g2), Some(b)) = (word(off), word(off + 1), word(off + 2), word(off + 3)) else {
|
||||
continue;
|
||||
};
|
||||
let g = (g1 + g2) / 2.0;
|
||||
let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g));
|
||||
if plausible {
|
||||
return Some([r / g, 1.0, b / g]);
|
||||
}
|
||||
}
|
||||
None
|
||||
[0x3F, 0x47, 0x19, 0x22].into_iter().find_map(|off| color_data_rggb(t, mn, off))
|
||||
}
|
||||
|
||||
/// Word `off` of ColorData. The entry is UNDEFINED: its bytes are a table of 16-bit words (file
|
||||
/// byte order), and the offsets count words, not bytes. Reads stay inside the entry's own byte
|
||||
/// count.
|
||||
fn color_data_word(t: &Tiff, mn: &Ifd, off: usize) -> Option<u16> {
|
||||
let e = mn.get(CANON_COLOR_DATA)?;
|
||||
let bytes = e.unit().checked_mul(e.count as usize)?;
|
||||
let at = off.checked_mul(2)?.checked_add(e.at)?;
|
||||
(at.checked_add(2)? <= e.at.checked_add(bytes)?).then(|| t.u16_at(at)).flatten()
|
||||
}
|
||||
|
||||
/// RGGB levels at ColorData word `off` as multipliers relative to green, when plausible.
|
||||
fn color_data_rggb(t: &Tiff, mn: &Ifd, off: usize) -> Option<[f64; 3]> {
|
||||
let word = |k: usize| color_data_word(t, mn, off.checked_add(k)?).map(f64::from);
|
||||
let (r, g1, g2, b) = (word(0)?, word(1)?, word(2)?, word(3)?);
|
||||
let g = (g1 + g2) / 2.0;
|
||||
let plausible = (256.0..16384.0).contains(&g) && (g1 - g2).abs() <= g * 0.05 && (0.25..8.0).contains(&(r / g)) && (0.25..8.0).contains(&(b / g));
|
||||
plausible.then(|| [r / g, 1.0, b / g])
|
||||
}
|
||||
|
||||
/// ColorData versions whose sRAW gains (see `sraw.rs`) sit at a word offset we observed:
|
||||
/// version 15 (EOS 6D Mark II, 77D, 200D, 800D) at 0x80, just before the daylight preset.
|
||||
const SRAW_GAINS: [(u16, usize); 1] = [(15, 0x80)];
|
||||
|
||||
/// The per-shot gains an sRAW's stored RGB was divided by, relative to green.
|
||||
fn sraw_gains(t: &Tiff, mn: &Ifd) -> Option<[f64; 3]> {
|
||||
let version = color_data_word(t, mn, 0)?;
|
||||
let (_, off) = SRAW_GAINS.iter().find(|(v, _)| *v == version)?;
|
||||
color_data_rggb(t, mn, *off)
|
||||
}
|
||||
|
||||
/// The white (clipping) level: the largest value when a meaningful share of
|
||||
@@ -181,6 +194,86 @@ pub(crate) fn masked_black(data: &[u16], width: usize, area: Rect) -> Option<[f3
|
||||
Some([0, 1, 2, 3].map(|k| sum[k] as f32 / n[k] as f32))
|
||||
}
|
||||
|
||||
/// The slice widths of CR2 tag 0xC640 (count, width, last width), in samples. The tag is SHORT:
|
||||
/// larger values (a LONG in a damaged file) are refused, which also bounds the sum.
|
||||
fn slice_widths(tag: &[u32]) -> Option<Vec<usize>> {
|
||||
let short = 1..=u32::from(u16::MAX);
|
||||
match tag {
|
||||
[n, w, last] if *n < 64 && short.contains(w) && short.contains(last) => {
|
||||
let mut ws = vec![*w as usize; *n as usize];
|
||||
ws.push(*last as usize);
|
||||
Some(ws)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The image area inside `full` from the maker note's SensorInfo ([1] width, [2] height, [5]
|
||||
/// left, [6] top, [7] right, [8] bottom border, inclusive); `full` when absent or empty.
|
||||
fn image_area(t: &Tiff, mn: Option<&Ifd>, full: Rect) -> Rect {
|
||||
let info = mn.map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default();
|
||||
let active = match info.get(5..9) {
|
||||
Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full),
|
||||
_ => full,
|
||||
};
|
||||
if active.is_empty() { full } else { active }
|
||||
}
|
||||
|
||||
/// sRAW / mRAW: subsampled YCbCr, developed as three-sample camera RGB (see `sraw.rs`).
|
||||
fn decode_sraw(t: &Tiff, ifds: &[Ifd], ifd0: &Ifd, slices: &[u32], src: &[u8], frame: ljpeg::Frame, limits: &Limits) -> Result<Sensor> {
|
||||
let per_mcu = frame.h * frame.v + 2;
|
||||
let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?;
|
||||
let widths = slice_widths(slices).unwrap_or_else(|| vec![frame.width / frame.h * per_mcu]);
|
||||
let row: usize = widths.iter().sum();
|
||||
if row == 0 || !row.is_multiple_of(per_mcu) || !total.is_multiple_of(row) {
|
||||
return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame"));
|
||||
}
|
||||
let (width, height) = (row / per_mcu * frame.h, total / row * frame.v);
|
||||
// The RGB output: three u16 per pixel.
|
||||
limits.check(width as u64, height as u64, 6)?;
|
||||
let (_, samples) = ljpeg::decode_subsampled(src, total)?;
|
||||
let planes = sraw::planes(&frame, &samples, &widths)?;
|
||||
drop(samples);
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
let mn = maker_note(t, ifds);
|
||||
let camera_wb = mn.as_ref().and_then(|m| as_shot_wb(t, m));
|
||||
let gains = mn.as_ref().and_then(|m| sraw_gains(t, m));
|
||||
if gains.is_none() {
|
||||
warnings.push("the sRAW colour gains of this camera are not known; colours rely on the look fitted to the camera's JPEG".to_string());
|
||||
}
|
||||
let offset = (1u32 << (frame.precision - 1)) as f32;
|
||||
let data = sraw::camera_rgb(&planes, offset, gains.unwrap_or([1.0; 3]));
|
||||
drop(planes);
|
||||
let full = Rect::new(0, 0, width, height);
|
||||
let active = image_area(t, mn.as_ref(), full);
|
||||
let white = [0, 1, 2].map(|k| sraw::clip_level(&data, k, sraw::FULL_SCALE));
|
||||
Ok(Sensor {
|
||||
format: RawFormat::Cr2,
|
||||
make: t.tag_ascii(ifd0, tag::MAKE),
|
||||
model: t.tag_ascii(ifd0, tag::MODEL),
|
||||
width,
|
||||
height,
|
||||
samples: 3,
|
||||
data,
|
||||
cfa: None,
|
||||
linearization: None,
|
||||
// Y is stored black-subtracted.
|
||||
black: BlackLevels::uniform(0.0),
|
||||
white,
|
||||
active,
|
||||
crop: active,
|
||||
color: Default::default(),
|
||||
camera_wb,
|
||||
orientation: crate::tiff::orientation(t.tag_uint(ifd0, tag::ORIENTATION)),
|
||||
baseline_exposure: 0.0,
|
||||
gain_maps: Vec::new(),
|
||||
tone_curve: Vec::new(),
|
||||
black_point: 0.0,
|
||||
warnings,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
let ifds = t.all_ifds();
|
||||
let ifd0 = t.ifd_at(t.first_ifd, 0).ok_or_else(|| RawError::malformed("CR2 has no IFD0"))?;
|
||||
@@ -191,23 +284,16 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
let src = t.bytes(off, len).or_else(|| t.data.get(off..)).ok_or_else(|| RawError::malformed("CR2 raw data lies outside the file"))?;
|
||||
|
||||
let frame = ljpeg::frame(src).map_err(|e| match e {
|
||||
RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("Canon sRAW / mRAW"),
|
||||
RawError::Unsupported(m) if m.contains("subsampled") => RawError::unsupported("this Canon sRAW / mRAW layout"),
|
||||
e => e,
|
||||
})?;
|
||||
let total = frame.samples().ok_or_else(|| RawError::malformed("CR2 frame too large"))?;
|
||||
let slices = t.tag_uints(&raw, tag::CR2_SLICE);
|
||||
let (width, widths) = match slices.as_slice() {
|
||||
[n, w, last] if *n < 64 && *w > 0 && *last > 0 => {
|
||||
let (n, w, last) = (*n as usize, *w as usize, *last as usize);
|
||||
let mut ws = vec![w; n];
|
||||
ws.push(last);
|
||||
(n * w + last, ws)
|
||||
}
|
||||
_ => {
|
||||
let w = frame.width * frame.components;
|
||||
(w, vec![w])
|
||||
}
|
||||
};
|
||||
if frame.is_subsampled() {
|
||||
return decode_sraw(t, &ifds, &ifd0, &slices, src, frame, limits);
|
||||
}
|
||||
let widths = slice_widths(&slices).unwrap_or_else(|| vec![frame.width * frame.components]);
|
||||
let width: usize = widths.iter().sum();
|
||||
if width == 0 || total % width != 0 {
|
||||
return Err(RawError::malformed("CR2 slices do not match the JPEG frame"));
|
||||
}
|
||||
@@ -231,13 +317,7 @@ pub(crate) fn decode(t: &Tiff, limits: &Limits) -> Result<Sensor> {
|
||||
let mut warnings = Vec::new();
|
||||
let mn = maker_note(t, &ifds);
|
||||
let full = Rect::new(0, 0, width, height);
|
||||
// SensorInfo: [1] width, [2] height, [5] left, [6] top, [7] right, [8] bottom border (inclusive).
|
||||
let info = mn.as_ref().map(|m| t.tag_uints(m, CANON_SENSOR_INFO)).unwrap_or_default();
|
||||
let active = match info.get(5..9) {
|
||||
Some(&[l, tp, r, b]) if r > l && b > tp => Rect::new(l as usize, tp as usize, (r - l + 1) as usize, (b - tp + 1) as usize).intersect(&full),
|
||||
_ => full,
|
||||
};
|
||||
let active = if active.is_empty() { full } else { active };
|
||||
let active = image_area(t, mn.as_ref(), full);
|
||||
// Black: the masked columns left of the image (skipping a few edge columns).
|
||||
let black = if active.x >= 16 {
|
||||
// Only the outer half: the columns next to the image area can be partly exposed.
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
//! image area (the D800E, the ILCE-7).
|
||||
//!
|
||||
//! Decoded today: DNG (uncompressed, deflate, lossless-JPEG, lossy-JPEG and JPEG XL, strips and
|
||||
//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices), uncompressed or
|
||||
//! tiles, CFA and LinearRaw), CR2 (lossless JPEG with Canon slices, and sRAW / mRAW), uncompressed or
|
||||
//! lossless-JPEG TIFF/EP raws (NEF, ARW, PEF… when not vendor-compressed),
|
||||
//! Nikon compressed NEF (lossless and lossy), Sony compressed ARW (cRAW),
|
||||
//! Panasonic RW2 (RawFormat 5 packed and RawFormat 3/4 vendor-compressed),
|
||||
@@ -65,6 +65,7 @@ mod saturation;
|
||||
mod sensor;
|
||||
mod sony;
|
||||
mod sony_metadata;
|
||||
mod sraw;
|
||||
mod tiff;
|
||||
mod tiffep;
|
||||
mod tone;
|
||||
|
||||
+183
-10
@@ -8,8 +8,10 @@
|
||||
//!
|
||||
//! Output is the sample sequence in raster order: `height` rows of `width ×
|
||||
//! components` interleaved samples. Only one interleaved scan holding every
|
||||
//! component with sampling factors 1×1 is supported, which is how DNG, CR2
|
||||
//! and the TIFF-based raws use it.
|
||||
//! component is supported, which is how DNG, CR2 and the TIFF-based raws use
|
||||
//! it; [`decode`] takes sampling factors 1×1 only. Canon's sRAW / mRAW frames
|
||||
//! (three components, the first sampled 2×1 or 2×2) go through
|
||||
//! [`decode_subsampled`], which follows Canon's prediction rather than T.81's.
|
||||
|
||||
use crate::error::{RawError, Result};
|
||||
|
||||
@@ -20,11 +22,21 @@ pub(crate) struct Frame {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub components: usize,
|
||||
/// Horizontal and vertical sampling factors of the first component (1 and 1 unless the
|
||||
/// frame is subsampled; the other components are then sampled 1×1).
|
||||
pub h: usize,
|
||||
pub v: usize,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
/// Samples in the frame: per MCU, `h × v` of the first component and one of each other.
|
||||
pub fn samples(&self) -> Option<usize> {
|
||||
self.width.checked_mul(self.height)?.checked_mul(self.components)
|
||||
let mcus = (self.width / self.h.max(1)).checked_mul(self.height / self.v.max(1))?;
|
||||
mcus.checked_mul(self.h.checked_mul(self.v)?.checked_add(self.components)?.checked_sub(1)?)
|
||||
}
|
||||
|
||||
pub fn is_subsampled(&self) -> bool {
|
||||
self.h != 1 || self.v != 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -343,14 +355,19 @@ fn parse(data: &[u8]) -> Result<Parsed<'_>> {
|
||||
return Err(RawError::malformed(format!("unsupported SOF3 ({precision}-bit, {width}x{height}, {nf} components)")));
|
||||
}
|
||||
comp_ids.clear();
|
||||
let mut factors = Vec::with_capacity(nf);
|
||||
for c in 0..nf {
|
||||
let s = &seg[6 + 3 * c..9 + 3 * c];
|
||||
if s[1] != 0x11 {
|
||||
return Err(RawError::unsupported("lossless JPEG with subsampled components"));
|
||||
}
|
||||
factors.push(s[1]);
|
||||
comp_ids.push(s[0]);
|
||||
}
|
||||
frame = Some(Frame { precision, width, height, components: nf });
|
||||
// Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, whole MCUs only.
|
||||
let (h, v) = match factors.as_slice() {
|
||||
f if f.iter().all(|&s| s == 0x11) => (1, 1),
|
||||
[y @ (0x21 | 0x22), 0x11, 0x11] if width % 2 == 0 && height % usize::from(y & 0x0F) == 0 => (2, usize::from(y & 0x0F)),
|
||||
_ => return Err(RawError::unsupported(format!("lossless JPEG with subsampled components {factors:02x?} ({width}x{height})"))),
|
||||
};
|
||||
frame = Some(Frame { precision, width, height, components: nf, h, v });
|
||||
}
|
||||
0xC0..=0xC2 => return Err(RawError::unsupported("lossy (DCT) JPEG compressed raw data")),
|
||||
0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF => return Err(RawError::unsupported("hierarchical or arithmetic-coded JPEG")),
|
||||
@@ -422,6 +439,9 @@ fn parse(data: &[u8]) -> Result<Parsed<'_>> {
|
||||
pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec<u16>)> {
|
||||
let p = parse(data)?;
|
||||
let f = p.frame;
|
||||
if f.is_subsampled() {
|
||||
return Err(RawError::unsupported(format!("lossless JPEG with subsampled components ({}x{} luma)", f.h, f.v)));
|
||||
}
|
||||
let total = f
|
||||
.samples()
|
||||
.filter(|&n| n <= max_samples)
|
||||
@@ -531,10 +551,100 @@ pub(crate) fn decode(data: &[u8], max_samples: usize) -> Result<(Frame, Vec<u16>
|
||||
Ok((f, out))
|
||||
}
|
||||
|
||||
/// Decodes a subsampled frame (Canon sRAW / mRAW: Y sampled 2×1 or 2×2, Cb and Cr 1×1, see
|
||||
/// [`Frame::h`]) into its sample sequence in decode order: per MCU the `h × v` Y samples
|
||||
/// row-major, then Cb, then Cr; `width / h` MCUs make a row and `height / v` rows the frame.
|
||||
///
|
||||
/// Only predictor 1 is supported, with Canon's rule instead of T.81's per-component sample
|
||||
/// grid: each Y sample is predicted from the Y sample decoded just before it (the previous one
|
||||
/// in the MCU, or the last of the previous MCU), Cb and Cr from those of the previous MCU, and
|
||||
/// the first MCU of a row from the first MCU of the row above (from `2^(P−Pt−1)` on the first
|
||||
/// row of a restart interval).
|
||||
pub(crate) fn decode_subsampled(data: &[u8], max_samples: usize) -> Result<(Frame, Vec<u16>)> {
|
||||
let p = parse(data)?;
|
||||
let f = p.frame;
|
||||
let total = f
|
||||
.samples()
|
||||
.filter(|&n| n <= max_samples)
|
||||
.ok_or_else(|| RawError::LimitExceeded(format!("lossless JPEG frame {}x{}x{}", f.width, f.height, f.components)))?;
|
||||
if !f.is_subsampled() || f.components != 3 {
|
||||
return Err(RawError::malformed("lossless JPEG frame is not subsampled YCbCr"));
|
||||
}
|
||||
if p.predictor != 1 {
|
||||
return Err(RawError::unsupported(format!("subsampled lossless JPEG with predictor {}", p.predictor)));
|
||||
}
|
||||
if p.entropy.len().saturating_mul(8) < total / 2 {
|
||||
return Err(RawError::malformed("lossless JPEG data is truncated"));
|
||||
}
|
||||
// Each component's table (components may share one).
|
||||
let [ty, tcb, tcr] = match p.comp_table.as_slice() {
|
||||
&[a, b, c] => [&p.tables[a], &p.tables[b], &p.tables[c]],
|
||||
_ => return Err(RawError::malformed("lossless JPEG scan tables")),
|
||||
};
|
||||
let luma = f.h * f.v;
|
||||
let per_mcu = luma + 2;
|
||||
let mcus = f.width / f.h;
|
||||
let row_len = mcus * per_mcu;
|
||||
if row_len == 0 {
|
||||
return Err(RawError::malformed("empty lossless JPEG frame"));
|
||||
}
|
||||
// The restart interval counts MCUs.
|
||||
if p.restart != 0 && p.restart % mcus != 0 {
|
||||
return Err(RawError::unsupported("lossless JPEG restart interval that is not whole rows"));
|
||||
}
|
||||
let rows_per_interval = if p.restart == 0 { usize::MAX } else { p.restart / mcus };
|
||||
let mut out = vec![0u16; total];
|
||||
let mut bits = Bits::new(p.entropy);
|
||||
let initial = 1i32 << (f.precision - p.point_transform - 1);
|
||||
// First Y, Cb and Cr of the row above: the first MCU's predictors.
|
||||
let mut top = [initial; 3];
|
||||
let mut interval_row = 0usize;
|
||||
for row in out.chunks_exact_mut(row_len) {
|
||||
if interval_row == rows_per_interval {
|
||||
bits.restart()?;
|
||||
interval_row = 0;
|
||||
}
|
||||
if interval_row == 0 {
|
||||
top = [initial; 3];
|
||||
}
|
||||
let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]);
|
||||
for (m, mcu) in row.chunks_exact_mut(per_mcu).enumerate() {
|
||||
let (ys, c) = mcu.split_at_mut(luma);
|
||||
for (k, s) in ys.iter_mut().enumerate() {
|
||||
// The first Y of the row comes from the row above, every other from the previous Y.
|
||||
let pred = if m == 0 && k == 0 { top[0] } else { y };
|
||||
*s = (pred + bits.diff(ty)?) as u16;
|
||||
y = i32::from(*s);
|
||||
if m == 0 && k == 0 {
|
||||
top[0] = y;
|
||||
}
|
||||
}
|
||||
if let [scb, scr] = c {
|
||||
*scb = (cb + bits.diff(tcb)?) as u16;
|
||||
*scr = (cr + bits.diff(tcr)?) as u16;
|
||||
(cb, cr) = (i32::from(*scb), i32::from(*scr));
|
||||
}
|
||||
if m == 0 {
|
||||
(top[1], top[2]) = (cb, cr);
|
||||
}
|
||||
}
|
||||
interval_row += 1;
|
||||
if bits.fake > 64 {
|
||||
return Err(RawError::malformed("lossless JPEG data is truncated"));
|
||||
}
|
||||
}
|
||||
if p.point_transform > 0 {
|
||||
for v in &mut out {
|
||||
*v <<= p.point_transform;
|
||||
}
|
||||
}
|
||||
Ok((f, out))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testgen::{lj92_encode, lj92_encode_tables};
|
||||
use crate::testgen::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables};
|
||||
|
||||
/// Deterministic pseudo-random samples with some structure (smooth + noise).
|
||||
fn samples(n: usize, precision: u8, seed: u64) -> Vec<u16> {
|
||||
@@ -559,7 +669,7 @@ mod tests {
|
||||
let v = samples(w * h * comps, precision, u64::from(predictor) * 31 + comps as u64);
|
||||
let j = lj92_encode(&v, w, h, comps, precision, predictor, None);
|
||||
let (f, out) = decode(&j, usize::MAX).unwrap();
|
||||
assert_eq!(f, Frame { precision, width: w, height: h, components: comps });
|
||||
assert_eq!(f, Frame { precision, width: w, height: h, components: comps, h: 1, v: 1 });
|
||||
assert_eq!(out, v, "P={precision} pred={predictor} comps={comps}");
|
||||
}
|
||||
}
|
||||
@@ -591,7 +701,7 @@ mod tests {
|
||||
let v = samples(w * h * comps, 14, u64::from(predictor) * 7 + comps as u64);
|
||||
let j = lj92_encode_tables(&v, w, h, table_of, 14, predictor, restart_rows);
|
||||
let (f, out) = decode(&j, usize::MAX).unwrap();
|
||||
assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps });
|
||||
assert_eq!(f, Frame { precision: 14, width: w, height: h, components: comps, h: 1, v: 1 });
|
||||
assert_eq!(out, v, "tables={table_of:?} pred={predictor} restart={restart_rows:?}");
|
||||
}
|
||||
}
|
||||
@@ -663,4 +773,67 @@ mod tests {
|
||||
flooded.extend_from_slice(&j[2..]); // the rest of the valid stream
|
||||
assert!(matches!(decode(&flooded, usize::MAX), Err(RawError::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subsampled_roundtrip() {
|
||||
for (h, v) in [(2usize, 2usize), (2, 1)] {
|
||||
let (w, ht) = (14, 6);
|
||||
let n = (w / h) * (ht / v) * (h * v + 2);
|
||||
for precision in [12u8, 15, 16] {
|
||||
for restart in [None, Some(1), Some(ht / v)] {
|
||||
let seq = samples(n, precision, h as u64 * 7 + v as u64);
|
||||
let j = lj92_encode_sraw(&seq, w, ht, h, v, precision, restart);
|
||||
let f = frame(&j).unwrap();
|
||||
assert_eq!((f.h, f.v, f.samples()), (h, v, Some(n)));
|
||||
let (_, out) = decode_subsampled(&j, usize::MAX).unwrap();
|
||||
assert_eq!(out, seq, "{h}x{v} P={precision} restart {restart:?}");
|
||||
// The plain decoder refuses subsampled frames instead of mislaying them.
|
||||
assert!(matches!(decode(&j, usize::MAX), Err(RawError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Extreme values exercise the 16-bit and 32768 difference categories.
|
||||
let seq: Vec<u16> = (0..7 * 3 * 6).map(|i| if (i / 5) % 2 == 0 { 0 } else { 65535 }).collect();
|
||||
let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 16, Some(1));
|
||||
assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq);
|
||||
// Y and the chroma on separate tables, or each its own: the scan maps every component
|
||||
// to its table even when components share one.
|
||||
for table_of in [[0, 1, 1], [0, 1, 2], [1, 0, 0]] {
|
||||
let seq = samples(7 * 3 * 6, 15, 5);
|
||||
let j = lj92_encode_sraw_tables(&seq, 14, 6, (2, 2), table_of, 15, Some(1));
|
||||
assert_eq!(decode_subsampled(&j, usize::MAX).unwrap().1, seq, "tables {table_of:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subsampled_hostile_streams_error_without_panicking() {
|
||||
let seq = samples(7 * 3 * 6, 15, 3);
|
||||
let j = lj92_encode_sraw(&seq, 14, 6, 2, 2, 15, Some(1));
|
||||
for n in 0..j.len() {
|
||||
let _ = decode_subsampled(&j[..n], usize::MAX);
|
||||
}
|
||||
let mut s = 0x0123_4567u64;
|
||||
for _ in 0..2000 {
|
||||
let mut b = j.clone();
|
||||
for _ in 0..4 {
|
||||
s = s.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
let at = (s >> 33) as usize % b.len();
|
||||
b[at] = (s >> 20) as u8;
|
||||
}
|
||||
let _ = decode_subsampled(&b, 1 << 20);
|
||||
}
|
||||
assert!(matches!(decode_subsampled(&j, 10), Err(RawError::LimitExceeded(_))));
|
||||
// A frame that is not subsampled, or another predictor, is not Canon sRAW.
|
||||
let plain = lj92_encode(&samples(14 * 6 * 3, 15, 1), 14, 6, 3, 15, 1, None);
|
||||
assert!(decode_subsampled(&plain, usize::MAX).is_err());
|
||||
let mut p6 = j.clone();
|
||||
let sos = p6.windows(2).position(|w| w == [0xFF, 0xDA]).unwrap();
|
||||
p6[sos + 11] = 6; // Ss (predictor) after Ns and three component selectors
|
||||
assert!(matches!(decode_subsampled(&p6, usize::MAX), Err(RawError::Unsupported(_))));
|
||||
// Sampling layouts other than Canon's are refused at the frame header.
|
||||
let mut odd = j.clone();
|
||||
let sof = odd.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap();
|
||||
odd[sof + 14] = 0x21; // Cb subsampled too
|
||||
assert!(matches!(frame(&odd), Err(RawError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Canon sRAW / mRAW (CR2 with subsampled YCbCr).
|
||||
//!
|
||||
//! The camera demosaics the sensor data and stores it as Y, Cb, Cr in one lossless JPEG frame
|
||||
//! whose Y component is sampled 2×2 (sRAW1, which Canon calls mRAW on the later bodies) or 2×1
|
||||
//! (sRAW2), sliced like the Bayer CR2 data (tag 0xC640, widths in samples). The decoder
|
||||
//! ([`crate::ljpeg::decode_subsampled`]) gives the sample sequence; [`planes`] lays it out,
|
||||
//! [`camera_rgb`] interpolates the chroma and converts to camera RGB, and the result is
|
||||
//! developed like a three-sample LinearRaw: no CFA, the as-shot white balance, the look fitted
|
||||
//! to the embedded JPEG (`photocraft-io`), tone and exposure as for every other raw.
|
||||
//!
|
||||
//! Observed on EOS 6D Mark II mRAW files (ColorData version 15, 4680 × 3132 data):
|
||||
//! * Y is already black-subtracted (the darkest samples are 0) and on the sensor's scale; Cb and
|
||||
//! Cr are colour differences offset by `2^(P−1)`.
|
||||
//! * The stored RGB is camera RGB divided by per-shot gains, an RGGB entry of ColorData (word
|
||||
//! 0x80 in version 15; its green is 1170, not the 1024 of the white-balance presets) that
|
||||
//! roughly neutralises the scene. Multiplying them back gives camera RGB that matches an
|
||||
//! independent converter's linear camera-RGB output of the same files to a diagonal of
|
||||
//! (1, 1, 1) ± 1.5 % and 0.6 % RMS; the as-shot white balance then applies as for Bayer data.
|
||||
//! * The inverse with the BT.601 luma weights (ITU-R BT.601: Y = 0.299 R + 0.587 G + 0.114 B)
|
||||
//! and unscaled differences (Cb = B − Y, Cr = R − Y) leaves no cross-channel terms above 3 %
|
||||
//! in that comparison.
|
||||
//! * Chroma edges follow the luma edges slightly better half an MCU in than at its first
|
||||
//! sample, so the chroma is treated as centred on its MCU and interpolated bilinearly.
|
||||
//!
|
||||
//! Approximate: the chroma siting and the bilinear interpolation (colour edges are softer than
|
||||
//! in a Bayer development; luma keeps full resolution). The gains are read only for ColorData
|
||||
//! versions where their offset was observed; for other bodies they are left at 1, which is a
|
||||
//! diagonal colour error that the matrix fitted to the camera's JPEG absorbs (a warning says
|
||||
//! so). Older bodies (sRAW before about 2009) are documented elsewhere to use other offsets
|
||||
//! and chroma scalings; no such sample was available, so they decode with the same rule.
|
||||
//! Shadow noise below black is clipped at 0 by the conversion.
|
||||
|
||||
use crate::error::{RawError, Result};
|
||||
use crate::ljpeg::Frame;
|
||||
use crate::par;
|
||||
|
||||
/// The de-sliced YCbCr planes: Y at full resolution, Cb and Cr one sample per MCU, stored
|
||||
/// values (chroma still carries its offset).
|
||||
pub(crate) struct Planes {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub h: usize,
|
||||
pub v: usize,
|
||||
pub y: Vec<u16>,
|
||||
pub cb: Vec<u16>,
|
||||
pub cr: Vec<u16>,
|
||||
}
|
||||
|
||||
/// Lays the decoded sample sequence out as planes. `slices` are the slice widths in samples
|
||||
/// (CR2 tag 0xC640; one slice of the whole MCU row when absent): slice 0 is filled MCU row by
|
||||
/// MCU row, then slice 1, and so on, as for the Bayer CR2 data.
|
||||
pub(crate) fn planes(f: &Frame, samples: &[u16], slices: &[usize]) -> Result<Planes> {
|
||||
let (h, v) = (f.h, f.v);
|
||||
let per_mcu = h * v + 2;
|
||||
let total: usize = slices.iter().sum();
|
||||
if total == 0 || !total.is_multiple_of(per_mcu) || slices.iter().any(|w| !w.is_multiple_of(per_mcu)) || !samples.len().is_multiple_of(total) {
|
||||
return Err(RawError::malformed("CR2 sRAW slices do not match the JPEG frame"));
|
||||
}
|
||||
let mcus = total / per_mcu;
|
||||
let rows = samples.len() / total;
|
||||
let (width, height) = (mcus * h, rows * v);
|
||||
let mut p = Planes { width, height, h, v, y: vec![0; width * height], cb: vec![0; mcus * rows], cr: vec![0; mcus * rows] };
|
||||
let mut runs = samples.chunks_exact(per_mcu);
|
||||
let mut x0 = 0usize;
|
||||
for &sw in slices {
|
||||
let n = sw / per_mcu;
|
||||
for r in 0..rows {
|
||||
for mx in x0..x0 + n {
|
||||
let mcu = runs.next().ok_or_else(|| RawError::malformed("CR2 sRAW slice data is short"))?;
|
||||
let (ys, c) = mcu.split_at(h * v);
|
||||
for (k, &s) in ys.iter().enumerate() {
|
||||
let (x, y) = (mx * h + k % h, r * v + k / h);
|
||||
if let Some(d) = p.y.get_mut(y * width + x) {
|
||||
*d = s;
|
||||
}
|
||||
}
|
||||
if let ([cb, cr], Some(dcb), Some(dcr)) = (c, p.cb.get_mut(r * mcus + mx), p.cr.get_mut(r * mcus + mx)) {
|
||||
(*dcb, *dcr) = (*cb, *cr);
|
||||
}
|
||||
}
|
||||
}
|
||||
x0 += n;
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
/// White level of unclipped frames: 14-bit full scale less Canon's usual black of about 2048.
|
||||
pub(crate) const FULL_SCALE: f32 = 14335.0;
|
||||
|
||||
/// BT.601 luma weights of R and B (G's is the rest).
|
||||
const KR: f32 = 0.299;
|
||||
const KB: f32 = 0.114;
|
||||
|
||||
/// Interpolates the chroma to every pixel and converts to camera RGB, interleaved:
|
||||
/// `R = Y + Cr`, `B = Y + Cb`, `G = (Y − KR·R − KB·B) / KG`, then each channel multiplied by the
|
||||
/// camera's sRAW `gains`. `offset` is the chroma's zero (`2^(P−1)`).
|
||||
pub(crate) fn camera_rgb(p: &Planes, offset: f32, gains: [f64; 3]) -> Vec<u16> {
|
||||
let (w, h) = (p.width, p.height);
|
||||
let cw = w / p.h.max(1);
|
||||
let ch = p.cb.len().checked_div(cw).unwrap_or(0);
|
||||
let mut out = vec![0u16; w * h * 3];
|
||||
if w == 0 || cw == 0 || ch == 0 {
|
||||
return out;
|
||||
}
|
||||
let gains = gains.map(|m| if m.is_finite() && m > 0.0 { m as f32 } else { 1.0 });
|
||||
let kg = 1.0 - KR - KB;
|
||||
// Chroma sample positions: centred on the MCU (see the module docs). Per output column (row):
|
||||
// the two chroma columns (rows) around it and the weight of the second.
|
||||
let taps = |n: usize, f: usize, len: usize| -> Vec<(usize, usize, f32)> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let c = ((i as f32 + 0.5) / f as f32 - 0.5).clamp(0.0, (len - 1) as f32);
|
||||
let a = (c as usize).min(len - 1);
|
||||
let b = (a + 1).min(len - 1);
|
||||
(a, b, c - a as f32)
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
let xs = taps(w, p.h.max(1), cw);
|
||||
let ys = taps(h, p.v.max(1), ch);
|
||||
let band = par::band_rows(w);
|
||||
par::chunks_mut(&mut out, band * w * 3, |b, chunk| {
|
||||
for (r, row) in chunk.chunks_exact_mut(w * 3).enumerate() {
|
||||
let y = b * band + r;
|
||||
let (Some(luma), Some(&(ya, yb, fy))) = (p.y.get(y * w..(y + 1) * w), ys.get(y)) else { continue };
|
||||
let chroma = |plane: &[u16], xa: usize, xb: usize, fx: f32| {
|
||||
let at = |cy: usize, cx: usize| plane.get(cy * cw + cx).map_or(offset, |&v| f32::from(v));
|
||||
let top = at(ya, xa) * (1.0 - fx) + at(ya, xb) * fx;
|
||||
let bottom = at(yb, xa) * (1.0 - fx) + at(yb, xb) * fx;
|
||||
top * (1.0 - fy) + bottom * fy - offset
|
||||
};
|
||||
for ((o, &l), &(xa, xb, fx)) in row.as_chunks_mut::<3>().0.iter_mut().zip(luma).zip(&xs) {
|
||||
let l = f32::from(l);
|
||||
let (cb, cr) = (chroma(&p.cb, xa, xb, fx), chroma(&p.cr, xa, xb, fx));
|
||||
let (red, blue) = (l + cr, l + cb);
|
||||
let green = (l - KR * red - KB * blue) / kg;
|
||||
for (k, v) in [red, green, blue].into_iter().enumerate() {
|
||||
o[k] = (v * gains[k]).round().clamp(0.0, 65535.0) as u16;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
out
|
||||
}
|
||||
|
||||
/// White level of channel `k` of interleaved RGB: the largest value when a meaningful share of
|
||||
/// samples piles up there (clipped highlights), else `full`.
|
||||
pub(crate) fn clip_level(rgb: &[u16], k: usize, full: f32) -> f32 {
|
||||
let step = 3 * (rgb.len() / 3 / 2_000_000).max(1);
|
||||
let samples = || rgb.iter().skip(k).step_by(step);
|
||||
let max = samples().copied().max().unwrap_or(0);
|
||||
if max == 0 {
|
||||
return full;
|
||||
}
|
||||
let near = samples().filter(|&&v| u32::from(v) + u32::from(max / 256) >= u32::from(max)).count();
|
||||
if near * 2000 >= samples().count() { f32::from(max) * 0.995 } else { full.max(f32::from(max)) }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::testgen::Cr2SrawSpec;
|
||||
use crate::{DevelopOptions, Limits, decode, develop_sensor};
|
||||
|
||||
const OFFSET: f32 = 16384.0;
|
||||
|
||||
/// A linear ramp of camera RGB (bilinear chroma interpolation reproduces it exactly away
|
||||
/// from the borders).
|
||||
fn camera(x: usize, y: usize) -> [f32; 3] {
|
||||
let (x, y) = (x as f32, y as f32);
|
||||
[1500.0 + 40.0 * x + 10.0 * y, 2500.0 + 15.0 * x + 30.0 * y, 1200.0 + 5.0 * x + 45.0 * y]
|
||||
}
|
||||
|
||||
/// The camera's stored YCbCr for `camera` divided by `gains`: Y per pixel, Cb / Cr at the
|
||||
/// centre of each MCU (the siting the decoder assumes).
|
||||
fn spec(h: usize, v: usize, gains: [f32; 3], slices: Vec<usize>, restart_rows: Option<usize>) -> Cr2SrawSpec {
|
||||
let (w, ht) = (48, 24);
|
||||
let stored = |x: f32, y: f32| {
|
||||
let c = camera(0, 0);
|
||||
let (dx, dy) = (camera(1, 0), camera(0, 1));
|
||||
[0, 1, 2].map(|k| (c[k] + (dx[k] - c[k]) * x + (dy[k] - c[k]) * y) / gains[k])
|
||||
};
|
||||
let ycc = |p: [f32; 3]| {
|
||||
let y = KR * p[0] + (1.0 - KR - KB) * p[1] + KB * p[2];
|
||||
(y, p[2] - y + OFFSET, p[0] - y + OFFSET)
|
||||
};
|
||||
let y = (0..w * ht).map(|i| ycc(stored((i % w) as f32, (i / w) as f32)).0.round() as u16).collect();
|
||||
let (mw, mh) = (w / h, ht / v);
|
||||
let centre = |m: usize, f: usize| (m * f) as f32 + (f as f32 - 1.0) / 2.0;
|
||||
let chroma: Vec<(f32, f32, f32)> = (0..mw * mh).map(|i| ycc(stored(centre(i % mw, h), centre(i / mw, v)))).collect();
|
||||
Cr2SrawSpec {
|
||||
width: w,
|
||||
height: ht,
|
||||
h,
|
||||
v,
|
||||
precision: 15,
|
||||
y,
|
||||
cb: chroma.iter().map(|c| c.1.round() as u16).collect(),
|
||||
cr: chroma.iter().map(|c| c.2.round() as u16).collect(),
|
||||
slices,
|
||||
restart_rows,
|
||||
wb_rggb: Some([2048, 1024, 1024, 1536]),
|
||||
gains: Some([(1170.0 * gains[0]) as u16, 1170, 1170, (1170.0 * gains[2]) as u16]),
|
||||
borders: Some([0, 2, 47, 23]),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sraw_decodes_to_camera_rgb() {
|
||||
let gains = [0.75, 1.0, 0.4];
|
||||
// sRAW1 (2×2: 6 samples an MCU) and sRAW2 (2×1: 4 samples an MCU), with and without
|
||||
// slices and restart intervals.
|
||||
for (h, v, slices, restart) in
|
||||
[(2, 2, vec![], None), (2, 2, vec![48, 48, 48], Some(3)), (2, 2, vec![60, 60, 24], None), (2, 1, vec![], Some(1)), (2, 1, vec![32, 32, 32], None)]
|
||||
{
|
||||
let s = spec(h, v, gains, slices.clone(), restart);
|
||||
let sensor = decode(&s.build(), &Limits::default()).expect("decode");
|
||||
assert_eq!((sensor.width, sensor.height, sensor.samples), (48, 24, 3), "{h}x{v} {slices:?}");
|
||||
assert!(sensor.cfa.is_none());
|
||||
assert_eq!(sensor.crop, crate::Rect::new(0, 2, 48, 22));
|
||||
assert_eq!(sensor.camera_wb, Some([2.0, 1.0, 1.5]));
|
||||
assert!(sensor.warnings.is_empty(), "{:?}", sensor.warnings);
|
||||
for y in 2..22 {
|
||||
for x in 2..46 {
|
||||
let at = (y * 48 + x) * 3;
|
||||
for (k, (&got, want)) in sensor.data[at..at + 3].iter().zip(camera(x, y)).enumerate() {
|
||||
let got = f32::from(got);
|
||||
// Rounding of Y, Cb, Cr and the stored gains (whole 1/1170 steps).
|
||||
assert!((got - want).abs() <= 4.0 + want * 0.002, "{h}x{v} {slices:?} ({x}, {y}) ch {k}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_gains_keep_the_stored_colour_and_say_so() {
|
||||
let mut s = spec(2, 2, [1.0; 3], vec![], None);
|
||||
s.gains = None;
|
||||
let sensor = decode(&s.build(), &Limits::default()).expect("decode");
|
||||
assert!(sensor.warnings.iter().any(|w| w.contains("sRAW colour gains")), "{:?}", sensor.warnings);
|
||||
let want = camera(10, 10);
|
||||
let got = &sensor.data[(10 * 48 + 10) * 3..(10 * 48 + 10) * 3 + 3];
|
||||
assert!(got.iter().zip(want).all(|(&g, w)| (f32::from(g) - w).abs() <= 4.0), "{got:?} vs {want:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sraw_develops_as_linear_rgb() {
|
||||
let s = spec(2, 1, [0.75, 1.0, 0.4], vec![], None);
|
||||
let sensor = decode(&s.build(), &Limits::default()).expect("decode");
|
||||
let d = develop_sensor(&sensor, &DevelopOptions::default()).expect("develop");
|
||||
assert_eq!((d.width, d.height), (48, 22));
|
||||
assert_eq!(d.info.cfa, None);
|
||||
assert_eq!(d.info.wb_multipliers, [2.0, 1.0, 1.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_sraw_errors_without_panicking() {
|
||||
let b = spec(2, 2, [0.75, 1.0, 0.4], vec![48, 48, 48], Some(2)).build();
|
||||
for n in (0..b.len()).step_by(7) {
|
||||
let _ = decode(&b[..n], &Limits::default());
|
||||
}
|
||||
let mut s = 0x9E37_79B9u64;
|
||||
for _ in 0..1500 {
|
||||
let mut c = b.clone();
|
||||
for _ in 0..3 {
|
||||
s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
|
||||
let at = (s >> 33) as usize % c.len();
|
||||
c[at] = (s >> 20) as u8;
|
||||
}
|
||||
if let Ok(sensor) = decode(&c, &Limits::default()) {
|
||||
let _ = develop_sensor(&sensor, &DevelopOptions::default());
|
||||
}
|
||||
}
|
||||
// Slices that do not split whole MCUs are refused.
|
||||
let mut bad = spec(2, 2, [1.0; 3], vec![48, 48, 48], None).build();
|
||||
let tag = bad.windows(4).position(|w| w == [0x40, 0xC6, 3, 0]).expect("slice tag");
|
||||
let at = u32::from_le_bytes([bad[tag + 8], bad[tag + 9], bad[tag + 10], bad[tag + 11]]) as usize;
|
||||
bad[at + 2..at + 4].copy_from_slice(&47u16.to_le_bytes());
|
||||
assert!(matches!(decode(&bad, &Limits::default()), Err(RawError::Malformed(_))));
|
||||
// The planes refuse a sample count that is not whole slice rows.
|
||||
let f = Frame { precision: 15, width: 4, height: 2, components: 3, h: 2, v: 2 };
|
||||
assert!(planes(&f, &[0; 11], &[12]).is_err());
|
||||
assert!(planes(&f, &[0; 12], &[0]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn white_level_follows_clipping() {
|
||||
// A lone bright sample is not clipping.
|
||||
let mut rgb: Vec<u16> = (0..3 * 10_000).map(|i| (i % 5000) as u16).collect();
|
||||
rgb[0] = 9000;
|
||||
assert_eq!(clip_level(&rgb, 0, 14335.0), 14335.0);
|
||||
for p in rgb.as_chunks_mut::<3>().0.iter_mut().take(100) {
|
||||
p[1] = 12000;
|
||||
}
|
||||
assert!((clip_level(&rgb, 1, 14335.0) - 12000.0 * 0.995).abs() < 1e-3);
|
||||
assert_eq!(clip_level(&[], 2, 14335.0), 14335.0);
|
||||
}
|
||||
|
||||
/// Real files: `PHOTOCRAFT_SRAW_CR2` lists CR2 paths (separated by `:`), e.g. EOS 6D Mark II
|
||||
/// mRAW. Checks the size, the gains and that the development runs.
|
||||
#[test]
|
||||
#[ignore = "needs real sRAW CR2 files in PHOTOCRAFT_SRAW_CR2"]
|
||||
fn real_sraw_files() {
|
||||
let paths = std::env::var("PHOTOCRAFT_SRAW_CR2").expect("PHOTOCRAFT_SRAW_CR2");
|
||||
for path in paths.split(':').filter(|p| !p.is_empty()) {
|
||||
let bytes = std::fs::read(path).expect("read");
|
||||
let s = decode(&bytes, &Limits::default()).expect("decode");
|
||||
assert_eq!(s.samples, 3, "{path}");
|
||||
assert!(s.cfa.is_none() && s.camera_wb.is_some(), "{path}");
|
||||
assert!(s.warnings.is_empty(), "{path}: {:?}", s.warnings);
|
||||
let d = develop_sensor(&s, &DevelopOptions::default()).expect("develop");
|
||||
eprintln!("{path}: {}x{} from {}x{}, white {:?}", d.width, d.height, s.width, s.height, s.white);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,9 +15,9 @@ mod raf;
|
||||
mod rw2;
|
||||
mod tiff;
|
||||
|
||||
pub use canon::{Cr2Spec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep};
|
||||
pub use canon::{Cr2Spec, Cr2SrawSpec, craw_block, craw_encode, nef_compressed, sony_craw, tiff_ep};
|
||||
pub use dng::{DngSpec, DngStorage, baseline_jpeg, gain_map_opcode_list, map_polynomial_opcode_list};
|
||||
pub use lj92::{lj92_encode, lj92_encode_tables};
|
||||
pub use lj92::{lj92_encode, lj92_encode_sraw, lj92_encode_sraw_tables, lj92_encode_tables};
|
||||
pub use orf::orf;
|
||||
pub use raf::{RafPacking, RafSpec, XTRANS, mosaic, mosaic_cfa, scene};
|
||||
pub use rw2::{rw2, rw2_format4, rw2_pack, rw2_v4_pack};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::lj92::lj92_encode;
|
||||
use super::lj92::{lj92_encode, lj92_encode_sraw};
|
||||
use super::tiff::{TiffBuilder, Val};
|
||||
|
||||
// ---------------------------------------------------------------- CR2
|
||||
@@ -94,6 +94,103 @@ impl Cr2Spec {
|
||||
}
|
||||
}
|
||||
|
||||
/// A synthetic Canon sRAW / mRAW CR2: Y, Cb and Cr planes in one subsampled lossless JPEG
|
||||
/// (see `ljpeg::decode_subsampled` and `sraw.rs`).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Cr2SrawSpec {
|
||||
/// Image size in pixels (multiples of `h` and `v`).
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
/// Y sampling factors: 2×2 (sRAW1 / mRAW) or 2×1 (sRAW2).
|
||||
pub h: usize,
|
||||
pub v: usize,
|
||||
pub precision: u8,
|
||||
/// `width * height` Y samples, row-major.
|
||||
pub y: Vec<u16>,
|
||||
/// One Cb and one Cr per MCU (`width / h` by `height / v`), offset by `2^(precision−1)`.
|
||||
pub cb: Vec<u16>,
|
||||
pub cr: Vec<u16>,
|
||||
/// Slice widths in samples (all but the last equal); empty = no slice tag.
|
||||
pub slices: Vec<usize>,
|
||||
/// Restart interval in MCU rows.
|
||||
pub restart_rows: Option<usize>,
|
||||
/// As-shot RGGB levels at ColorData word 0x3F.
|
||||
pub wb_rggb: Option<[u16; 4]>,
|
||||
/// sRAW gains (RGGB) at ColorData word 0x80; ColorData version 15 is written either way.
|
||||
pub gains: Option<[u16; 4]>,
|
||||
/// Image borders: left, top, right, bottom (inclusive), as in SensorInfo.
|
||||
pub borders: Option<[u16; 4]>,
|
||||
}
|
||||
|
||||
impl Cr2SrawSpec {
|
||||
pub fn build(&self) -> Vec<u8> {
|
||||
let (h, v) = (self.h, self.v);
|
||||
let per_mcu = h * v + 2;
|
||||
let (mcus, rows) = (self.width / h, self.height / v);
|
||||
let widths: Vec<usize> = if self.slices.is_empty() { vec![mcus * per_mcu] } else { self.slices.clone() };
|
||||
assert_eq!(widths.iter().sum::<usize>(), mcus * per_mcu);
|
||||
// Slice the MCUs into the JPEG sample order.
|
||||
let mut seq = Vec::with_capacity(mcus * rows * per_mcu);
|
||||
let mut m0 = 0;
|
||||
for &sw in &widths {
|
||||
assert_eq!(sw % per_mcu, 0);
|
||||
let n = sw / per_mcu;
|
||||
for r in 0..rows {
|
||||
for mx in m0..m0 + n {
|
||||
for k in 0..h * v {
|
||||
seq.push(self.y[(r * v + k / h) * self.width + mx * h + k % h]);
|
||||
}
|
||||
seq.push(self.cb[r * mcus + mx]);
|
||||
seq.push(self.cr[r * mcus + mx]);
|
||||
}
|
||||
}
|
||||
m0 += n;
|
||||
}
|
||||
let jpeg = lj92_encode_sraw(&seq, self.width, self.height, h, v, self.precision, self.restart_rows);
|
||||
let mut t = TiffBuilder::default();
|
||||
let jb = t.blob(jpeg.clone());
|
||||
let mut raw = vec![
|
||||
(256, Val::Short(vec![self.width as u16])),
|
||||
(257, Val::Short(vec![self.height as u16])),
|
||||
(259, Val::Short(vec![6])),
|
||||
(273, Val::Blobs(vec![jb])),
|
||||
(279, Val::Long(vec![jpeg.len() as u32])),
|
||||
];
|
||||
if !self.slices.is_empty() {
|
||||
let n = widths.len() - 1;
|
||||
raw.push((50752, Val::Short(vec![n as u16, widths[0] as u16, widths[n] as u16])));
|
||||
}
|
||||
let raw_ifd = t.ifd(raw);
|
||||
let mut mn: Vec<(u16, Val)> = Vec::new();
|
||||
if let Some([l, tp, r, b]) = self.borders {
|
||||
mn.push((0x00E0, Val::Short(vec![34, self.width as u16, self.height as u16, 0, 0, l, tp, r, b, 0, 0, 0, 0, 0, 0, 0, 0])));
|
||||
}
|
||||
let mut cd = vec![0u8; 2 * 1602];
|
||||
cd[0..2].copy_from_slice(&15u16.to_le_bytes());
|
||||
for (at, levels) in [(0x3F, self.wb_rggb), (0x80, self.gains)] {
|
||||
for (i, v) in levels.iter().flatten().enumerate() {
|
||||
cd[2 * (at + i)..2 * (at + i) + 2].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
mn.push((0x4001, Val::Undefined(cd)));
|
||||
let mi = t.ifd(mn);
|
||||
let exif_ifd = t.ifd(vec![(33434, Val::Rational(vec![(1, 100)])), (37500, Val::IfdBytes(mi))]);
|
||||
let ifd0 = t.ifd(vec![
|
||||
(256, Val::Long(vec![2])),
|
||||
(257, Val::Long(vec![2])),
|
||||
(271, Val::Ascii("Canon".into())),
|
||||
(272, Val::Ascii("Canon EOS Synthetic".into())),
|
||||
(274, Val::Short(vec![1])),
|
||||
(34665, Val::Ifds(vec![exif_ifd])),
|
||||
]);
|
||||
let ifd1 = t.ifd(vec![(256, Val::Long(vec![1]))]);
|
||||
let ifd2 = t.ifd(vec![(256, Val::Long(vec![1]))]);
|
||||
t.chain = vec![ifd0, ifd1, ifd2, raw_ifd];
|
||||
t.cr2_raw_ifd = Some(raw_ifd);
|
||||
t.build()
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- TIFF/EP
|
||||
|
||||
/// A synthetic uncompressed TIFF/EP raw (NEF / ARW-like): IFD0 with Make, the
|
||||
|
||||
+121
-19
@@ -56,7 +56,6 @@ pub fn lj92_encode(samples: &[u16], width: usize, height: usize, components: usi
|
||||
pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of: &[u8], precision: u8, predictor: u8, restart_rows: Option<usize>) -> Vec<u8> {
|
||||
let components = table_of.len();
|
||||
assert_eq!(samples.len(), width * height * components);
|
||||
assert!(table_of.iter().all(|&t| t < 4));
|
||||
let row = width * components;
|
||||
let interval = restart_rows.unwrap_or(usize::MAX);
|
||||
// Differences per sample, following T.81 H.1.2.1 prediction rules.
|
||||
@@ -85,16 +84,118 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of
|
||||
_ => (ra + rb) >> 1,
|
||||
}
|
||||
};
|
||||
let mut d = (i32::from(samples[i]) - px) & 0xFFFF;
|
||||
if d > 32768 {
|
||||
d -= 65536;
|
||||
}
|
||||
diffs.push(d);
|
||||
diffs.push(wrap_diff(i32::from(samples[i]) - px));
|
||||
}
|
||||
}
|
||||
}
|
||||
let frame = Frame {
|
||||
width,
|
||||
height,
|
||||
factors: &vec![0x11; components],
|
||||
table_of,
|
||||
pattern: &(0..components as u8).collect::<Vec<_>>(),
|
||||
precision,
|
||||
predictor,
|
||||
restart: restart_rows.map(|r| (r * width, interval.saturating_mul(row))),
|
||||
};
|
||||
lj92_stream(&diffs, &frame)
|
||||
}
|
||||
|
||||
/// A difference modulo 2^16, in −32767..=32768 (T.81 H.1.2.2).
|
||||
fn wrap_diff(d: i32) -> i32 {
|
||||
let d = d & 0xFFFF;
|
||||
if d > 32768 { d - 65536 } else { d }
|
||||
}
|
||||
|
||||
/// Encodes a Canon sRAW / mRAW frame: `seq` is the sample sequence in decode order (per MCU the
|
||||
/// `h × v` Y samples, then Cb and Cr; `width / h` MCUs a row), predicted as
|
||||
/// `ljpeg::decode_subsampled` describes: each Y from the previous Y, Cb and Cr from the previous
|
||||
/// MCU's, the first MCU of a row from the first of the row above. `restart_rows` counts MCU rows.
|
||||
pub fn lj92_encode_sraw(seq: &[u16], width: usize, height: usize, h: usize, v: usize, precision: u8, restart_rows: Option<usize>) -> Vec<u8> {
|
||||
lj92_encode_sraw_tables(seq, width, height, (h, v), [0, 0, 0], precision, restart_rows)
|
||||
}
|
||||
|
||||
/// Like [`lj92_encode_sraw`], but Y, Cb and Cr use Huffman tables `table_of` (0–3).
|
||||
pub fn lj92_encode_sraw_tables(
|
||||
seq: &[u16],
|
||||
width: usize,
|
||||
height: usize,
|
||||
(h, v): (usize, usize),
|
||||
table_of: [u8; 3],
|
||||
precision: u8,
|
||||
restart_rows: Option<usize>,
|
||||
) -> Vec<u8> {
|
||||
let (luma, mcus) = (h * v, width / h);
|
||||
let per_mcu = luma + 2;
|
||||
let row_len = mcus * per_mcu;
|
||||
assert_eq!(seq.len(), row_len * (height / v));
|
||||
let interval = restart_rows.unwrap_or(usize::MAX);
|
||||
let initial = 1i32 << (precision - 1);
|
||||
let mut diffs = Vec::with_capacity(seq.len());
|
||||
let mut top = [initial; 3];
|
||||
for (r, row) in seq.chunks_exact(row_len).enumerate() {
|
||||
if r % interval == 0 {
|
||||
top = [initial; 3];
|
||||
}
|
||||
let (mut y, mut cb, mut cr) = (top[0], top[1], top[2]);
|
||||
for (m, mcu) in row.chunks_exact(per_mcu).enumerate() {
|
||||
for (k, &s) in mcu[..luma].iter().enumerate() {
|
||||
let pred = if m == 0 && k == 0 { top[0] } else { y };
|
||||
diffs.push(wrap_diff(i32::from(s) - pred));
|
||||
y = i32::from(s);
|
||||
if m == 0 && k == 0 {
|
||||
top[0] = y;
|
||||
}
|
||||
}
|
||||
diffs.push(wrap_diff(i32::from(mcu[luma]) - cb));
|
||||
diffs.push(wrap_diff(i32::from(mcu[luma + 1]) - cr));
|
||||
(cb, cr) = (i32::from(mcu[luma]), i32::from(mcu[luma + 1]));
|
||||
if m == 0 {
|
||||
(top[1], top[2]) = (cb, cr);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut pattern = vec![0u8; luma];
|
||||
pattern.extend_from_slice(&[1, 2]);
|
||||
let frame = Frame {
|
||||
width,
|
||||
height,
|
||||
factors: &[(h as u8) << 4 | v as u8, 0x11, 0x11],
|
||||
table_of: &table_of,
|
||||
pattern: &pattern,
|
||||
precision,
|
||||
predictor: 1,
|
||||
restart: restart_rows.map(|r| (r * mcus, interval.saturating_mul(row_len))),
|
||||
};
|
||||
lj92_stream(&diffs, &frame)
|
||||
}
|
||||
|
||||
/// The frame header [`lj92_stream`] writes around the differences.
|
||||
struct Frame<'a> {
|
||||
width: usize,
|
||||
height: usize,
|
||||
/// Each component's sampling factors (`h << 4 | v`).
|
||||
factors: &'a [u8],
|
||||
/// Each component's Huffman table id (0–3).
|
||||
table_of: &'a [u8],
|
||||
/// The component of each difference, repeating: `0, 1, 2` interleaved, or an MCU's Y samples
|
||||
/// then Cb and Cr.
|
||||
pattern: &'a [u8],
|
||||
precision: u8,
|
||||
predictor: u8,
|
||||
/// The restart interval `(DRI value, differences per interval)`.
|
||||
restart: Option<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// Writes SOI, SOF3, one DHT per table id, the restart interval, SOS and the entropy-coded
|
||||
/// `diffs`.
|
||||
fn lj92_stream(diffs: &[i32], f: &Frame<'_>) -> Vec<u8> {
|
||||
let components = f.factors.len();
|
||||
assert_eq!(f.table_of.len(), components);
|
||||
assert!(f.table_of.iter().all(|&t| t < 4));
|
||||
let table = |i: usize| f.table_of[usize::from(f.pattern[i % f.pattern.len()])];
|
||||
// Tables: categories ordered by frequency get increasing code lengths.
|
||||
let mut ids: Vec<u8> = table_of.to_vec();
|
||||
let mut ids: Vec<u8> = f.table_of.to_vec();
|
||||
ids.sort_unstable();
|
||||
ids.dedup();
|
||||
let mut code_of = [[(0u32, 0u32); 17]; 4];
|
||||
@@ -102,7 +203,7 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of
|
||||
for &t in &ids {
|
||||
let mut freq = [0usize; 17];
|
||||
for (i, &d) in diffs.iter().enumerate() {
|
||||
if table_of[i % components] == t {
|
||||
if table(i) == t {
|
||||
freq[category(d) as usize] += 1;
|
||||
}
|
||||
}
|
||||
@@ -133,12 +234,12 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of
|
||||
// SOF3
|
||||
out.extend_from_slice(&[0xFF, 0xC3]);
|
||||
out.extend_from_slice(&((8 + 3 * components) as u16).to_be_bytes());
|
||||
out.push(precision);
|
||||
out.extend_from_slice(&(height as u16).to_be_bytes());
|
||||
out.extend_from_slice(&(width as u16).to_be_bytes());
|
||||
out.push(f.precision);
|
||||
out.extend_from_slice(&(f.height as u16).to_be_bytes());
|
||||
out.extend_from_slice(&(f.width as u16).to_be_bytes());
|
||||
out.push(components as u8);
|
||||
for c in 0..components {
|
||||
out.extend_from_slice(&[c as u8 + 1, 0x11, 0]);
|
||||
for (c, &factor) in f.factors.iter().enumerate() {
|
||||
out.extend_from_slice(&[c as u8 + 1, factor, 0]);
|
||||
}
|
||||
// DHT, one per table id
|
||||
for (t, counts, vals) in &dhts {
|
||||
@@ -148,28 +249,29 @@ pub fn lj92_encode_tables(samples: &[u16], width: usize, height: usize, table_of
|
||||
out.extend_from_slice(counts);
|
||||
out.extend_from_slice(vals);
|
||||
}
|
||||
if let Some(r) = restart_rows {
|
||||
if let Some((dri, _)) = f.restart {
|
||||
out.extend_from_slice(&[0xFF, 0xDD, 0, 4]);
|
||||
out.extend_from_slice(&((r * width) as u16).to_be_bytes());
|
||||
out.extend_from_slice(&(dri as u16).to_be_bytes());
|
||||
}
|
||||
let every = f.restart.map_or(usize::MAX, |(_, n)| n);
|
||||
// SOS
|
||||
out.extend_from_slice(&[0xFF, 0xDA]);
|
||||
out.extend_from_slice(&((6 + 2 * components) as u16).to_be_bytes());
|
||||
out.push(components as u8);
|
||||
for (c, &t) in table_of.iter().enumerate() {
|
||||
for (c, &t) in f.table_of.iter().enumerate() {
|
||||
out.extend_from_slice(&[c as u8 + 1, t << 4]);
|
||||
}
|
||||
out.extend_from_slice(&[predictor, 0, 0]);
|
||||
out.extend_from_slice(&[f.predictor, 0, 0]);
|
||||
let mut w = BitWriter { out, acc: 0, n: 0 };
|
||||
let mut rst = 0u8;
|
||||
for (i, &d) in diffs.iter().enumerate() {
|
||||
if i > 0 && i % (interval.saturating_mul(row)) == 0 {
|
||||
if i > 0 && i % every == 0 {
|
||||
w.flush();
|
||||
w.out.extend_from_slice(&[0xFF, 0xD0 + rst]);
|
||||
rst = (rst + 1) % 8;
|
||||
}
|
||||
let s = category(d);
|
||||
let (c, l) = code_of[usize::from(table_of[i % components])][s as usize];
|
||||
let (c, l) = code_of[usize::from(table(i))][s as usize];
|
||||
w.put(c, l);
|
||||
if (1..16).contains(&s) {
|
||||
let extra = if d < 0 { (d - 1) as u32 & ((1 << s) - 1) } else { d as u32 };
|
||||
|
||||
@@ -56,7 +56,8 @@ fn cr2_develops() {
|
||||
|
||||
#[test]
|
||||
fn cr2_srgb_raw_is_unsupported() {
|
||||
// A subsampled (sRAW-style) frame: patch the first component's sampling factors.
|
||||
// A subsampled frame in a layout Canon sRAW does not use (two components, Y 2×1): patch the
|
||||
// first component's sampling factors. Real sRAW / mRAW decodes (see `sraw.rs`).
|
||||
let mut b = cr2_spec(32, 8, 2, vec![]).build();
|
||||
let sof = b.windows(2).position(|w| w == [0xFF, 0xC3]).unwrap();
|
||||
b[sof + 11] = 0x21;
|
||||
|
||||
@@ -127,6 +127,7 @@ impl PhotocraftApp {
|
||||
color_range: None,
|
||||
adjust_preview: None,
|
||||
live_adjust_preview: None,
|
||||
levels_clipping: None,
|
||||
synthetic: Vec::new(),
|
||||
synthetic_batch: None,
|
||||
synthetic_reinject: false,
|
||||
|
||||
@@ -378,6 +378,10 @@ impl PhotocraftApp {
|
||||
let docs = self.session.documents();
|
||||
self.channel_views.retain(|id, _| docs.iter().any(|d| d.doc.id.0 == *id));
|
||||
}
|
||||
// With no document left, no canvas paints the Levels clipping display to drop its cache.
|
||||
if self.session.documents().is_empty() {
|
||||
self.levels_clipping = None;
|
||||
}
|
||||
// Commands may close and reopen a preserved-ID document before the next repaint.
|
||||
canvas::retain_gpu_documents(self);
|
||||
}
|
||||
|
||||
@@ -111,11 +111,12 @@ use tabs::{dots, paint_dots};
|
||||
use tabs::{main_canvas_document, move_target_after_filter};
|
||||
#[cfg(test)]
|
||||
pub(crate) use textures::detail_plan;
|
||||
pub(crate) use textures::visible_doc_rect;
|
||||
pub(crate) use textures::{DetailPlan, damage_since, effect_reach, ensure_texture_in_view, retain_gpu_documents, shown_as_document};
|
||||
pub use textures::{MAX_TEXTURE, ensure_texture};
|
||||
#[cfg(test)]
|
||||
use textures::{clamp_texture_side, preview_bounds, texture_factor};
|
||||
use textures::{ensure_gpu, redraw_focus, visible_doc_rect};
|
||||
use textures::{ensure_gpu, redraw_focus};
|
||||
pub use tool_input::{ToolEvent, selection_drag_kind, tool_event};
|
||||
pub(crate) use tool_input::{command_guide_at, command_moves_layer, event_tool};
|
||||
pub(crate) use transform_controls::ControlsPress;
|
||||
@@ -525,6 +526,11 @@ fn paint_canvas(
|
||||
painter.image(tex, xf.doc_rect(a), uv, Color32::WHITE);
|
||||
}
|
||||
}
|
||||
// Image › Adjustments › Levels: Alt-drag on the black / white Input slider (levels_clipping.rs).
|
||||
// The main canvas only: the display keeps one cache, sized to that view.
|
||||
if primary {
|
||||
crate::levels_clipping::paint(app, ctx, painter, &xf, idx);
|
||||
}
|
||||
crate::color_range_ui::paint_selection_preview(app, ctx, painter, doc.id, img_rect, flip);
|
||||
// Artboards: pasteboard between the boards, outlines and names (artboard_ui.rs).
|
||||
if doc.has_artboards() {
|
||||
|
||||
@@ -203,16 +203,53 @@ pub(super) fn alt_eyedropper(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui:
|
||||
true
|
||||
}
|
||||
|
||||
/// Sample the image or targeted raster mask at (x, y) using the configured Sample Size.
|
||||
/// Write a valid sample to the foreground swatch, or to the background swatch with Alt.
|
||||
pub(super) fn sample_eyedropper(app: &mut PhotocraftApp, x: f64, y: f64, mods: egui::Modifiers) {
|
||||
if let Some(mut rgb) = eyedropper_color(app, x, y) {
|
||||
if super::paint_target(app) != json!("pixels") {
|
||||
rgb = [photocraft_color::convert::rgb_to_gray(rgb); 3];
|
||||
}
|
||||
let rgb = if let Some((surface, canvas)) = eyedropper_mask_source(app) {
|
||||
sample_layer_mask(surface, canvas, x, y, app.ui.tool_options.eyedropper_size)
|
||||
} else {
|
||||
eyedropper_color(app, x, y).map(|rgb| if super::paint_target(app) == json!("pixels") { rgb } else { [photocraft_color::convert::rgb_to_gray(rgb); 3] })
|
||||
};
|
||||
if let Some(rgb) = rgb {
|
||||
let key = if mods.alt { "background" } else { "foreground" };
|
||||
let _ = app.run("tools.setColors", json!({ key: [rgb[0],rgb[1],rgb[2],1.0] }));
|
||||
}
|
||||
}
|
||||
|
||||
/// Only the Eyedropper's Current Layer and Current & Below modes pick the targeted raster mask.
|
||||
fn eyedropper_mask_source(app: &PhotocraftApp) -> Option<(&photocraft_raster::Surface, photocraft_geom::Rect)> {
|
||||
use photocraft_engine::{channel_cmds::ChannelTarget, mask_view_cmds};
|
||||
|
||||
if app.active_tool() != Tool::Eyedropper
|
||||
|| app.ui.vector_mask_target
|
||||
|| !matches!(app.ui.tool_options.eyedropper_sample.as_str(), "current" | "currentAndBelow")
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let st = app.session.active()?;
|
||||
// Painting can implicitly edit an adjustment's mask even with its content thumbnail selected.
|
||||
let targeted = app.ui.mask_target || st.channel_view.target == ChannelTarget::LayerMask || mask_view_cmds::current(st).is_some_and(|v| !v.filter);
|
||||
if !targeted || st.doc.quick_mask.is_some() || !app.layer_mask_targeted() {
|
||||
return None;
|
||||
}
|
||||
let mask = st.doc.layer(st.active_layer?)?.mask.as_ref()?;
|
||||
Some((&mask.surface, st.doc.bounds()))
|
||||
}
|
||||
|
||||
/// Read the stored mask channel, including its sparse default, rather than its composited coverage.
|
||||
fn sample_layer_mask(surface: &photocraft_raster::Surface, canvas: photocraft_geom::Rect, x: f64, y: f64, size: u32) -> Option<[f32; 3]> {
|
||||
let rect = photocraft_engine::cmd::sample_cmds::sample_rect(x, y, size, canvas)?;
|
||||
let mut sum = 0.0;
|
||||
for y in rect.y0..rect.y1 {
|
||||
for x in rect.x0..rect.x1 {
|
||||
sum += f64::from(surface.sample_channel(x, y, 0));
|
||||
}
|
||||
}
|
||||
let gray = (sum / (f64::from(rect.width()) * f64::from(rect.height()))) as f32;
|
||||
gray.is_finite().then_some([gray; 3])
|
||||
}
|
||||
|
||||
/// The colour at document point (x, y) with the Eyedropper's Sample Size (the composite pixel,
|
||||
/// or the average of the square around it) from the layers `sample_layer` names (`document.sampleColor`).
|
||||
/// `None` off the image or over transparency.
|
||||
@@ -248,3 +285,7 @@ pub(crate) fn alt_loads_mixer(tool: Tool, mods: egui::Modifiers) -> bool {
|
||||
pub(crate) fn alt_picks(tool: Tool, mods: egui::Modifiers) -> bool {
|
||||
alt_samples(tool, mods) || alt_loads_mixer(tool, mods)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../eyedropper_mask_sample_tests.rs"]
|
||||
mod eyedropper_mask_sample_tests;
|
||||
@@ -637,7 +637,7 @@ fn budget_allowance(app: &PhotocraftApp) -> (u64, u64) {
|
||||
|
||||
/// The document pixels a view shows, with a margin for filtering. Uses all four canvas corners
|
||||
/// so a rotated camera still covers the visible tiles.
|
||||
pub(super) fn visible_doc_rect(xf: &ViewXform) -> DRect {
|
||||
pub(crate) fn visible_doc_rect(xf: &ViewXform) -> DRect {
|
||||
let r = xf.rect;
|
||||
let docs = [xf.to_doc(r.min), xf.to_doc(pos2(r.max.x, r.min.y)), xf.to_doc(r.max), xf.to_doc(pos2(r.min.x, r.max.y))];
|
||||
let mut x0 = docs[0][0];
|
||||
|
||||
@@ -277,6 +277,19 @@ pub(crate) fn close_box(ui: &mut egui::Ui, rect: egui::Rect) -> bool {
|
||||
/// it. Returns `Some(true)` / `Some(false)` when the body itself answered OK / Cancel.
|
||||
/// The body of a command dialog: the first handler whose marker the fields carry. The prompts and
|
||||
/// small editors come first; the rest are in `command_body_more`.
|
||||
/// The delete confirmations: a layer from the Layers panel's trash, or a note (#11788).
|
||||
fn delete_prompt(fields: &Fields) -> bool {
|
||||
crate::delete_layer_prompt::owns(fields) || crate::analysis_ui::owns_delete_note(fields)
|
||||
}
|
||||
|
||||
fn delete_prompt_body(ui: &mut egui::Ui, fields: &mut Fields) {
|
||||
if crate::analysis_ui::owns_delete_note(fields) {
|
||||
crate::analysis_ui::delete_note_body(ui, fields);
|
||||
} else {
|
||||
crate::delete_layer_prompt::body(ui, fields);
|
||||
}
|
||||
}
|
||||
|
||||
fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields: &mut Fields, id: egui::Id, interactive: bool) -> Option<bool> {
|
||||
let mut outcome: Option<bool> = None;
|
||||
match d.kind {
|
||||
@@ -292,7 +305,7 @@ fn command_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, d: &Dialog, fields:
|
||||
_ if crate::channel_options_ui::owns(fields) => crate::channel_options_ui::body(ui, fields),
|
||||
_ if crate::channel_options_ui::owns_new_spot(fields) => crate::channel_options_ui::new_spot_body(ui, fields),
|
||||
_ if crate::shape_dialog::owns(fields) => crate::shape_dialog::body(app, ui, fields),
|
||||
_ if crate::delete_layer_prompt::owns(fields) => crate::delete_layer_prompt::body(ui, fields),
|
||||
_ if delete_prompt(fields) => delete_prompt_body(ui, fields),
|
||||
_ if crate::disk_change_prompt::owns(fields) => crate::disk_change_prompt::body(ui, fields),
|
||||
_ if crate::replace_prompt::owns(fields) => crate::replace_prompt::body(ui, fields),
|
||||
_ if crate::preset_group_prompt::owns(fields) => crate::preset_group_prompt::body(ui, fields),
|
||||
@@ -464,6 +477,8 @@ fn button_row(
|
||||
tl!("Reset")
|
||||
} else if d.kind == DialogKind::NewDocument {
|
||||
tl!("Close")
|
||||
} else if crate::analysis_ui::owns_delete_note(fields) {
|
||||
tl!("No")
|
||||
} else {
|
||||
tl!("Cancel")
|
||||
};
|
||||
@@ -533,6 +548,8 @@ fn ok_label(d: &Dialog) -> &'static str {
|
||||
tl!("Continue")
|
||||
} else if crate::delete_layer_prompt::owns(&d.fields) {
|
||||
tl!("Delete")
|
||||
} else if crate::analysis_ui::owns_delete_note(&d.fields) {
|
||||
tl!("Yes")
|
||||
} else if crate::disk_change_prompt::owns(&d.fields) || crate::replace_prompt::owns(&d.fields) {
|
||||
tl!("Replace")
|
||||
} else if d.fields.contains_key("__export") {
|
||||
@@ -864,6 +881,7 @@ const ROUTES: &[fn(&Fields) -> bool] = &[
|
||||
merge_channels_ui::owns,
|
||||
crate::shape_dialog::owns,
|
||||
crate::delete_layer_prompt::owns,
|
||||
crate::analysis_ui::owns_delete_note,
|
||||
crate::disk_change_prompt::owns,
|
||||
crate::actions::owns_stop_message,
|
||||
crate::actions::owns_insert_stop,
|
||||
@@ -917,6 +935,24 @@ fn file_command(fields: &Fields) -> Option<&'static str> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Batch and the other folder runs (Image Processor, …) go on past a file that fails and list it
|
||||
/// in their result's `errors`; the status bar and a notice say which files failed and why, so a run
|
||||
/// that fails on every file isn't silent (#10682). Each file is named by its whole path: files of
|
||||
/// the same name in different subfolders are told apart.
|
||||
fn report_file_errors(app: &mut PhotocraftApp, d: &Dialog, r: &Value) {
|
||||
let Some(errors) = r.get("errors").and_then(Value::as_array).filter(|e| !e.is_empty()) else { return };
|
||||
let lines: Vec<String> = errors
|
||||
.iter()
|
||||
.map(|e| {
|
||||
let file = e.get("file").and_then(Value::as_str).unwrap_or_default();
|
||||
format!("{file}: {}", e.get("error").and_then(Value::as_str).unwrap_or_default())
|
||||
})
|
||||
.collect();
|
||||
let label = d.fields.get("__label").and_then(Value::as_str).unwrap_or("Command");
|
||||
let what = crate::i18n::t(label).trim_end_matches('…').to_string();
|
||||
crate::notices::file_failures(app, &what, &lines);
|
||||
}
|
||||
|
||||
/// Confirm a command dialog no specific handler owns: run its `__command` with the dialog's
|
||||
/// parameters, then settle the filter preview and the playing action.
|
||||
fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, String> {
|
||||
@@ -951,6 +987,9 @@ fn confirm_generic_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value,
|
||||
}
|
||||
};
|
||||
let result = crate::actions::run_step_dialog(app, &d.fields, &cmd, params.clone());
|
||||
if let Ok(r) = &result {
|
||||
report_file_errors(app, &d, r);
|
||||
}
|
||||
// A filter that runs as a background job keeps its preview on screen until the job
|
||||
// lands (`canvas::committed_filter_preview`) instead of flashing the unfiltered image.
|
||||
let running =
|
||||
@@ -1059,6 +1098,7 @@ fn confirm_command(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, String>
|
||||
fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result<Value, String> {
|
||||
match d.kind {
|
||||
_ if merge_channels_ui::owns(&d.fields) => merge_channels_ui::confirm(app, &d.fields),
|
||||
_ if crate::analysis_ui::owns_delete_note(&d.fields) => crate::analysis_ui::confirm_delete_note(app, &d.fields),
|
||||
_ if crate::file_ui::owns(&d.fields) => crate::file_ui::confirm(app, &d.fields),
|
||||
_ if crate::new_guide_ui::owns(&d.fields) => crate::new_guide_ui::confirm(app, &d.fields),
|
||||
_ if crate::color_picker_ui::owns(&d.fields) => {
|
||||
|
||||
@@ -504,6 +504,7 @@ pub fn body(app: &mut PhotocraftApp, ui: &mut egui::Ui, fields: &mut Map<String,
|
||||
fields.insert(CURVE_PICKER_BASE.into(), base);
|
||||
}
|
||||
}
|
||||
crate::levels_clipping::sync(ui.ctx(), dialog_mem(&kind), fields);
|
||||
let mut preview = fields.get("__preview").and_then(Value::as_bool).unwrap_or(true);
|
||||
ui.add_space(6.0);
|
||||
if crate::widgets::checkbox(ui, &mut preview, tl!("Preview")).changed() {
|
||||
|
||||
@@ -48,6 +48,7 @@ use hue_saturation::hue_saturation;
|
||||
#[cfg(test)]
|
||||
use hue_saturation::{lightness_track, move_hue_range_handle, saturation_track};
|
||||
use levels::levels;
|
||||
pub(crate) use levels::levels_drag;
|
||||
pub use levels::{auto_levels, gamma_from_pos, gamma_pos};
|
||||
use selective_color::selective_color;
|
||||
pub use session::{layer_editor, layer_mem, properties_coalesce, properties_reset, session_start};
|
||||
|
||||
@@ -60,6 +60,16 @@ pub(super) fn nearest(xs: &[f32], x: f32) -> Option<u8> {
|
||||
xs.iter().enumerate().min_by(|a, b| (a.1 - x).abs().total_cmp(&(b.1 - x).abs())).map(|(i, _)| i as u8)
|
||||
}
|
||||
|
||||
fn levels_drag_id(mem: egui::Id) -> egui::Id {
|
||||
mem.with("levels-drag")
|
||||
}
|
||||
|
||||
/// The Levels Input slider handle being dragged in the editor rooted at `mem` (0 black, 1 gamma,
|
||||
/// 2 white), as of its last frame.
|
||||
pub(crate) fn levels_drag(ctx: &egui::Context, mem: egui::Id) -> Option<u8> {
|
||||
ctx.data(|d| d.get_temp::<Option<u8>>(levels_drag_id(mem))).flatten()
|
||||
}
|
||||
|
||||
pub(super) fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let channels = editor_channels(cx, space_of(v));
|
||||
@@ -98,7 +108,9 @@ pub(super) fn levels(ui: &mut egui::Ui, v: &mut Value, cx: &EditorCx) -> Edit {
|
||||
let track = sr.shrink2(vec2(6.0, 0.0));
|
||||
let xpos = |val: f32| track.left() + val / 255.0 * track.width();
|
||||
let xval = |x: f32| ((x - track.left()) / track.width() * 255.0).clamp(0.0, 255.0);
|
||||
let drag_id = cx.mem.with("levels-drag");
|
||||
// Where 0 and 255 sit (tests press the handles there).
|
||||
ui.data_mut(|d| d.insert_temp(cx.mem.with("levels-slider"), track));
|
||||
let drag_id = levels_drag_id(cx.mem);
|
||||
let mut which: Option<u8> = ui.data(|d| d.get_temp(drag_id)).flatten();
|
||||
let ctx = ui.ctx().clone();
|
||||
let pressed = |r: &egui::Response| r.is_pointer_button_down_on() && ctx.input(|i| i.pointer.primary_pressed());
|
||||
|
||||
@@ -194,6 +194,19 @@ fn dialog(app: &PhotocraftApp) -> Option<(String, Value, bool)> {
|
||||
Some((kind, crate::filter_dialog::params_of(&d.fields), preview))
|
||||
}
|
||||
|
||||
/// Whether Image › Adjustments `kind` on document `idx` would edit a channel (the Channels panel's
|
||||
/// target or the Quick Mask) or the active layer's mask instead of the layer's pixels.
|
||||
pub(crate) fn targets_channel(app: &PhotocraftApp, idx: usize, kind: &str, params: &Value) -> bool {
|
||||
// The dialog's own target choice, when it has one, decides.
|
||||
if let Some(target) = params.get("target") {
|
||||
return target.as_str() != Some("pixels");
|
||||
}
|
||||
let Some(st) = app.session.documents().get(idx) else { return false };
|
||||
st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite
|
||||
|| st.doc.quick_mask.is_some()
|
||||
|| !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null()
|
||||
}
|
||||
|
||||
/// FNV-1a over `parts`, never 0.
|
||||
fn hash(parts: &[&[u8]]) -> u64 {
|
||||
parts.iter().flat_map(|p| p.iter()).fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x0100_0000_01b3)) | 1
|
||||
@@ -225,13 +238,7 @@ fn update(app: &mut PhotocraftApp, idx: usize) -> Option<&AdjustPreview> {
|
||||
let (doc_id, revision, target) = (st.doc.id, st.revision, st.active_layer?);
|
||||
// Commands that target a channel (Channels panel / Quick Mask) or a layer mask keep the proxy
|
||||
// preview.
|
||||
let channel_target = if let Some(target) = params.get("target") {
|
||||
target.as_str() != Some("pixels")
|
||||
} else {
|
||||
st.channel_view.target != photocraft_engine::channel_cmds::ChannelTarget::Composite
|
||||
|| st.doc.quick_mask.is_some()
|
||||
|| !app.with_mask_target(&format!("image.adjustments.{kind}"), Value::Null).is_null()
|
||||
};
|
||||
let channel_target = targets_channel(app, idx, &kind, ¶ms);
|
||||
let session = hash(&[&doc_id.0.to_le_bytes(), &revision.to_le_bytes(), &target.0.to_le_bytes(), &[u8::from(channel_target)]]);
|
||||
let h = hash(&[kind.as_bytes(), params.to_string().as_bytes(), &[u8::from(preview)]]);
|
||||
if let Some(p) = &app.adjust_preview
|
||||
|
||||
@@ -268,6 +268,12 @@ pub struct LiquifyDialog {
|
||||
pub preview_ms: f64,
|
||||
/// The smart filter being edited: OK updates it instead of adding a new Liquify filter.
|
||||
smart_filter: Option<usize>,
|
||||
/// Preview (P): off, the image is drawn unwarped while strokes still change the field, as
|
||||
/// Photoshop's Preview checkbox does (#7905). Every opening starts with it on.
|
||||
pub preview: bool,
|
||||
/// The undisplaced field drawn while Preview is off. It is as large as `field`, so it exists
|
||||
/// only while Preview is off: made when Preview is turned off, freed when it's turned back on.
|
||||
identity: Option<LiquifyField>,
|
||||
}
|
||||
|
||||
fn union(a: Option<[usize; 4]>, b: [usize; 4]) -> Option<[usize; 4]> {
|
||||
@@ -300,6 +306,7 @@ impl LiquifyDialog {
|
||||
"strokes": self.strokes.len() + usize::from(self.cur.is_some()),
|
||||
"redo": self.redo.len(),
|
||||
"meshSize": self.cell,
|
||||
"preview": self.preview,
|
||||
"maxDisplacement": self.field.max_displacement(),
|
||||
"proxy": [self.proxy.w, self.proxy.h],
|
||||
"dabMs": self.dab_ms,
|
||||
@@ -441,16 +448,29 @@ impl LiquifyDialog {
|
||||
/// Re-renders the dirty proxy pixels into `out` (the texture upload happens in `show`).
|
||||
fn render_dirty(&mut self) {
|
||||
if let Some(r) = self.dirty {
|
||||
let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field);
|
||||
if let Some(source) = &self.native_proxy {
|
||||
let bounds = Rect::new(0, 0, self.proxy.w as i32, self.proxy.h as i32);
|
||||
let dirty = Rect::new(r[0] as i32, r[1] as i32, r[2] as i32, r[3] as i32);
|
||||
render_components(source, bounds, &self.field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out);
|
||||
render_components(source, bounds, field, self.proxy.scale, &self.target, bounds, dirty, &mut self.out);
|
||||
} else {
|
||||
self.proxy.render(&self.field, r, &mut self.out);
|
||||
self.proxy.render(field, r, &mut self.out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns Preview on or off: the whole preview is redrawn with, or without, the warp.
|
||||
pub fn set_preview(&mut self, on: bool) {
|
||||
if on == self.preview {
|
||||
return;
|
||||
}
|
||||
self.identity = (!on).then(|| LiquifyField::new(self.canvas, self.cell));
|
||||
self.preview = on;
|
||||
self.dirty = Some([0, 0, self.proxy.w, self.proxy.h]);
|
||||
self.render_dirty();
|
||||
self.view_dirty = self.view_bounds;
|
||||
}
|
||||
|
||||
/// Builds or updates the visible source-resolution viewport. At ordinary zoom the whole-layer
|
||||
/// proxy remains cheaper; above 100%, a full-resolution crop is enough to fill the preview.
|
||||
fn update_view_preview(&mut self, ctx: &egui::Context, area: ERect) {
|
||||
@@ -497,10 +517,11 @@ impl LiquifyDialog {
|
||||
return;
|
||||
}
|
||||
let started = crate::gpu_canvas::now_ms();
|
||||
let field = self.identity.as_ref().filter(|_| !self.preview).unwrap_or(&self.field);
|
||||
let rendered = if self.native_proxy.is_some() {
|
||||
render_components(&self.source, self.canvas, &self.field, 1.0, &self.target, bounds, dirty, &mut self.view_out)
|
||||
render_components(&self.source, self.canvas, field, 1.0, &self.target, bounds, dirty, &mut self.view_out)
|
||||
} else {
|
||||
ProxyImage::render_full_resolution(&self.source, &self.field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch)
|
||||
ProxyImage::render_full_resolution(&self.source, field, bounds, dirty, &mut self.view_out, &mut self.view_source_scratch)
|
||||
};
|
||||
if !rendered {
|
||||
self.view_bounds = None;
|
||||
@@ -654,6 +675,8 @@ fn open_on(
|
||||
dab_ms: 0.0,
|
||||
preview_ms: 0.0,
|
||||
smart_filter,
|
||||
preview: true,
|
||||
identity: None,
|
||||
};
|
||||
// A sensible starting brush (about a tenth of the image), then the settings last used, so
|
||||
// Liquify opens as it was left (#418). Saved values are clamped; a bad one is skipped.
|
||||
@@ -728,6 +751,9 @@ pub fn control(app: &mut PhotocraftApp, ui: &Value) -> Result<Value, String> {
|
||||
applied?;
|
||||
let num = |k: &str| ui.get(k).and_then(Value::as_f64).map(|v| v as f32);
|
||||
let flag = |k: &str| ui.get(k).and_then(Value::as_bool);
|
||||
if let Some(on) = flag("preview") {
|
||||
d.set_preview(on);
|
||||
}
|
||||
if flag("undo") == Some(true) {
|
||||
d.undo();
|
||||
}
|
||||
@@ -847,6 +873,11 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
_ => 1.0,
|
||||
};
|
||||
}
|
||||
// P toggles Preview, as in Photoshop (#7905).
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::P)) {
|
||||
let on = !d.preview;
|
||||
d.set_preview(on);
|
||||
}
|
||||
// Ctrl+H (Hide Extras) toggles the red freeze-mask overlay; the mask itself stays active.
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) {
|
||||
d.opts.show_mask = !d.opts.show_mask;
|
||||
@@ -1086,7 +1117,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
let right = ERect::from_min_size(pos2(body.right() - RIGHT_W, body.top()), vec2(RIGHT_W, body.height()));
|
||||
painter.rect_filled(right, 0.0, t.dock);
|
||||
painter.line_segment([right.left_top(), right.left_bottom()], Stroke::new(1.0, t.separator));
|
||||
let mut props = ui.new_child(egui::UiBuilder::new().max_rect(right.shrink2(vec2(14.0, 12.0))));
|
||||
// The properties scroll above the Preview row and the buttons.
|
||||
let props_rect = ERect::from_min_max(right.min + vec2(14.0, 12.0), pos2(right.right() - 14.0, (right.bottom() - 84.0).max(right.top() + 12.0)));
|
||||
let mut props = ui.new_child(egui::UiBuilder::new().max_rect(props_rect));
|
||||
egui::ScrollArea::vertical().id_salt("liquify-props").show(&mut props, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = 6.0;
|
||||
widgets::section_label(ui, tl!("Brush Tool Options"));
|
||||
@@ -1161,6 +1194,15 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
.size(11.0),
|
||||
);
|
||||
});
|
||||
// Preview, centred above OK and Cancel as in Photoshop (#7905).
|
||||
let label_w = ui.fonts_mut(|f| f.layout_no_wrap(tl!("Preview").to_owned(), egui::TextStyle::Body.resolve(ui.style()), t.text).size().x);
|
||||
let row_w = (label_w + 30.0).min(RIGHT_W - 28.0);
|
||||
let preview_row = ERect::from_center_size(pos2(right.center().x, right.bottom() - 64.0), vec2(row_w, 24.0));
|
||||
let mut pr = ui.new_child(egui::UiBuilder::new().max_rect(preview_row).layout(egui::Layout::left_to_right(egui::Align::Center)));
|
||||
let mut preview = d.preview;
|
||||
if widgets::checkbox(&mut pr, &mut preview, tl!("Preview")).changed() {
|
||||
d.set_preview(preview);
|
||||
}
|
||||
// Footer buttons.
|
||||
let foot = ERect::from_min_size(pos2(right.left() + 14.0, right.bottom() - 48.0), vec2(RIGHT_W - 28.0, 32.0));
|
||||
let mut fb = ui.new_child(egui::UiBuilder::new().max_rect(foot).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
|
||||
@@ -1024,3 +1024,131 @@ fn workspaces_open_on_a_smart_object_with_its_filter_mask_targeted() {
|
||||
let Some(photocraft_doc::LayerContent::Smart(sm)) = st.doc.layer(layer).map(|l| &l.content) else { panic!("not a smart object") };
|
||||
assert_eq!(sm.smart_filters.iter().map(|f| f.command.as_str()).collect::<Vec<_>>(), ["filter.blur.gaussianBlur", photocraft_engine::distort_cmds::LIQUIFY]);
|
||||
}
|
||||
|
||||
/// Preview off shows the image unwarped while strokes still change the field, and P turns it back
|
||||
/// on, as Photoshop's Liquify Preview checkbox does (#7905). Each opening starts with it on.
|
||||
#[test]
|
||||
fn preview_off_shows_the_original_and_p_toggles_it() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app_with_layer();
|
||||
open(&mut app, &ctx).unwrap();
|
||||
let render = |d: &LiquifyDialog, field: &LiquifyField| {
|
||||
let mut out = vec![[0u8; 4]; d.proxy.w * d.proxy.h];
|
||||
d.proxy.render(field, [0, 0, d.proxy.w, d.proxy.h], &mut out);
|
||||
out
|
||||
};
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert!(d.preview && d.describe()["preview"] == json!(true), "Liquify opens with Preview on");
|
||||
let original = render(d, &LiquifyField::new(d.canvas, d.cell));
|
||||
let stroke = |app: &mut PhotocraftApp, y: f64| {
|
||||
for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] {
|
||||
pointer(app, ev, egui::Modifiers::NONE);
|
||||
}
|
||||
};
|
||||
control(&mut app, &json!({"tool": "forwardWarp", "size": 40})).unwrap();
|
||||
stroke(&mut app, 40.0);
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert_ne!(d.out, original, "the warp shows");
|
||||
|
||||
let r = control(&mut app, &json!({"preview": false})).unwrap();
|
||||
assert_eq!(r["preview"], json!(false));
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert_eq!(d.out, original, "Preview off: the image as it was");
|
||||
// A stroke with Preview off still warps the field, unseen.
|
||||
stroke(&mut app, 30.0);
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert_eq!(d.strokes.len(), 2);
|
||||
assert_eq!(d.out, original, "still unwarped while Preview is off");
|
||||
{
|
||||
let d = app.distort.liquify.as_mut().unwrap();
|
||||
d.zoom = 2.0;
|
||||
d.view_bounds = Some(Rect::new(0, 0, 20, 20));
|
||||
d.view_dirty = None;
|
||||
}
|
||||
|
||||
// P turns it back on, with both strokes.
|
||||
let mut input = egui::RawInput::default();
|
||||
input.events.push(egui::Event::Key { key: egui::Key::P, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE });
|
||||
ctx.begin_pass(input);
|
||||
keys(&mut app, &ctx);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert!(d.preview);
|
||||
assert_eq!(d.out, render(d, &d.field), "Preview on: the warp of both strokes");
|
||||
assert_eq!(d.view_dirty, d.view_bounds, "the zoomed preview is redrawn too");
|
||||
}
|
||||
|
||||
/// A forward-warp stroke across the test layer, at row `y`.
|
||||
fn warp_stroke(app: &mut PhotocraftApp, y: f64) {
|
||||
for ev in [ToolEvent::Down { x: 35.0, y, pressure: 1.0 }, ToolEvent::Move { x: 60.0, y, pressure: 1.0 }, ToolEvent::Up { x: 60.0, y }] {
|
||||
pointer(app, ev, egui::Modifiers::NONE);
|
||||
}
|
||||
}
|
||||
|
||||
/// The active layer's pixels over the whole document.
|
||||
fn layer_pixels(app: &PhotocraftApp) -> Vec<f32> {
|
||||
let st = app.session.active().unwrap();
|
||||
st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap().read_region(Rect::new(0, 0, 120, 80))
|
||||
}
|
||||
|
||||
/// With Preview off, a stroke changes the displacement field but the display stays the original
|
||||
/// image (#7905).
|
||||
#[test]
|
||||
fn a_stroke_with_preview_off_changes_the_field_but_not_the_display() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app_with_layer();
|
||||
open(&mut app, &ctx).unwrap();
|
||||
control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": false})).unwrap();
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
let (field_before, shown_before) = (d.field.clone(), d.out.clone());
|
||||
assert_eq!(d.field.max_displacement(), 0.0);
|
||||
warp_stroke(&mut app, 40.0);
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert_ne!(d.field, field_before, "the stroke changes the field");
|
||||
assert!(d.field.max_displacement() > 3.0);
|
||||
assert_eq!(d.out, shown_before, "the display does not change");
|
||||
}
|
||||
|
||||
/// OK with Preview off applies the warp: the layer ends up exactly as it does when the same stroke
|
||||
/// is committed with Preview on.
|
||||
#[test]
|
||||
fn ok_with_preview_off_applies_the_warp() {
|
||||
let ctx = egui::Context::default();
|
||||
let commit_with = |preview: bool| {
|
||||
let mut app = app_with_layer();
|
||||
let before = layer_pixels(&app);
|
||||
open(&mut app, &ctx).unwrap();
|
||||
control(&mut app, &json!({"tool": "forwardWarp", "size": 40, "preview": preview})).unwrap();
|
||||
warp_stroke(&mut app, 40.0);
|
||||
let past = app.session.active().unwrap().history.past_len();
|
||||
control(&mut app, &json!({"commit": true})).unwrap();
|
||||
assert!(app.distort.liquify.is_none());
|
||||
assert_eq!(app.session.active().unwrap().history.past_len(), past + 1, "one Liquify step");
|
||||
(before, layer_pixels(&app))
|
||||
};
|
||||
let (before, unpreviewed) = commit_with(false);
|
||||
assert_ne!(unpreviewed, before, "OK with Preview off warps the layer");
|
||||
assert_eq!(unpreviewed, commit_with(true).1, "the same warp as with Preview on");
|
||||
}
|
||||
|
||||
/// The identity field (as large as the image's field) exists only while Preview is off: turning
|
||||
/// Preview back on frees it, and closing the dialog drops it.
|
||||
#[test]
|
||||
fn the_identity_field_exists_only_while_preview_is_off() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = app_with_layer();
|
||||
open(&mut app, &ctx).unwrap();
|
||||
let identity = |app: &PhotocraftApp| app.distort.liquify.as_ref().unwrap().identity.is_some();
|
||||
assert!(!identity(&app), "not made while Preview is on");
|
||||
control(&mut app, &json!({"preview": false})).unwrap();
|
||||
assert!(identity(&app));
|
||||
control(&mut app, &json!({"preview": true})).unwrap();
|
||||
assert!(!identity(&app), "freed when Preview is turned back on");
|
||||
control(&mut app, &json!({"preview": false})).unwrap();
|
||||
assert!(identity(&app), "made again when Preview is turned off again");
|
||||
control(&mut app, &json!({"cancel": true})).unwrap();
|
||||
assert!(app.distort.liquify.is_none(), "closing drops the dialog and its identity field");
|
||||
open(&mut app, &ctx).unwrap();
|
||||
let d = app.distort.liquify.as_ref().unwrap();
|
||||
assert!(d.preview && d.identity.is_none(), "a new opening starts with Preview on and no identity field");
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
use egui::Modifiers;
|
||||
use photocraft_geom::Rect;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::canvas::{ToolEvent, tool_event};
|
||||
use crate::state::Tool;
|
||||
use crate::{PhotocraftApp, Services};
|
||||
|
||||
const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
|
||||
|
||||
/// Select the Eyedropper and target a fully revealed mask on a red pixel layer or an Invert adjustment above it.
|
||||
fn app_with_mask(adjustment: bool) -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default());
|
||||
app.run("file.new", json!({"width": 8, "height": 8, "background": "transparent"})).unwrap();
|
||||
app.session
|
||||
.edit("Paint red", |doc, _| {
|
||||
let surface = doc.layers[0].surface_mut().unwrap();
|
||||
surface.fill_rect(Rect::new(0, 0, 8, 8), &photocraft_raster::from_rgba(&surface.format(), RED));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let add = if adjustment { "layer.newAdjustmentLayer.invert" } else { "layer.layerMask.revealAll" };
|
||||
app.run(add, json!({})).unwrap();
|
||||
assert!(app.ui.mask_target);
|
||||
app.ui.tool = Tool::Eyedropper;
|
||||
app
|
||||
}
|
||||
|
||||
fn paint_mask(app: &mut PhotocraftApp, rect: Rect, gray: f32) {
|
||||
let layer = app.session.active().unwrap().active_layer.unwrap();
|
||||
app.session
|
||||
.edit("Paint mask", |doc, _| {
|
||||
doc.layer_mut(layer).unwrap().mask.as_mut().unwrap().surface.fill_rect(rect, &[gray]);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn click(app: &mut PhotocraftApp, x: f64, y: f64, mods: Modifiers) {
|
||||
tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, mods);
|
||||
tool_event(app, ToolEvent::Up { x, y }, mods);
|
||||
}
|
||||
|
||||
fn gray(value: f32) -> [f32; 4] {
|
||||
[value, value, value, 1.0]
|
||||
}
|
||||
|
||||
/// Both measured modes pick white and mid-grey from the selected mask on either layer kind.
|
||||
#[test]
|
||||
fn targeted_pixel_and_adjustment_masks_supply_point_samples() {
|
||||
for adjustment in [false, true] {
|
||||
let mut app = app_with_mask(adjustment);
|
||||
paint_mask(&mut app, Rect::new(2, 2, 3, 3), 0.5);
|
||||
for mode in ["current", "currentAndBelow"] {
|
||||
app.ui.tool_options.eyedropper_sample = mode.into();
|
||||
app.run("tools.setColors", json!({"foreground": "#222222"})).unwrap();
|
||||
click(&mut app, 1.5, 1.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, gray(1.0), "adjustment={adjustment} {mode}");
|
||||
click(&mut app, 2.5, 2.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, gray(128.0 / 255.0), "adjustment={adjustment} {mode}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The average at the corner counts only four in-canvas mask pixels and Alt writes background.
|
||||
#[test]
|
||||
fn mask_average_clips_at_canvas_edge_and_alt_sets_background() {
|
||||
let mut app = app_with_mask(false);
|
||||
paint_mask(&mut app, Rect::new(0, 0, 1, 2), 0.0);
|
||||
app.ui.tool_options.eyedropper_sample = "currentAndBelow".into();
|
||||
app.ui.tool_options.eyedropper_size = 3;
|
||||
app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap();
|
||||
let foreground = app.session.tools.foreground;
|
||||
click(&mut app, 0.5, 0.5, Modifiers::ALT);
|
||||
assert_eq!(app.session.tools.background, gray(0.5));
|
||||
assert_eq!(app.session.tools.foreground, foreground);
|
||||
}
|
||||
|
||||
/// Composite modes use the image, and selecting contents restores the same sampling as before.
|
||||
#[test]
|
||||
fn composite_modes_and_pixel_targets_still_sample_the_image() {
|
||||
let mut app = app_with_mask(true);
|
||||
for mode in ["all", "allNoAdjustments", "currentAndBelowNoAdjustments"] {
|
||||
app.ui.tool_options.eyedropper_sample = mode.into();
|
||||
let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": mode})).unwrap();
|
||||
let [r, g, b, _]: [f32; 4] = serde_json::from_value(sample).unwrap();
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, gray(photocraft_color::convert::rgb_to_gray([r, g, b])), "{mode}");
|
||||
}
|
||||
// An adjustment's content thumbnail can still route painting to its mask. That is not an
|
||||
// explicit Eyedropper target.
|
||||
app.run("channel.target.composite", json!({})).unwrap();
|
||||
assert!(!app.ui.mask_target);
|
||||
app.ui.tool_options.eyedropper_sample = "current".into();
|
||||
let before = app.session.tools.foreground;
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, before, "the adjustment alone has no image pixels");
|
||||
|
||||
let mut app = app_with_mask(false);
|
||||
app.run("channel.target.composite", json!({})).unwrap();
|
||||
for mode in ["current", "currentAndBelow"] {
|
||||
app.ui.tool_options.eyedropper_sample = mode.into();
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, RED, "{mode}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A white raster mask beside another selected target cannot take over that target's sample.
|
||||
#[test]
|
||||
fn vector_alpha_quick_mask_and_temporary_samples_keep_their_source() {
|
||||
let red_gray = gray(photocraft_color::convert::rgb_to_gray([1.0, 0.0, 0.0]));
|
||||
let mut app = app_with_mask(false);
|
||||
app.ui.tool_options.eyedropper_sample = "current".into();
|
||||
app.ui.tool = Tool::Brush;
|
||||
click(&mut app, 4.5, 4.5, Modifiers::ALT);
|
||||
assert_eq!(app.session.tools.foreground, red_gray, "the brush's Alt-click still samples the image");
|
||||
|
||||
app.ui.tool = Tool::Eyedropper;
|
||||
app.run("layer.vectorMask.revealAll", json!({})).unwrap();
|
||||
assert!(app.ui.vector_mask_target);
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, RED, "a vector target does not pick the raster mask");
|
||||
|
||||
app.run("channel.new", json!({"name": "Alpha"})).unwrap();
|
||||
app.run("channel.target", json!({"channel": {"alpha": 0}})).unwrap();
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, red_gray, "an alpha target does not pick the raster mask");
|
||||
|
||||
app.run("channel.target.layerMask", json!({})).unwrap();
|
||||
app.run("select.editInQuickMaskMode", json!({"on": true})).unwrap();
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, red_gray, "Quick Mask does not pick the raster mask");
|
||||
}
|
||||
|
||||
/// A smart filter's mask keeps its image-based sample even when the same layer has a raster mask.
|
||||
#[test]
|
||||
fn filter_mask_target_keeps_the_image_based_sample() {
|
||||
let mut app = app_with_mask(false);
|
||||
app.background_jobs = false;
|
||||
app.run("channel.target.composite", json!({})).unwrap();
|
||||
app.run("layer.smartObjects.convertToSmartObject", json!({})).unwrap();
|
||||
app.run("filter.blur.gaussianBlur", json!({"radius": 1})).unwrap();
|
||||
app.run("layer.layerMask.revealAll", json!({})).unwrap();
|
||||
let layer = app.session.active().unwrap().active_layer.unwrap();
|
||||
assert!(app.session.active().unwrap().doc.layer(layer).unwrap().mask.is_some());
|
||||
app.select_filter_mask_target(Some(layer.0));
|
||||
assert!(app.filter_mask_targeted());
|
||||
app.ui.tool_options.eyedropper_sample = "current".into();
|
||||
let sample = app.run("document.sampleColor", json!({"x": 4.5, "y": 4.5, "sampleLayer": "current"})).unwrap();
|
||||
let [r, g, b, a]: [f32; 4] = serde_json::from_value(sample).unwrap();
|
||||
let want = gray(photocraft_color::convert::rgb_to_gray([r, g, b]));
|
||||
assert!(a > 0.0 && want != gray(1.0), "the image and layer mask are distinct");
|
||||
click(&mut app, 4.5, 4.5, Modifiers::NONE);
|
||||
assert_eq!(app.session.tools.foreground, want);
|
||||
}
|
||||
|
||||
/// Out-of-canvas points and invalid sample options leave both swatches intact.
|
||||
#[test]
|
||||
fn invalid_mask_samples_leave_both_swatches_unchanged() {
|
||||
let mut app = app_with_mask(false);
|
||||
app.ui.tool_options.eyedropper_sample = "current".into();
|
||||
app.run("tools.setColors", json!({"foreground": [0.2, 0.2, 0.2, 1.0], "background": [0.8, 0.8, 0.8, 1.0]})).unwrap();
|
||||
let before = (app.session.tools.foreground, app.session.tools.background);
|
||||
let assert_unchanged = |app: &PhotocraftApp| assert_eq!((app.session.tools.foreground, app.session.tools.background), before);
|
||||
for (x, y) in [(-0.1, 1.0), (1.0, 8.0), (f64::NAN, 1.0), (1.0, f64::INFINITY)] {
|
||||
for mods in [Modifiers::NONE, Modifiers::ALT] {
|
||||
click(&mut app, x, y, mods);
|
||||
assert_unchanged(&app);
|
||||
}
|
||||
}
|
||||
app.ui.tool_options.eyedropper_size = 2;
|
||||
click(&mut app, 1.0, 1.0, Modifiers::NONE);
|
||||
assert_unchanged(&app);
|
||||
app.ui.tool_options.eyedropper_size = 1;
|
||||
app.ui.tool_options.eyedropper_sample = "invalid".into();
|
||||
click(&mut app, 1.0, 1.0, Modifiers::ALT);
|
||||
assert_unchanged(&app);
|
||||
}
|
||||
@@ -745,6 +745,10 @@ fn handle_object_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool
|
||||
if crate::slice_ui::keys(app, ctx) {
|
||||
return true;
|
||||
}
|
||||
// A note selected with the Note tool: ⌫/Delete asks to delete the note, not the layer (#11788).
|
||||
if crate::analysis_ui::note_keys(app, ctx) {
|
||||
return true;
|
||||
}
|
||||
// A selected smart filter row: ⌫/Delete removes the filter, not its smart object (#4751).
|
||||
crate::smart_ui::keys(app, ctx)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,405 @@
|
||||
//! Photoshop's Levels clipping display (#3328). While Alt is held and the black or white Input
|
||||
//! slider of the Image › Adjustments › Levels dialog is dragged, the canvas shows what the input
|
||||
//! levels clip instead of the preview:
|
||||
//! - black slider: the image turns white; a channel the input levels clip to black drops to 0, so
|
||||
//! pixels clipped in every channel are black and pixels clipped in red alone are cyan;
|
||||
//! - white slider: the image turns black; a channel clipped to white rises to 255, so red alone is
|
||||
//! red and all three are white.
|
||||
//!
|
||||
//! Releasing Alt or the mouse shows the preview again; the document is never touched. Grayscale
|
||||
//! documents show black and white only. CMYK and Lab documents, and commands that edit a channel,
|
||||
//! a layer mask or a non-pixel layer, keep the normal preview.
|
||||
//!
|
||||
//! The display is an opaque texture over the visible part of the image, at about the screen's
|
||||
//! resolution: one texel per block of `factor`×`factor` document pixels. A block shows a channel
|
||||
//! clipped when any pixel in it is, so a lone clipped highlight stays visible zoomed out. Clipping
|
||||
//! is a threshold on each channel's sample (the input stretch is monotone), so the target's
|
||||
//! per-block minimum and maximum are scanned once per view and a slider move only compares them
|
||||
//! with the new thresholds.
|
||||
//!
|
||||
//! State is the dialog field `__clipping` (`"shadows"` / `"highlights"`): [`sync`] sets it when an
|
||||
//! Alt-drag starts and clears it when the drag ends, and automation can set it with
|
||||
//! `ui.dialog.set`. OK never sees it (`filter_dialog::params_of` drops `__` keys).
|
||||
|
||||
use egui::{Color32, Mesh, TextureOptions, pos2};
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_compose::adjust::{levels_float, levels_q};
|
||||
use photocraft_doc::adjust::{LevelsChannel, ToneSpace};
|
||||
use photocraft_doc::{Adjustment, DocId, LayerContent, LayerId};
|
||||
use photocraft_geom::Rect;
|
||||
use photocraft_raster::Surface;
|
||||
use serde_json::{Map, Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::canvas::ViewXform;
|
||||
|
||||
/// The dialog field that turns the display on.
|
||||
pub const FIELD: &str = "__clipping";
|
||||
|
||||
/// A pixel counts where the selection covers at least this much (the command blends the rest).
|
||||
const SELECTED: f32 = 0.5;
|
||||
|
||||
/// Which input slider's clipping is shown.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ClipEnd {
|
||||
/// The black slider: what the input levels clip to black.
|
||||
Shadows,
|
||||
/// The white slider: what they clip to white.
|
||||
Highlights,
|
||||
}
|
||||
|
||||
impl ClipEnd {
|
||||
/// The [`FIELD`] value that asks for this end.
|
||||
fn name(self) -> &'static str {
|
||||
match self {
|
||||
ClipEnd::Shadows => "shadows",
|
||||
ClipEnd::Highlights => "highlights",
|
||||
}
|
||||
}
|
||||
|
||||
/// The display a `__clipping` field value asks for (anything else: off).
|
||||
pub fn parse(v: Option<&Value>) -> Option<Self> {
|
||||
match v.and_then(Value::as_str) {
|
||||
Some("shadows") => Some(ClipEnd::Shadows),
|
||||
Some("highlights") => Some(ClipEnd::Highlights),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror an Alt-drag on the Levels dialog's black or white Input slider (editor state under
|
||||
/// `mem`) into the dialog's [`FIELD`]. Only changes are written, so a display turned on through
|
||||
/// automation stays until it is cleared or a drag ends.
|
||||
pub fn sync(ctx: &egui::Context, mem: egui::Id, fields: &mut Map<String, Value>) {
|
||||
if fields.get("__adjust").and_then(Value::as_str) != Some("levels") {
|
||||
return;
|
||||
}
|
||||
let held = ctx.input(|i| i.modifiers.alt && i.pointer.primary_down());
|
||||
let live = match crate::adjust_editors::levels_drag(ctx, mem) {
|
||||
Some(0) if held => Some(ClipEnd::Shadows),
|
||||
Some(2) if held => Some(ClipEnd::Highlights),
|
||||
_ => None,
|
||||
};
|
||||
let last_id = mem.with("levels-clipping");
|
||||
let last: Option<ClipEnd> = ctx.data(|d| d.get_temp(last_id)).flatten();
|
||||
if live == last {
|
||||
return;
|
||||
}
|
||||
ctx.data_mut(|d| d.insert_temp(last_id, live));
|
||||
match live {
|
||||
Some(end) => {
|
||||
fields.insert(FIELD.into(), json!(end.name()));
|
||||
}
|
||||
None => {
|
||||
fields.remove(FIELD);
|
||||
}
|
||||
}
|
||||
// The canvas paints before the dialogs: show the change on the next frame.
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// Which ends the Levels input levels clip a sample `v` (0..1) of one channel to, as
|
||||
/// (black, white): the channel's own input range or, after it, the composite's. `quantum` is the
|
||||
/// document's (whole levels, as the compositor rounds them; None: 32-bit float, unclamped). Gamma
|
||||
/// and the output levels don't matter: what reaches an end of an input range is flattened there,
|
||||
/// wherever the output levels then put it.
|
||||
pub fn classify(master: &LevelsChannel, channel: &LevelsChannel, v: f32, quantum: Option<f32>) -> (bool, bool) {
|
||||
let eval = |ch: &LevelsChannel, v: f32| if quantum.is_some() { levels_q(ch, v, quantum) } else { levels_float(ch, v) };
|
||||
let full = |ch: &LevelsChannel| LevelsChannel { out_black: 0.0, out_white: 1.0, ..ch.clone() };
|
||||
let stretch = |ch: &LevelsChannel| LevelsChannel { gamma: 1.0, ..full(ch) };
|
||||
let own = eval(&stretch(channel), v);
|
||||
let composite = eval(&stretch(master), eval(&full(channel), v));
|
||||
(own <= 0.0 || composite <= 0.0, own >= 1.0 || composite >= 1.0)
|
||||
}
|
||||
|
||||
/// A sample as a 16-bit key: exact for 8- and 16-bit documents (their samples are on this grid),
|
||||
/// 32-bit samples clamped to 0..1 (beyond is clipped either way). Non-finite: None.
|
||||
fn key(v: f32) -> Option<u16> {
|
||||
v.is_finite().then(|| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16)
|
||||
}
|
||||
|
||||
/// Per channel (R, G, B): the highest key clipped to black and the lowest clipped to white (None:
|
||||
/// no key clips that way).
|
||||
pub type Thresholds = [(Option<u16>, Option<u16>); 3];
|
||||
|
||||
/// The [`Thresholds`] of the Levels `adj` in a document of `depth`. None for anything but Levels
|
||||
/// in the RGB channel space (which Grayscale documents use too).
|
||||
pub fn thresholds(adj: &Adjustment, depth: SampleType) -> Option<Thresholds> {
|
||||
let Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, .. } = adj else { return None };
|
||||
let quantum = photocraft_compose::adjustment_quantum(depth);
|
||||
let at = |ch: &LevelsChannel, k: u16| classify(master, ch, f32::from(k) / 65535.0, quantum);
|
||||
Some(std::array::from_fn(|c| {
|
||||
let ch = &per_channel[c];
|
||||
// Black clipping holds below a key and white clipping above one (the stretch is monotone).
|
||||
let black = (at(ch, 0).0).then(|| last_true(|k| at(ch, k).0));
|
||||
let white = (at(ch, u16::MAX).1).then(|| first_true(|k| at(ch, k).1));
|
||||
(black, white)
|
||||
}))
|
||||
}
|
||||
|
||||
/// The largest key where `f` holds, given it holds at 0 and stops holding at most once.
|
||||
fn last_true(f: impl Fn(u16) -> bool) -> u16 {
|
||||
let (mut lo, mut hi) = (0u32, u32::from(u16::MAX) + 1);
|
||||
while hi - lo > 1 {
|
||||
let mid = (lo + hi) / 2;
|
||||
if f(mid as u16) {
|
||||
lo = mid;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
lo as u16
|
||||
}
|
||||
|
||||
/// The smallest key where `f` holds, given it holds at `u16::MAX` and starts holding at most once.
|
||||
fn first_true(f: impl Fn(u16) -> bool) -> u16 {
|
||||
let (mut lo, mut hi) = (-1i32, i32::from(u16::MAX));
|
||||
while hi - lo > 1 {
|
||||
let mid = (lo + hi) / 2;
|
||||
if f(mid as u16) {
|
||||
hi = mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
}
|
||||
}
|
||||
hi as u16
|
||||
}
|
||||
|
||||
/// Per block of the scanned area: each channel's minimum (0..3) and maximum (3..6) key over the
|
||||
/// pixels that count. A block with none has min > max.
|
||||
type Extremes = [u16; 6];
|
||||
const NONE: Extremes = [u16::MAX, u16::MAX, u16::MAX, 0, 0, 0];
|
||||
|
||||
/// The target's per-block extremes over `rect` (document pixels, `factor`×`factor` blocks).
|
||||
pub struct Stats {
|
||||
rect: Rect,
|
||||
factor: u32,
|
||||
size: [usize; 2],
|
||||
blocks: Vec<Extremes>,
|
||||
}
|
||||
|
||||
/// Scan `surface` (a layer's pixels) over `rect` in `factor`×`factor` blocks. Pixels count when
|
||||
/// visible (alpha > 0, finite) and, with a `selection`, at least half selected.
|
||||
pub fn scan(surface: &Surface, selection: Option<&Surface>, rect: Rect, factor: u32) -> Stats {
|
||||
let factor = factor.max(1);
|
||||
let f = factor as usize;
|
||||
let size = [rect.width().div_ceil(factor) as usize, rect.height().div_ceil(factor) as usize];
|
||||
let mut blocks = vec![NONE; size[0] * size[1]];
|
||||
let row = |by: usize, out: &mut [Extremes]| {
|
||||
let y0 = rect.y0.saturating_add((by * f) as i32);
|
||||
let band = Rect::new(rect.x0, y0, rect.x1, y0.saturating_add(factor as i32).min(rect.y1));
|
||||
let width = band.width() as usize;
|
||||
let mut px = vec![[0.0f32; 4]; width * band.height() as usize];
|
||||
surface.read_rgba_into(band, &mut px);
|
||||
let mut coverage = Vec::new();
|
||||
let stride = selection.map_or(1, |s| s.channels().max(1));
|
||||
if let Some(s) = selection {
|
||||
s.read_region_into(band, &mut coverage);
|
||||
}
|
||||
for (i, p) in px.iter().enumerate() {
|
||||
let visible = p[3] > 0.0;
|
||||
let selected = selection.is_none() || coverage.get(i * stride).is_some_and(|k| *k >= SELECTED);
|
||||
if !visible || !selected {
|
||||
continue;
|
||||
}
|
||||
let (Some(r), Some(g), Some(b)) = (key(p[0]), key(p[1]), key(p[2])) else { continue };
|
||||
let Some(e) = out.get_mut((i % width.max(1)) / f) else { continue };
|
||||
for (c, k) in [r, g, b].into_iter().enumerate() {
|
||||
e[c] = e[c].min(k);
|
||||
e[c + 3] = e[c + 3].max(k);
|
||||
}
|
||||
}
|
||||
};
|
||||
if size[0] > 0 {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
blocks.par_chunks_mut(size[0]).enumerate().for_each(|(by, out)| row(by, out));
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
for (by, out) in blocks.chunks_mut(size[0]).enumerate() {
|
||||
row(by, out);
|
||||
}
|
||||
}
|
||||
Stats { rect, factor, size, blocks }
|
||||
}
|
||||
|
||||
/// The display colour of a pixel clipped to black in the channels of `black` and to white in
|
||||
/// those of `white` (bit 0 red, 1 green, 2 blue).
|
||||
pub fn colour(end: ClipEnd, black: u8, white: u8) -> Color32 {
|
||||
let on = |mask: u8, c: u8| if mask & (1 << c) != 0 { 255 } else { 0 };
|
||||
match end {
|
||||
ClipEnd::Shadows => {
|
||||
let m = 7 ^ black;
|
||||
Color32::from_rgb(on(m, 0), on(m, 1), on(m, 2))
|
||||
}
|
||||
ClipEnd::Highlights => Color32::from_rgb(on(white, 0), on(white, 1), on(white, 2)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The display of `stats` for `end` under the per-channel `thresholds`, one colour per block (in
|
||||
/// parallel off the web: this runs on every slider move).
|
||||
pub fn image(stats: &Stats, thresholds: &Thresholds, end: ClipEnd) -> Vec<Color32> {
|
||||
// Integer bounds (none clipped: below every key / above every key) and the 8 possible colours.
|
||||
let lo = thresholds.map(|(lo, _)| lo.map_or(-1, i32::from));
|
||||
let hi = thresholds.map(|(_, hi)| hi.map_or(i32::from(u16::MAX) + 1, i32::from));
|
||||
let palette: [Color32; 8] = std::array::from_fn(|m| match end {
|
||||
ClipEnd::Shadows => colour(end, m as u8, 0),
|
||||
ClipEnd::Highlights => colour(end, 0, m as u8),
|
||||
});
|
||||
let block = |e: &Extremes| {
|
||||
let mut mask = 0usize;
|
||||
for c in 0..3 {
|
||||
let (min, max) = (i32::from(e[c]), i32::from(e[c + 3]));
|
||||
let clipped = match end {
|
||||
ClipEnd::Shadows => min <= max && min <= lo[c],
|
||||
ClipEnd::Highlights => min <= max && max >= hi[c],
|
||||
};
|
||||
mask |= usize::from(clipped) << c;
|
||||
}
|
||||
palette[mask]
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
use rayon::prelude::*;
|
||||
stats.blocks.par_iter().map(block).collect()
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
{
|
||||
stats.blocks.iter().map(block).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the display needs from the app: the end shown and the Levels adjustment, for the active
|
||||
/// document's target layer.
|
||||
struct Request {
|
||||
end: ClipEnd,
|
||||
adj: Adjustment,
|
||||
doc: std::sync::Arc<photocraft_doc::Document>,
|
||||
revision: u64,
|
||||
target: LayerId,
|
||||
}
|
||||
|
||||
/// The open Levels dialog's fields, if any. A Smart Filter's Levels (`__smartFilter`) edits the
|
||||
/// filter, not the layer's pixels, so it has no display (`adjust_preview` keeps it off the layer
|
||||
/// path too).
|
||||
fn dialog(app: &PhotocraftApp) -> Option<&Map<String, Value>> {
|
||||
app.ui.dialogs.iter().map(|d| &d.fields).find(|f| f.get("__adjust").and_then(Value::as_str) == Some("levels") && !f.contains_key("__smartFilter"))
|
||||
}
|
||||
|
||||
/// The display the open Levels dialog asks for on document `idx`. None when no Levels dialog
|
||||
/// shows clipping, `idx` isn't the active document, or the document can't show it: CMYK and Lab,
|
||||
/// a channel, mask or Quick Mask target, or a target that isn't a pixel layer.
|
||||
fn request(app: &PhotocraftApp, idx: usize) -> Option<Request> {
|
||||
let fields = dialog(app)?;
|
||||
let end = ClipEnd::parse(fields.get(FIELD))?;
|
||||
let params = crate::filter_dialog::params_of(fields);
|
||||
if app.session.active_index() != Some(idx) || crate::adjust_preview::targets_channel(app, idx, "levels", ¶ms) {
|
||||
return None;
|
||||
}
|
||||
let st = app.session.documents().get(idx)?;
|
||||
if !matches!(st.doc.mode, ColorMode::Rgb | ColorMode::Grayscale) {
|
||||
return None;
|
||||
}
|
||||
let target = st.active_layer?;
|
||||
if !matches!(st.doc.layer(target).map(|l| &l.content), Some(LayerContent::Raster(_))) {
|
||||
return None;
|
||||
}
|
||||
let adj = photocraft_engine::adjust_params::from_params("levels", ¶ms, None, st.doc.mode).ok()?;
|
||||
Some(Request { end, adj, doc: st.doc.clone(), revision: st.revision, target })
|
||||
}
|
||||
|
||||
/// The display's per-view state on the app.
|
||||
pub struct Cache {
|
||||
/// What `stats` scanned: document, revision, target, area and block size.
|
||||
key: (DocId, u64, LayerId, Rect, u32),
|
||||
stats: Stats,
|
||||
/// The end and thresholds the texture shows.
|
||||
drawn: Option<(ClipEnd, Thresholds)>,
|
||||
tex: Option<egui::TextureHandle>,
|
||||
}
|
||||
|
||||
/// Most blocks the display builds (2048 × 2048). A 2560×1440 canvas still gets one block per
|
||||
/// device pixel, a bigger one bigger blocks: the block stats stay under 50 MB, the texture at
|
||||
/// 16 MB, and a slider move near the 2 ms `levels_clipping_bench` measures for 3.7M blocks.
|
||||
const MAX_BLOCKS: u64 = 2048 * 2048;
|
||||
|
||||
/// The visible part of the document in `xf` and the block size giving about one texel per screen
|
||||
/// pixel (`ppp` physical pixels per point), within `max_side` texels a side and [`MAX_BLOCKS`].
|
||||
fn view_area(xf: &ViewXform, bounds: Rect, ppp: f32, max_side: u32) -> Option<(Rect, u32)> {
|
||||
let device_zoom = xf.zoom * ppp;
|
||||
if !(device_zoom.is_finite() && device_zoom > 0.0) {
|
||||
return None;
|
||||
}
|
||||
let visible = crate::canvas::visible_doc_rect(xf).intersect(&bounds);
|
||||
if visible.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let max_side = max_side.max(1);
|
||||
let (w, h) = (visible.width(), visible.height());
|
||||
let budget = ((u64::from(w) * u64::from(h)) as f64 / MAX_BLOCKS as f64).sqrt().ceil() as u32;
|
||||
let mut factor = ((1.0 / device_zoom).floor().clamp(1.0, 65536.0) as u32).max(w.div_ceil(max_side)).max(h.div_ceil(max_side)).max(budget);
|
||||
// Snap to the block grid so panning keeps the blocks where they were. That can widen the area
|
||||
// by up to a block, so grow the blocks until the snapped area fits.
|
||||
loop {
|
||||
let f = i32::try_from(factor).ok()?;
|
||||
let r = Rect::new(visible.x0.div_euclid(f) * f, visible.y0.div_euclid(f) * f, visible.x1, visible.y1).intersect(&bounds);
|
||||
let (bw, bh) = (r.width().div_ceil(factor), r.height().div_ceil(factor));
|
||||
if bw <= max_side && bh <= max_side && u64::from(bw) * u64::from(bh) <= MAX_BLOCKS {
|
||||
return Some((r, factor));
|
||||
}
|
||||
factor = factor.checked_add(1)?;
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw the Levels clipping display over the image in canvas view `xf` of document `idx`, if one
|
||||
/// is asked for. Drops the cache once no Levels dialog is open. Only the main canvas calls it:
|
||||
/// the one cache follows that view.
|
||||
pub fn paint(app: &mut PhotocraftApp, ctx: &egui::Context, painter: &egui::Painter, xf: &ViewXform, idx: usize) {
|
||||
if dialog(app).is_none() {
|
||||
app.levels_clipping = None;
|
||||
return;
|
||||
}
|
||||
// A background job holds the workers and may replace the document: no thresholds, scan or
|
||||
// image until it ends.
|
||||
if app.session.has_jobs() {
|
||||
return;
|
||||
}
|
||||
let Some(req) = request(app, idx) else { return };
|
||||
let Some(thr) = thresholds(&req.adj, req.doc.pixel_format().sample) else { return };
|
||||
let max_side = (ctx.input(|i| i.max_texture_side) as u32).clamp(256, 8192);
|
||||
let Some((rect, factor)) = view_area(xf, req.doc.bounds(), ctx.pixels_per_point(), max_side) else { return };
|
||||
let key = (req.doc.id, req.revision, req.target, rect, factor);
|
||||
if app.levels_clipping.as_ref().is_none_or(|c| c.key != key) {
|
||||
let Some(LayerContent::Raster(surface)) = req.doc.layer(req.target).map(|l| &l.content) else { return };
|
||||
let stats = scan(surface, req.doc.selection.as_ref(), rect, factor);
|
||||
let tex = app.levels_clipping.take().and_then(|c| c.tex);
|
||||
app.levels_clipping = Some(Cache { key, stats, drawn: None, tex });
|
||||
}
|
||||
let Some(cache) = app.levels_clipping.as_mut() else { return };
|
||||
if cache.drawn != Some((req.end, thr)) || cache.tex.is_none() {
|
||||
let img = egui::ColorImage::new(cache.stats.size, image(&cache.stats, &thr, req.end));
|
||||
match &mut cache.tex {
|
||||
Some(t) => t.set(img, TextureOptions::NEAREST),
|
||||
None => cache.tex = Some(ctx.load_texture("levels-clipping", img, TextureOptions::NEAREST)),
|
||||
}
|
||||
cache.drawn = Some((req.end, thr));
|
||||
}
|
||||
let Some(tex) = cache.tex.as_ref().map(egui::TextureHandle::id) else { return };
|
||||
// The texture covers whole blocks; the last row and column may reach past the area.
|
||||
let s = &cache.stats;
|
||||
let f = s.factor as f32;
|
||||
let uv = [s.rect.width() as f32 / (s.size[0] as f32 * f).max(1.0), s.rect.height() as f32 / (s.size[1] as f32 * f).max(1.0)];
|
||||
let (x0, y0, x1, y1) = (s.rect.x0 as f32, s.rect.y0 as f32, s.rect.x1 as f32, s.rect.y1 as f32);
|
||||
let mut mesh = Mesh::with_texture(tex);
|
||||
for (p, t) in [((x0, y0), (0.0, 0.0)), ((x1, y0), (uv[0], 0.0)), ((x1, y1), (uv[0], uv[1])), ((x0, y1), (0.0, uv[1]))] {
|
||||
mesh.vertices.push(egui::epaint::Vertex { pos: xf.to_screen(p.0, p.1), uv: pos2(t.0, t.1), color: Color32::WHITE });
|
||||
}
|
||||
mesh.add_triangle(0, 1, 2);
|
||||
mesh.add_triangle(0, 2, 3);
|
||||
painter.add(egui::Shape::mesh(mesh));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "levels_clipping_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,625 @@
|
||||
use super::*;
|
||||
use egui_kittest::Harness;
|
||||
use photocraft_color::{Color, PixelFormat};
|
||||
use photocraft_compose::Buffer;
|
||||
use photocraft_compose::adjust::{Transfer, apply_depth};
|
||||
use photocraft_doc::{Document, Size};
|
||||
|
||||
const DEPTHS: [SampleType; 3] = [SampleType::U8, SampleType::U16, SampleType::F32];
|
||||
|
||||
fn lv(in_black: f32, gamma: f32, in_white: f32) -> LevelsChannel {
|
||||
LevelsChannel { in_black: in_black / 255.0, gamma, in_white: in_white / 255.0, ..LevelsChannel::default() }
|
||||
}
|
||||
|
||||
fn levels(master: LevelsChannel, per_channel: [LevelsChannel; 3]) -> Adjustment {
|
||||
Adjustment::Levels { master, per_channel, space: ToneSpace::Rgb, black: LevelsChannel::default() }
|
||||
}
|
||||
|
||||
/// Samples to try at `depth`: every 8-bit level, a 16-bit sweep, and float values past both ends.
|
||||
fn samples(depth: SampleType) -> Vec<f32> {
|
||||
match depth {
|
||||
SampleType::U8 => (0..=255).map(|n| n as f32 / 255.0).collect(),
|
||||
SampleType::U16 => (0..=65535).step_by(13).map(|n| n as f32 / 65535.0).collect(),
|
||||
SampleType::F32 => (-40..=1100).map(|n| n as f32 / 1000.0).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// With gamma 1 and the output levels at their defaults, a channel is clipped exactly where the
|
||||
/// compositor's Levels result sits at an end: 0 for black, 1 for white (the 8-bit LUT staircase
|
||||
/// and the 32-bit formula; 16-bit against the whole-level chain the LUT samples).
|
||||
#[test]
|
||||
fn clipping_matches_the_levels_result() {
|
||||
let master = lv(30.0, 1.0, 200.0);
|
||||
let channels = [lv(10.0, 1.0, 240.0), LevelsChannel::default(), lv(60.0, 1.0, 120.0)];
|
||||
let adj = levels(master.clone(), channels.clone());
|
||||
for depth in DEPTHS {
|
||||
let quantum = photocraft_compose::adjustment_quantum(depth);
|
||||
for v in samples(depth) {
|
||||
let result: [f32; 3] = if depth == SampleType::U16 {
|
||||
std::array::from_fn(|c| levels_q(&master, levels_q(&channels[c], v, quantum), quantum))
|
||||
} else {
|
||||
let mut b = Buffer::filled(Rect::new(0, 0, 1, 1), [v, v, v, 1.0]);
|
||||
apply_depth(&adj, &mut b, Transfer::for_document(ColorMode::Rgb, depth), Some(depth));
|
||||
[b.px[0][0], b.px[0][1], b.px[0][2]]
|
||||
};
|
||||
for (c, (ch, r)) in channels.iter().zip(result).enumerate() {
|
||||
let (black, white) = classify(&master, ch, v, quantum);
|
||||
assert_eq!(black, r <= 0.0, "{depth:?} v={v} channel {c}: {r}");
|
||||
assert_eq!(white, r >= 1.0, "{depth:?} v={v} channel {c}: {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gamma and the output levels don't change what the input levels clip, so the display tests the
|
||||
/// input-range clamps rather than the final value. Narrowed output levels never reach black or
|
||||
/// white, and gamma below 1 rounds the 8-bit levels just above the black point to black although
|
||||
/// the slider keeps them. (Gamma above 1 reaches white at the top: its toe is at black.)
|
||||
#[test]
|
||||
fn gamma_and_output_levels_do_not_hide_clipping() {
|
||||
let q = Some(255.0);
|
||||
let master = LevelsChannel { gamma: 1.5, ..lv(20.0, 1.0, 200.0) };
|
||||
let plain = lv(20.0, 1.0, 200.0);
|
||||
let outputs = LevelsChannel { out_black: 25.0 / 255.0, out_white: 230.0 / 255.0, gamma: 0.6, ..lv(20.0, 1.0, 200.0) };
|
||||
let crushed = LevelsChannel { gamma: 0.5, ..lv(20.0, 1.0, 200.0) };
|
||||
assert!(levels_q(&outputs, 0.0, q) > 0.0 && levels_q(&outputs, 1.0, q) < 1.0, "narrowed outputs never reach black or white");
|
||||
assert_eq!(levels_q(&crushed, 21.0 / 255.0, q), 0.0, "gamma 0.5 rounds level 21 to black");
|
||||
for n in 0..=255 {
|
||||
let v = n as f32 / 255.0;
|
||||
let id = LevelsChannel::default();
|
||||
let want = (n <= 20, n >= 200);
|
||||
assert_eq!(classify(&master, &id, v, q), want, "gamma 1.5 composite, level {n}");
|
||||
assert_eq!(classify(&plain, &id, v, q), want, "level {n}");
|
||||
assert_eq!(classify(&outputs, &id, v, q), want, "outputs and gamma 0.6, level {n}");
|
||||
assert_eq!(classify(&crushed, &id, v, q), want, "gamma 0.5 composite, level {n}");
|
||||
assert_eq!(classify(&id, &master, v, q), want, "gamma 1.5 channel, level {n}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-channel thresholds give the same answer as [`classify`] for every key tried.
|
||||
#[test]
|
||||
fn thresholds_agree_with_classify() {
|
||||
let cases = [
|
||||
levels(lv(30.0, 1.0, 200.0), Default::default()),
|
||||
levels(LevelsChannel::default(), [lv(10.0, 0.4, 240.0), lv(0.0, 2.5, 90.0), lv(128.0, 1.0, 130.0)]),
|
||||
levels(lv(5.0, 3.0, 250.0), [LevelsChannel { out_black: 0.2, out_white: 0.9, ..lv(40.0, 0.7, 220.0) }, lv(0.0, 1.0, 255.0), lv(200.0, 9.0, 255.0)]),
|
||||
];
|
||||
for adj in &cases {
|
||||
let Adjustment::Levels { master, per_channel, .. } = adj else { panic!("Levels") };
|
||||
for depth in DEPTHS {
|
||||
let quantum = photocraft_compose::adjustment_quantum(depth);
|
||||
let thr = thresholds(adj, depth).unwrap();
|
||||
let keys: Vec<u16> = match depth {
|
||||
SampleType::U8 => (0..=255u16).map(|n| n * 257).collect(),
|
||||
_ => (0..=65535u16).step_by(7).chain([u16::MAX]).collect(),
|
||||
};
|
||||
for k in keys {
|
||||
for (c, (ch, (lo, hi))) in per_channel.iter().zip(thr).enumerate() {
|
||||
let (black, white) = classify(master, ch, f32::from(k) / 65535.0, quantum);
|
||||
assert_eq!(black, lo.is_some_and(|lo| k <= lo), "{depth:?} key {k} channel {c} black");
|
||||
assert_eq!(white, hi.is_some_and(|hi| k >= hi), "{depth:?} key {k} channel {c} white");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop's threshold display: black slider, a clipped channel drops to 0 on white; white
|
||||
/// slider, a clipped channel rises to 255 on black.
|
||||
#[test]
|
||||
fn colours_follow_the_clipped_channels() {
|
||||
let rgb = Color32::from_rgb;
|
||||
assert_eq!(colour(ClipEnd::Shadows, 0, 7), Color32::WHITE);
|
||||
assert_eq!(colour(ClipEnd::Shadows, 0b001, 0), rgb(0, 255, 255), "red alone: cyan");
|
||||
assert_eq!(colour(ClipEnd::Shadows, 0b110, 0), rgb(255, 0, 0), "green and blue: red");
|
||||
assert_eq!(colour(ClipEnd::Shadows, 7, 0), Color32::BLACK);
|
||||
assert_eq!(colour(ClipEnd::Highlights, 7, 0), Color32::BLACK);
|
||||
assert_eq!(colour(ClipEnd::Highlights, 0, 0b001), rgb(255, 0, 0), "red alone: red");
|
||||
assert_eq!(colour(ClipEnd::Highlights, 0, 0b011), rgb(255, 255, 0));
|
||||
assert_eq!(colour(ClipEnd::Highlights, 0, 7), Color32::WHITE);
|
||||
}
|
||||
|
||||
fn surface(fmt: PixelFormat, w: u32, h: u32, px: impl Fn(u32, u32) -> Vec<f32>) -> Surface {
|
||||
let mut s = Surface::new(fmt);
|
||||
let data: Vec<f32> = (0..h).flat_map(|y| (0..w).map(move |x| (x, y))).flat_map(|(x, y)| px(x, y)).collect();
|
||||
s.write_region(Rect::new(0, 0, w as i32, h as i32), &data);
|
||||
s
|
||||
}
|
||||
|
||||
/// A block shows what any counted pixel in it clips; transparent, unselected (under half) and
|
||||
/// non-finite pixels don't count.
|
||||
#[test]
|
||||
fn blocks_keep_lone_extremes_of_the_pixels_that_count() {
|
||||
let s = surface(PixelFormat::RGBA32F, 8, 8, |x, y| match (x, y) {
|
||||
(5, 5) => vec![0.0, 0.5, 0.5, 1.0],
|
||||
(1, 1) => vec![1.0, 1.0, 1.0, 0.0],
|
||||
(2, 2) => vec![f32::NAN, 1.0, 1.0, 1.0],
|
||||
(7, 1) => vec![1.0, 1.0, 1.0, 1.0],
|
||||
_ => vec![0.5, 0.5, 0.5, 1.0],
|
||||
});
|
||||
let thr = [(key(0.1), key(0.9)); 3];
|
||||
let grey = surface(PixelFormat::GRAY8, 8, 8, |x, _| vec![if x < 6 { 1.0 } else { 0.4 }]);
|
||||
for (selection, top_right) in [(None, Color32::WHITE), (Some(&grey), Color32::BLACK)] {
|
||||
let stats = scan(&s, selection, Rect::new(0, 0, 8, 8), 4);
|
||||
assert_eq!(stats.size, [2, 2]);
|
||||
let black = image(&stats, &thr, ClipEnd::Shadows);
|
||||
assert_eq!(black, vec![Color32::WHITE, Color32::WHITE, Color32::WHITE, Color32::from_rgb(0, 255, 255)], "{selection:?}");
|
||||
let white = image(&stats, &thr, ClipEnd::Highlights);
|
||||
assert_eq!(white, vec![Color32::BLACK, top_right, Color32::BLACK, Color32::BLACK], "{selection:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Gray documents' Levels act on one channel, so the display is black and white only.
|
||||
#[test]
|
||||
fn gray_layers_show_black_and_white_only() {
|
||||
let s = surface(PixelFormat::GRAYA8, 16, 1, |x, _| vec![x as f32 / 15.0, 1.0]);
|
||||
let adj = levels(lv(100.0, 1.0, 180.0), Default::default());
|
||||
let thr = thresholds(&adj, SampleType::U8).unwrap();
|
||||
let stats = scan(&s, None, Rect::new(0, 0, 16, 1), 1);
|
||||
for end in [ClipEnd::Shadows, ClipEnd::Highlights] {
|
||||
for (x, c) in image(&stats, &thr, end).into_iter().enumerate() {
|
||||
let v = x as f32 / 15.0 * 255.0;
|
||||
let clipped = if end == ClipEnd::Shadows { v <= 100.0 } else { v >= 180.0 };
|
||||
assert!(c == Color32::BLACK || c == Color32::WHITE, "x={x}: {c:?}");
|
||||
assert_eq!(c == colour(end, 7, 7), clipped, "{end:?} x={x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Out-of-range and non-finite settings never panic.
|
||||
#[test]
|
||||
fn hostile_settings_do_not_panic() {
|
||||
let bad = LevelsChannel { in_black: f32::NAN, in_white: -3.0, gamma: 0.0, out_black: f32::INFINITY, out_white: f32::NEG_INFINITY };
|
||||
for adj in [levels(bad.clone(), [bad.clone(), LevelsChannel::default(), lv(255.0, 100.0, 0.0)]), levels(LevelsChannel::default(), Default::default())] {
|
||||
for depth in DEPTHS {
|
||||
let _ = thresholds(&adj, depth);
|
||||
}
|
||||
}
|
||||
let cmyk =
|
||||
Adjustment::Levels { master: LevelsChannel::default(), per_channel: Default::default(), space: ToneSpace::Cmyk, black: LevelsChannel::default() };
|
||||
assert!(thresholds(&cmyk, SampleType::U8).is_none());
|
||||
assert!(thresholds(&Adjustment::Invert, SampleType::U8).is_none());
|
||||
for params in [json!({"inBlack": 1e9, "inWhite": -5, "gamma": 0}), json!({"red": {"gamma": 100, "inWhite": 0}}), json!({"inBlack": "x"})] {
|
||||
if let Ok(adj) = photocraft_engine::adjust_params::from_params("levels", ¶ms, None, ColorMode::Rgb) {
|
||||
let _ = thresholds(&adj, SampleType::U16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 16×8 document: the background's red channel ramps 0..1 left to right, green is 0.5, blue 1.
|
||||
fn ramp_app(mode: ColorMode, depth: SampleType) -> PhotocraftApp {
|
||||
let mut doc = Document::with_background("t", Size::new(16, 8), mode, depth, Color::rgba(1.0, 1.0, 1.0, 1.0));
|
||||
let gray = mode == ColorMode::Grayscale;
|
||||
if let Some(s) = doc.layers[0].surface_mut() {
|
||||
let data: Vec<f32> =
|
||||
(0..8).flat_map(|_| 0..16).flat_map(|x| if gray { vec![x as f32 / 15.0, 1.0] } else { vec![x as f32 / 15.0, 0.5, 1.0, 1.0] }).collect();
|
||||
s.write_region(Rect::new(0, 0, 16, 8), &data);
|
||||
}
|
||||
let target = doc.layers[0].id;
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.add_document(doc, None);
|
||||
session.select_layer(target).unwrap();
|
||||
PhotocraftApp::new(session, crate::Services::default())
|
||||
}
|
||||
|
||||
fn open_levels(app: &mut PhotocraftApp, params: Value, end: Option<&str>) -> u64 {
|
||||
let id = crate::adjust_dialog::open(app, "image.adjustments.levels").unwrap();
|
||||
let fields = &mut app.ui.dialog_mut(id).unwrap().fields;
|
||||
if let Value::Object(p) = params {
|
||||
fields.extend(p);
|
||||
}
|
||||
if let Some(end) = end {
|
||||
fields.insert(FIELD.into(), json!(end));
|
||||
}
|
||||
id
|
||||
}
|
||||
|
||||
/// A canvas view of the 16×8 document at `zoom` points per pixel (1 pixel per point).
|
||||
fn view(zoom: f32) -> ViewXform {
|
||||
ViewXform {
|
||||
rect: egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(16.0 * zoom, 8.0 * zoom)),
|
||||
zoom,
|
||||
center: [8.0, 4.0],
|
||||
flip: false,
|
||||
rotation: 0.0,
|
||||
aspect: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`paint`] in a frame of its own (so its mesh doesn't spill into a later frame's shapes), then
|
||||
/// the colours of the blocks it shows.
|
||||
fn paint_view(app: &mut PhotocraftApp, ctx: &egui::Context, xf: &ViewXform) -> Option<Vec<Color32>> {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
let painter = egui::Painter::new(ui.ctx().clone(), egui::LayerId::background(), egui::Rect::EVERYTHING);
|
||||
paint(app, ui.ctx(), &painter, xf, 0);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
let c = app.levels_clipping.as_ref()?;
|
||||
let (end, thr) = c.drawn?;
|
||||
Some(image(&c.stats, &thr, end))
|
||||
}
|
||||
|
||||
/// A view at one device pixel per document pixel whose visible document rect (with
|
||||
/// `visible_doc_rect`'s 2 px margin) is exactly `x0..x1` × `y0..y1`.
|
||||
fn xf_over(x0: i32, x1: i32, y0: i32, y1: i32) -> ViewXform {
|
||||
let size = egui::vec2((x1 - x0 - 4) as f32, (y1 - y0 - 4) as f32);
|
||||
ViewXform {
|
||||
rect: egui::Rect::from_min_size(egui::Pos2::ZERO, size),
|
||||
zoom: 1.0,
|
||||
center: [(x0 + x1) as f32 / 2.0, (y0 + y1) as f32 / 2.0],
|
||||
flip: false,
|
||||
rotation: 0.0,
|
||||
aspect: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Snapping the area to the block grid can widen it by up to a block; the blocks grow until the
|
||||
/// snapped area still fits the texture limit (here a 2048 px device limit) on both sides.
|
||||
#[test]
|
||||
fn the_snapped_area_fits_the_texture_limit() {
|
||||
let bounds = Rect::new(0, 0, 20000, 20000);
|
||||
let (r, f) = view_area(&xf_over(1, 4097, 0, 100), bounds, 1.0, 2048).unwrap();
|
||||
assert_eq!((r.x0, f), (0, 3), "4096 px from x 1: blocks of 2 would need 2049");
|
||||
for (x0, y0) in [(0, 0), (1, 1), (2, 3), (5, 7), (1023, 2047)] {
|
||||
for span in 4090..4100 {
|
||||
let (x1, y1) = (x0 + span, y0 + span / 2);
|
||||
let (r, f) = view_area(&xf_over(x0, x1, y0, y1), bounds, 1.0, 2048).unwrap();
|
||||
let fi = f as i32;
|
||||
assert!(r.width().div_ceil(f) <= 2048 && r.height().div_ceil(f) <= 2048, "{x0},{y0} span {span}: {r:?} / {f}");
|
||||
assert!(r.x0 % fi == 0 && r.y0 % fi == 0, "snapped to the grid: {r:?} / {f}");
|
||||
assert!(r.x0 <= x0 && r.y0 <= y0 && r.x1 >= x1 && r.y1 >= y1, "covers the view: {r:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// However big the display, the display builds at most `MAX_BLOCKS` blocks: an 8K canvas at
|
||||
/// 100 % gets bigger blocks instead of a 33M-texel texture, while 2560×1440 keeps one block per
|
||||
/// device pixel.
|
||||
#[test]
|
||||
fn a_huge_display_grows_the_blocks() {
|
||||
let bounds = Rect::new(0, 0, 20000, 20000);
|
||||
let (_, f) = view_area(&xf_over(0, 2564, 0, 1444), bounds, 1.0, 8192).unwrap();
|
||||
assert_eq!(f, 1, "2560×1440: one block per device pixel");
|
||||
for (w, h) in [(7680, 4320), (8192, 8192), (15360, 8640)] {
|
||||
let (r, f) = view_area(&xf_over(0, w, 0, h), bounds, 1.0, 8192).unwrap();
|
||||
let blocks = u64::from(r.width().div_ceil(f)) * u64::from(r.height().div_ceil(f));
|
||||
assert!(blocks <= MAX_BLOCKS, "{w}×{h}: {blocks} blocks of {f}");
|
||||
assert!(blocks > MAX_BLOCKS / 4, "{w}×{h}: no coarser than needed ({blocks} blocks of {f})");
|
||||
}
|
||||
}
|
||||
|
||||
/// The main canvas's view of the 16×8 document at 10 device pixels per pixel.
|
||||
fn main_view(app: &mut PhotocraftApp) -> crate::state::View {
|
||||
app.sync_views();
|
||||
crate::state::View { zoom: 10.0, center: [8.0, 4.0], fit_pending: false, fill_pending: false, ..app.ui.views[0].clone() }
|
||||
}
|
||||
|
||||
/// The shapes of one 160×80 canvas frame of document 0 in `view`.
|
||||
fn canvas_frame(ctx: &egui::Context, app: &mut PhotocraftApp, view: &crate::state::View, primary: bool) -> Vec<egui::epaint::ClippedShape> {
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
|
||||
crate::canvas::canvas_view(app, ui, 0, egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(160.0, 80.0)), view.clone(), primary);
|
||||
});
|
||||
out.textures_delta.clear();
|
||||
out.shapes
|
||||
}
|
||||
|
||||
/// How many meshes among `shapes` (shape lists included) draw texture `tex`.
|
||||
fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> usize {
|
||||
fn count(s: &egui::Shape, tex: egui::TextureId) -> usize {
|
||||
match s {
|
||||
egui::Shape::Mesh(m) => usize::from(m.texture_id == tex),
|
||||
egui::Shape::Vec(v) => v.iter().map(|s| count(s, tex)).sum(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
shapes.iter().map(|c| count(&c.shape, tex)).sum()
|
||||
}
|
||||
|
||||
/// The display keeps one cache, sized to the main canvas's view: an extra document window's
|
||||
/// canvas (not primary) neither draws it nor replaces that cache with its own view.
|
||||
#[test]
|
||||
fn only_the_main_canvas_draws_the_display() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
open_levels(&mut app, json!({"inBlack": 100}), Some("shadows"));
|
||||
let main = main_view(&mut app);
|
||||
let other = crate::state::View { zoom: 0.25, ..main.clone() };
|
||||
let shapes = canvas_frame(&ctx, &mut app, &main, true);
|
||||
let cache = app.levels_clipping.as_ref().expect("the main canvas builds the display");
|
||||
let (key, tex) = (cache.key, cache.tex.as_ref().map(egui::TextureHandle::id).expect("its texture"));
|
||||
assert_eq!(meshes_with(&shapes, tex), 1, "the main canvas draws the display");
|
||||
let shapes = canvas_frame(&ctx, &mut app, &other, false);
|
||||
assert_eq!(meshes_with(&shapes, tex), 0, "an extra window doesn't draw it");
|
||||
assert_eq!(app.levels_clipping.as_ref().map(|c| c.key), Some(key), "nor replaces the main canvas's cache");
|
||||
}
|
||||
|
||||
/// The display covers the view at about one texel per screen pixel, in every depth and in Gray,
|
||||
/// and goes away with the dialog.
|
||||
#[test]
|
||||
fn paint_shows_the_target_clipping_for_the_view() {
|
||||
let ctx = egui::Context::default();
|
||||
for (mode, depth) in
|
||||
[(ColorMode::Rgb, SampleType::U8), (ColorMode::Rgb, SampleType::U16), (ColorMode::Rgb, SampleType::F32), (ColorMode::Grayscale, SampleType::U8)]
|
||||
{
|
||||
let mut app = ramp_app(mode, depth);
|
||||
let id = open_levels(&mut app, json!({"inBlack": 100, "inWhite": 200}), Some("shadows"));
|
||||
let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap_or_else(|| panic!("{mode:?} {depth:?}"));
|
||||
assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [16, 8]);
|
||||
let gray = mode == ColorMode::Grayscale;
|
||||
let clipped = if gray { Color32::BLACK } else { Color32::from_rgb(0, 255, 255) };
|
||||
for (x, p) in px.iter().take(16).enumerate() {
|
||||
let want = if x as f32 / 15.0 * 255.0 <= 100.0 { clipped } else { Color32::WHITE };
|
||||
assert_eq!(*p, want, "{mode:?} {depth:?} shadows x={x}");
|
||||
}
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!("highlights"));
|
||||
let px = paint_view(&mut app, &ctx, &view(10.0)).unwrap();
|
||||
for (x, p) in px.iter().skip(16 * 7).enumerate() {
|
||||
let red = x as f32 / 15.0 * 255.0 >= 200.0;
|
||||
let want = match (gray, red) {
|
||||
(true, true) => Color32::WHITE,
|
||||
(true, false) => Color32::BLACK,
|
||||
(false, true) => Color32::from_rgb(255, 0, 255),
|
||||
(false, false) => Color32::from_rgb(0, 0, 255),
|
||||
};
|
||||
assert_eq!(*p, want, "{mode:?} {depth:?} highlights x={x}");
|
||||
}
|
||||
// Zoomed out, a texel covers a block of pixels.
|
||||
paint_view(&mut app, &ctx, &view(0.25)).unwrap();
|
||||
assert_eq!(app.levels_clipping.as_ref().unwrap().stats.factor, 4);
|
||||
assert_eq!(app.levels_clipping.as_ref().unwrap().stats.size, [4, 2]);
|
||||
// Off with the dialog still open: the cached texture stays but no canvas frame draws it.
|
||||
let main = main_view(&mut app);
|
||||
let shapes = canvas_frame(&ctx, &mut app, &main, true);
|
||||
let tex = app.levels_clipping.as_ref().and_then(|c| c.tex.as_ref()).map(egui::TextureHandle::id).unwrap();
|
||||
assert_eq!(meshes_with(&shapes, tex), 1, "{mode:?} {depth:?}: on, it draws");
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), Value::Null);
|
||||
assert!(request(&app, 0).is_none());
|
||||
let shapes = canvas_frame(&ctx, &mut app, &main, true);
|
||||
assert_eq!(meshes_with(&shapes, tex), 0, "{mode:?} {depth:?}: off, it draws nothing");
|
||||
assert!(app.levels_clipping.is_some(), "{mode:?} {depth:?}: the cache stays while the dialog is open");
|
||||
// Closed: the cache goes.
|
||||
app.ui.close_dialog(id);
|
||||
paint_view(&mut app, &ctx, &view(10.0));
|
||||
assert!(app.levels_clipping.is_none(), "{mode:?} {depth:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// CMYK and Lab documents, a Quick Mask, and a target that isn't a pixel layer keep the normal
|
||||
/// preview.
|
||||
#[test]
|
||||
fn ineligible_documents_show_no_display() {
|
||||
for mode in ["cmyk", "lab"] {
|
||||
let mut session = photocraft_engine::Session::new();
|
||||
session.execute("file.new", json!({"width": 8, "height": 8, "mode": mode})).unwrap();
|
||||
let mut app = PhotocraftApp::new(session, crate::Services::default());
|
||||
open_levels(&mut app, json!({}), Some("shadows"));
|
||||
assert!(request(&app, 0).is_none(), "{mode}");
|
||||
}
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
app.run("select.editInQuickMaskMode", json!({})).unwrap();
|
||||
assert!(app.session.active().unwrap().doc.quick_mask.is_some());
|
||||
open_levels(&mut app, json!({}), Some("shadows"));
|
||||
assert!(request(&app, 0).is_none(), "Quick Mask");
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
app.run("layer.newFillLayer.solidColor", json!({"color": "#808080"})).unwrap();
|
||||
open_levels(&mut app, json!({}), Some("shadows"));
|
||||
assert!(request(&app, 0).is_none(), "fill layer");
|
||||
}
|
||||
|
||||
/// While a background job runs the display draws nothing and neither scans nor builds its
|
||||
/// texture. It comes back once the job is done.
|
||||
#[test]
|
||||
fn a_running_job_holds_the_display() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
open_levels(&mut app, json!({"inBlack": 100}), Some("shadows"));
|
||||
let gate = Arc::new(AtomicBool::new(false));
|
||||
let open = gate.clone();
|
||||
let started = app
|
||||
.session
|
||||
.start_job(
|
||||
"test.slow",
|
||||
json!({}),
|
||||
"Slow",
|
||||
false,
|
||||
move |job| {
|
||||
while !open.load(Ordering::Relaxed) {
|
||||
job.check()?;
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
|_, ()| Ok(json!({})),
|
||||
)
|
||||
.unwrap();
|
||||
let photocraft_engine::jobs::Started::Job(job) = started else { panic!("ran inline") };
|
||||
assert!(app.session.has_jobs());
|
||||
assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none());
|
||||
assert!(app.levels_clipping.is_none(), "no scan and no texture while the job runs");
|
||||
gate.store(true, Ordering::Relaxed);
|
||||
app.session.wait_job(job).unwrap();
|
||||
assert!(!app.session.has_jobs());
|
||||
assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "back once the job is done");
|
||||
}
|
||||
|
||||
/// Closing the last document drops the display's cache: no canvas is left to paint it away.
|
||||
#[test]
|
||||
fn closing_the_last_document_drops_the_cache() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
open_levels(&mut app, json!({"inBlack": 100}), Some("shadows"));
|
||||
assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some());
|
||||
app.run("file.close", json!({})).unwrap();
|
||||
assert!(app.session.documents().is_empty());
|
||||
assert!(app.levels_clipping.is_none());
|
||||
}
|
||||
|
||||
/// A Smart Filter's Levels dialog edits the filter, not the layer's pixels: no display, and its
|
||||
/// cache goes as if no Levels dialog were open, even over a pixel layer.
|
||||
#[test]
|
||||
fn smart_filter_levels_show_no_display() {
|
||||
let ctx = egui::Context::default();
|
||||
let mut app = ramp_app(ColorMode::Rgb, SampleType::U8);
|
||||
let id = open_levels(&mut app, json!({"inBlack": 100}), Some("shadows"));
|
||||
assert!(paint_view(&mut app, &ctx, &view(10.0)).is_some(), "a plain Levels dialog shows it");
|
||||
let layer = app.session.active().and_then(|s| s.active_layer).unwrap();
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("__smartFilter".into(), json!({"layer": layer.0}));
|
||||
assert!(request(&app, 0).is_none());
|
||||
assert!(paint_view(&mut app, &ctx, &view(10.0)).is_none());
|
||||
assert!(app.levels_clipping.is_none(), "the cache goes");
|
||||
}
|
||||
|
||||
fn dialog_harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> {
|
||||
let h = Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state(|ui, app| crate::dialogs::show(app, ui.ctx()), app);
|
||||
PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]);
|
||||
h
|
||||
}
|
||||
|
||||
fn clipping(h: &Harness<'static, PhotocraftApp>) -> Option<Value> {
|
||||
h.state().ui.dialogs.first().and_then(|d| d.fields.get(FIELD).cloned())
|
||||
}
|
||||
|
||||
fn press(h: &mut Harness<'static, PhotocraftApp>, at: egui::Pos2, pressed: bool, modifiers: egui::Modifiers) {
|
||||
h.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers });
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
fn modifiers(h: &mut Harness<'static, PhotocraftApp>, m: egui::Modifiers) {
|
||||
h.event(egui::Event::ModifiersChanged(m));
|
||||
h.run_steps(1);
|
||||
}
|
||||
|
||||
/// Alt-dragging the black slider shows the shadows display while both are held, the white slider
|
||||
/// the highlights; the gamma slider, a drag without Alt and the Properties panel show nothing.
|
||||
/// The document stays untouched throughout.
|
||||
#[test]
|
||||
fn alt_drag_on_the_black_and_white_sliders_turns_the_display_on() {
|
||||
let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8));
|
||||
let original = h.state().session.active().unwrap().doc.clone();
|
||||
let id = crate::adjust_dialog::open(h.state_mut(), "image.adjustments.levels").unwrap();
|
||||
h.run_steps(3);
|
||||
let track = h.ctx.data(|d| d.get_temp::<egui::Rect>(egui::Id::unique(("adjust-dialog", "levels")).with("levels-slider"))).unwrap();
|
||||
let at = |level: f32| egui::pos2(track.left() + level / 255.0 * track.width(), track.center().y + 4.0);
|
||||
let alt = egui::Modifiers::ALT;
|
||||
// Black slider: on while Alt and the button are held, off with either.
|
||||
modifiers(&mut h, alt);
|
||||
h.event(egui::Event::PointerMoved(at(0.0)));
|
||||
press(&mut h, at(0.0), true, alt);
|
||||
assert_eq!(clipping(&h), Some(json!("shadows")));
|
||||
h.event(egui::Event::PointerMoved(at(60.0)));
|
||||
h.run_steps(1);
|
||||
let in_black = h.state().ui.dialogs[0].fields["inBlack"].as_f64().unwrap();
|
||||
assert!((55.0..=65.0).contains(&in_black), "the drag still moves the slider: {in_black}");
|
||||
assert_eq!(clipping(&h), Some(json!("shadows")));
|
||||
modifiers(&mut h, egui::Modifiers::NONE);
|
||||
assert_eq!(clipping(&h), None, "releasing Alt shows the preview");
|
||||
modifiers(&mut h, alt);
|
||||
assert_eq!(clipping(&h), Some(json!("shadows")), "Alt again");
|
||||
press(&mut h, at(60.0), false, alt);
|
||||
assert_eq!(clipping(&h), None, "releasing the mouse shows the preview");
|
||||
// White slider.
|
||||
h.event(egui::Event::PointerMoved(at(255.0)));
|
||||
press(&mut h, at(255.0), true, alt);
|
||||
assert_eq!(clipping(&h), Some(json!("highlights")));
|
||||
press(&mut h, at(255.0), false, alt);
|
||||
assert_eq!(clipping(&h), None);
|
||||
// Gamma slider (halfway between 60 and 255 at gamma 1).
|
||||
let gamma = 60.0 + (255.0 - 60.0) / 2.0;
|
||||
h.event(egui::Event::PointerMoved(at(gamma)));
|
||||
press(&mut h, at(gamma), true, alt);
|
||||
assert_eq!(clipping(&h), None, "the gamma slider has no display");
|
||||
press(&mut h, at(gamma), false, alt);
|
||||
// No Alt.
|
||||
modifiers(&mut h, egui::Modifiers::NONE);
|
||||
h.event(egui::Event::PointerMoved(at(60.0)));
|
||||
press(&mut h, at(60.0), true, egui::Modifiers::NONE);
|
||||
assert_eq!(clipping(&h), None, "no Alt, no display");
|
||||
press(&mut h, at(60.0), false, egui::Modifiers::NONE);
|
||||
assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original));
|
||||
assert!(h.state().ui.dialogs.iter().any(|d| d.id == id));
|
||||
}
|
||||
|
||||
/// Set through automation, the display stays until cleared; it never re-keys the live preview,
|
||||
/// touches the document or reaches OK.
|
||||
#[test]
|
||||
fn the_display_never_reaches_the_document() {
|
||||
let commit = |end: Option<&str>| {
|
||||
let mut h = dialog_harness(ramp_app(ColorMode::Rgb, SampleType::U8));
|
||||
let original = h.state().session.active().unwrap().doc.clone();
|
||||
let steps = h.state().session.active().unwrap().history.past_len();
|
||||
let id = open_levels(h.state_mut(), json!({"inBlack": 60, "gamma": 1.2}), None);
|
||||
h.run_steps(3);
|
||||
let _ = crate::adjust_preview::display_doc(h.state_mut(), 0);
|
||||
let key = crate::adjust_preview::shown_key(h.state());
|
||||
if let Some(end) = end {
|
||||
h.state_mut().ui.dialog_mut(id).unwrap().fields.insert(FIELD.into(), json!(end));
|
||||
h.run_steps(3);
|
||||
assert_eq!(clipping(&h), Some(json!(end)), "an automation-set display stays");
|
||||
let _ = crate::adjust_preview::display_doc(h.state_mut(), 0);
|
||||
assert_eq!(crate::adjust_preview::shown_key(h.state()), key, "the preview is not re-keyed");
|
||||
assert!(std::sync::Arc::ptr_eq(&h.state().session.active().unwrap().doc, &original));
|
||||
}
|
||||
crate::dialogs::confirm(h.state_mut(), id).unwrap();
|
||||
let st = h.state().session.active().unwrap();
|
||||
assert_eq!(st.history.past_len(), steps + 1);
|
||||
let mut px = Vec::new();
|
||||
st.doc.layers[0].surface().unwrap().read_region_into(Rect::new(0, 0, 16, 8), &mut px);
|
||||
px
|
||||
};
|
||||
let plain = commit(None);
|
||||
for end in ["shadows", "highlights"] {
|
||||
assert_eq!(commit(Some(end)), plain, "{end}: OK commits only the levels");
|
||||
}
|
||||
}
|
||||
|
||||
/// Scan once per view, then per slider move thresholds + colours (the texture upload comes on
|
||||
/// top). `CARGO_PROFILE_RELEASE_LTO=false CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 cargo test
|
||||
/// --release -p photocraft-ui-egui --lib levels_clipping_bench -- --ignored --nocapture`
|
||||
#[test]
|
||||
#[ignore = "benchmark"]
|
||||
fn levels_clipping_bench() {
|
||||
let adj = levels(lv(40.0, 1.3, 215.0), [lv(5.0, 1.0, 250.0), LevelsChannel::default(), lv(0.0, 0.8, 240.0)]);
|
||||
for (w, h) in [(6000u32, 4000u32), (7360, 4912)] {
|
||||
let mut s = Surface::new(PixelFormat::RGBA8);
|
||||
for y0 in (0..h).step_by(256) {
|
||||
let rows = 256.min(h - y0);
|
||||
let data: Vec<f32> = (0..rows * w)
|
||||
.flat_map(|i| {
|
||||
let (x, y) = (i % w, y0 + i / w);
|
||||
let n = ((x.wrapping_mul(2_654_435_761) ^ y.wrapping_mul(40_503)) >> 7) % 64;
|
||||
let v = (x as f32 / w as f32 * 0.8 + n as f32 / 255.0).min(1.0);
|
||||
[v, 1.0 - v, (y as f32 / h as f32), 1.0]
|
||||
})
|
||||
.collect();
|
||||
s.write_region(Rect::new(0, y0 as i32, w as i32, (y0 + rows) as i32), &data);
|
||||
}
|
||||
let fit = w.div_ceil(2400);
|
||||
for (name, rect, factor) in [("fit", Rect::new(0, 0, w as i32, h as i32), fit), ("100%", Rect::new(1000, 1000, 3560, 2440), 1)] {
|
||||
let best = |f: &mut dyn FnMut()| {
|
||||
(0..5)
|
||||
.map(|_| {
|
||||
let t = std::time::Instant::now();
|
||||
f();
|
||||
t.elapsed().as_secs_f64() * 1000.0
|
||||
})
|
||||
.fold(f64::MAX, f64::min)
|
||||
};
|
||||
let scan_ms = best(&mut || {
|
||||
std::hint::black_box(scan(&s, None, rect, factor));
|
||||
});
|
||||
let stats = scan(&s, None, rect, factor);
|
||||
let update_ms = best(&mut || {
|
||||
let thr = thresholds(&adj, SampleType::U8).unwrap();
|
||||
std::hint::black_box(egui::ColorImage::new(stats.size, image(&stats, &thr, ClipEnd::Shadows)));
|
||||
});
|
||||
println!(
|
||||
"{} MP {name} (1/{factor}, {}×{} texels): scan {scan_ms:.1} ms, update {update_ms:.1} ms",
|
||||
(w * h) / 1_000_000,
|
||||
stats.size[0],
|
||||
stats.size[1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,6 +41,7 @@ mod icon_data;
|
||||
pub mod icons;
|
||||
pub mod jobs_ui;
|
||||
pub(crate) mod last_brush;
|
||||
pub mod levels_clipping;
|
||||
pub mod links;
|
||||
pub mod memory_warning;
|
||||
pub mod menu_catalog;
|
||||
@@ -539,6 +540,8 @@ pub struct PhotocraftApp {
|
||||
/// The Properties panel's live adjustment-layer drag: its damage region and coverage
|
||||
/// (`adjust_preview::live_key`).
|
||||
pub(crate) live_adjust_preview: Option<adjust_preview::LiveAdjust>,
|
||||
/// The Levels dialog's Alt-drag clipping display over the canvas.
|
||||
pub(crate) levels_clipping: Option<levels_clipping::Cache>,
|
||||
/// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame.
|
||||
pub(crate) synthetic: Vec<egui::Event>,
|
||||
/// The one synthetic batch currently being delivered.
|
||||
|
||||
@@ -607,6 +607,88 @@ fn batch_dialogs_include_all_subfolders() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #10682 / #10113: an action recorded with the Type tool (a new type layer, typed in key by key)
|
||||
/// runs in Batch on every file of the folder and saves each into the destination.
|
||||
#[test]
|
||||
fn batch_runs_an_action_recorded_with_the_type_tool() {
|
||||
let (mut app, ctx) = app_with(1);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-ui-batch-type-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
for name in ["a.png", "b.png"] {
|
||||
app.run("file.saveACopy", json!({"path": dir.join("in").join(name).to_string_lossy()})).unwrap();
|
||||
}
|
||||
app.run("actions.record", json!({"name": "Caption"})).unwrap();
|
||||
let id = app.run("type.create", json!({"x": 10, "y": 40, "text": "", "size": 20})).unwrap()["layer"].as_u64().unwrap();
|
||||
for (i, c) in "Hi".chars().enumerate() {
|
||||
app.run("type.edit", json!({"layer": id, "replace": {"start": i, "end": i, "text": c.to_string()}, "coalesce": "typing"})).unwrap();
|
||||
}
|
||||
app.run("actions.stop", json!({})).unwrap();
|
||||
app.run("file.saveACopy", json!({"path": dir.join("ref.png").to_string_lossy()})).unwrap();
|
||||
assert_eq!(crate::actions::selected_action(&app).map(|a| a.steps.len()), Some(1), "one step for the typing");
|
||||
// CodeRabbit on #10730: and that step makes the layer with the text typed.
|
||||
assert_eq!(crate::actions::selected_action(&app).and_then(|a| a.steps.first()).map(|(_, p)| p["text"].clone()), Some(json!("Hi")));
|
||||
let d = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
let fields = &mut app.ui.dialog_mut(d).unwrap().fields;
|
||||
fields.insert("input".into(), json!(dir.join("in").to_string_lossy()));
|
||||
fields.insert("output".into(), json!(dir.join("out").to_string_lossy()));
|
||||
let r = crate::dialogs::confirm(&mut app, d).unwrap();
|
||||
assert_eq!(r["files"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
assert!(r.get("failed").is_none_or(|f| f.as_array().is_some_and(Vec::is_empty)), "{r}");
|
||||
for name in ["a.png", "b.png"] {
|
||||
assert!(dir.join("out").join(name).is_file(), "{name} saved: {r}");
|
||||
// CodeRabbit on #10730: the action ran on each file: the typed text is in its pixels.
|
||||
let pixels = |folder: &str| photocraft_codecs::decode(&std::fs::read(dir.join(folder).join(name)).unwrap()).unwrap().data().to_vec();
|
||||
assert_ne!(pixels("out"), pixels("in"), "{name}: the text was laid on it");
|
||||
}
|
||||
// CodeRabbit on #10730: all of it, as typed by hand: the document the action was recorded
|
||||
// on (the same image, with the text typed into it) has the pixels Batch wrote.
|
||||
let decoded = |path: std::path::PathBuf| photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap().data().to_vec();
|
||||
for name in ["a.png", "b.png"] {
|
||||
assert_eq!(decoded(dir.join("out").join(name)), decoded(dir.join("ref.png")), "{name}: Batch laid the whole text, as it was typed by hand");
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// #10682: a Batch whose action fails on every file said nothing; the status bar and a notice now
|
||||
/// name each file that failed and why.
|
||||
#[test]
|
||||
fn a_batch_that_fails_on_its_files_says_which_and_why() {
|
||||
let (mut app, ctx) = app_with(1);
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-ui-batch-fails-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(dir.join("in")).unwrap();
|
||||
for name in ["a.png", "b.png"] {
|
||||
app.run("file.saveACopy", json!({"path": dir.join("in").join(name).to_string_lossy()})).unwrap();
|
||||
}
|
||||
// A step for a layer that only the recording document has.
|
||||
app.session
|
||||
.actions
|
||||
.list
|
||||
.push(photocraft_engine::actions_cmds::Action::new("Stale", vec![("layer.setProps".into(), json!({"layer": 424_242, "opacity": 50}))]));
|
||||
let d = menu(&mut app, &ctx, "file.automate.batch", json!({})).unwrap()["dialog"].as_u64().unwrap();
|
||||
let fields = &mut app.ui.dialog_mut(d).unwrap().fields;
|
||||
fields.insert("input".into(), json!(dir.join("in").to_string_lossy()));
|
||||
fields.insert("output".into(), json!(dir.join("out").to_string_lossy()));
|
||||
let notices = app.ui.notices.len();
|
||||
let r = crate::dialogs::confirm(&mut app, d).unwrap();
|
||||
assert_eq!(r["errors"].as_array().map(Vec::len), Some(2), "{r}");
|
||||
assert!(app.ui.status_error, "the status bar reports it: {}", app.ui.status);
|
||||
let notice = app.ui.notices.get(notices).expect("a notice lists the files");
|
||||
assert_eq!(notice.lines.len(), 2);
|
||||
// CodeRabbit on #10730: a failure, not a warning, and each file by its whole path.
|
||||
assert!(notice.error && notice.title.ends_with("2 files failed"), "{}", notice.title);
|
||||
let path = |name: &str| format!("{}: ", dir.join("in").join(name).to_string_lossy());
|
||||
assert!(notice.lines[0].starts_with(&path("a.png")) && notice.lines[1].starts_with(&path("b.png")), "{:?}", notice.lines);
|
||||
// CodeRabbit on #10730: each line is its file's error, word for word, path then reason.
|
||||
let errors = r["errors"].as_array().unwrap();
|
||||
for (line, e) in notice.lines.iter().zip(errors) {
|
||||
assert!(!e["error"].as_str().unwrap_or_default().trim().is_empty(), "{e}");
|
||||
assert_eq!(*line, format!("{}: {}", e["file"].as_str().unwrap(), e["error"].as_str().unwrap()));
|
||||
}
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Float in Window takes the document and the screen position a dragged-off tab was dropped at
|
||||
/// (#3733); bad params are errors, not panics.
|
||||
#[test]
|
||||
|
||||
@@ -184,6 +184,18 @@ pub fn io_warnings(app: &mut PhotocraftApp, what: &str, warnings: &[String]) {
|
||||
post(app, title, warnings.to_vec(), false, None);
|
||||
}
|
||||
|
||||
/// Report the files a folder run (Batch, Image Processor, …) could not process, one line each:
|
||||
/// the status bar shows the first as an error, and a notice titled with how many failed lists
|
||||
/// them all until dismissed (#10682).
|
||||
pub fn file_failures(app: &mut PhotocraftApp, what: &str, failures: &[String]) {
|
||||
let Some(first) = failures.first() else { return };
|
||||
let n = failures.len();
|
||||
let title = crate::i18n::fmt(&crate::i18n::trn(crate::i18n::current(), n as u64, "{what}: {n} file failed", "{what}: {n} files failed"), &[("what", what)]);
|
||||
app.ui.status = if n == 1 { format!("{what}: {first}") } else { format!("{title}: {first} …") };
|
||||
app.ui.status_error = true;
|
||||
post(app, title, failures.to_vec(), true, None);
|
||||
}
|
||||
|
||||
/// Report a failed file operation: the status bar shows it as an error and a notice keeps it on
|
||||
/// screen until dismissed.
|
||||
pub fn error(app: &mut PhotocraftApp, message: String) {
|
||||
|
||||
@@ -296,7 +296,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn preview_draws_a_stroke_that_fits() {
|
||||
let mut b = BrushSettings { size: 400.0, ..Default::default() };
|
||||
// The preview's S-curve carries a pressure ramp, so the coverage window below is a
|
||||
// tapering stroke's: Pressure for Size is off by default since #11809, so the brush asks.
|
||||
let mut b = BrushSettings { size: 400.0, pressure_size: true, ..Default::default() };
|
||||
let px = preview_pixels(&b, 120, 40, [1.0, 0.0, 0.0, 1.0]);
|
||||
assert_eq!(px.len(), 120 * 40 * 4);
|
||||
let covered = px.as_chunks::<4>().0.iter().filter(|p| p[3] > 128).count();
|
||||
|
||||
@@ -230,6 +230,23 @@ fn set_ruler(app: &mut PhotocraftApp, r: Ruler) {
|
||||
let _ = app.run("image.analysis.rulerTool", json!({"start": r.start, "end": r.end, "protractor": r.protractor}));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "note_show_on_new_tests.rs"]
|
||||
mod note_show_on_new_tests;
|
||||
|
||||
/// Create a note at the rounded document position using the Note tool's options.
|
||||
/// After `notes.add` succeeds, select the note and open the Notes panel. Enable Show Notes
|
||||
/// while leaving the master Extras switch alone.
|
||||
pub(crate) fn create_note(app: &mut PhotocraftApp, x: f64, y: f64) -> Result<Value, String> {
|
||||
let a = &app.ui.analysis;
|
||||
let params = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": a.note_color});
|
||||
let result = app.run("notes.add", params)?;
|
||||
app.ui.analysis.note_selected = result["index"].as_u64().map(|v| v as usize);
|
||||
app.ui.analysis.notes = true;
|
||||
app.ui.view.show.notes = true;
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Pointer input for the Ruler, Count, Note and Color Sampler tools. Returns true when consumed.
|
||||
pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> bool {
|
||||
let tool = app.active_tool();
|
||||
@@ -318,12 +335,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) ->
|
||||
app.ui.analysis.drag = Some(Drag::Note(i, [x - doc.notes[i].position[0], y - doc.notes[i].position[1]]));
|
||||
}
|
||||
None => {
|
||||
let a = &app.ui.analysis;
|
||||
let p = json!({"x": x.round(), "y": y.round(), "author": a.note_author, "color": [a.note_color[0], a.note_color[1], a.note_color[2]]});
|
||||
if let Ok(r) = app.run("notes.add", p) {
|
||||
app.ui.analysis.note_selected = r["index"].as_u64().map(|v| v as usize);
|
||||
app.ui.analysis.notes = true;
|
||||
}
|
||||
let _ = create_note(app, x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -821,11 +833,8 @@ fn notes_panel(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
if let Some(p) = edit {
|
||||
let _ = app.run("notes.set", p);
|
||||
}
|
||||
if delete
|
||||
&& let Some(i) = sel
|
||||
&& app.run("notes.delete", json!({"index": i})).is_ok()
|
||||
{
|
||||
app.ui.analysis.note_selected = (n > 1).then(|| i.min(n - 2));
|
||||
if delete && let Some(i) = sel {
|
||||
ask_delete_note(app, i);
|
||||
}
|
||||
if close {
|
||||
app.ui.analysis.notes = false;
|
||||
@@ -988,3 +997,97 @@ fn dialog(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
|
||||
/// Marks the "Delete this note?" alert (#11788).
|
||||
const DELETE_NOTE_MARK: &str = "__deleteNote";
|
||||
/// Its "Don't show again", kept with the other dialog preferences.
|
||||
const DELETE_NOTE_PREF: &str = "notes.delete.confirmation";
|
||||
|
||||
/// Delete note `index` of the active document, as the Note tool's ⌫/Delete and the Notes panel's
|
||||
/// trash do: after the alert "Delete this note?" ([Yes] [No], "Don't show again"), or at once once
|
||||
/// that is ticked. Nothing is selected afterwards.
|
||||
pub fn ask_delete_note(app: &mut PhotocraftApp, index: usize) {
|
||||
let skip = app.session.prefs().dialogs.get(DELETE_NOTE_PREF).and_then(|v| v.get("skip")).and_then(Value::as_bool) == Some(true);
|
||||
let Some(doc) = app.session.active().map(|s| s.doc.id.0) else { return };
|
||||
if skip {
|
||||
delete_note(app, index);
|
||||
return;
|
||||
}
|
||||
if app.ui.dialogs.iter().any(|d| owns_delete_note(&d.fields)) {
|
||||
return;
|
||||
}
|
||||
let mut f = Map::new();
|
||||
f.insert(DELETE_NOTE_MARK.into(), json!(true));
|
||||
f.insert("__command".into(), json!("notes.delete"));
|
||||
f.insert("__label".into(), json!(tl!("Delete Note")));
|
||||
f.insert("document".into(), json!(doc));
|
||||
f.insert("index".into(), json!(index));
|
||||
f.insert("skip".into(), json!(false));
|
||||
app.ui.open_dialog(crate::state::DialogKind::Command, f);
|
||||
}
|
||||
|
||||
fn delete_note(app: &mut PhotocraftApp, index: usize) {
|
||||
match app.run("notes.delete", json!({"index": index})) {
|
||||
Ok(_) => app.ui.analysis.note_selected = None,
|
||||
Err(e) => {
|
||||
app.ui.status = e;
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn owns_delete_note(fields: &Map<String, Value>) -> bool {
|
||||
fields.contains_key(DELETE_NOTE_MARK)
|
||||
}
|
||||
|
||||
pub fn delete_note_body(ui: &mut egui::Ui, fields: &mut Map<String, Value>) {
|
||||
ui.label(tl!("Delete this note?"));
|
||||
ui.add_space(8.0);
|
||||
let mut skip = fields.get("skip").and_then(Value::as_bool).unwrap_or(false);
|
||||
ui.checkbox(&mut skip, tl!("Don't show again"));
|
||||
fields.insert("skip".into(), json!(skip));
|
||||
}
|
||||
|
||||
/// Yes: the note goes (one "Delete Note" step), and "Don't show again" is remembered.
|
||||
pub fn confirm_delete_note(app: &mut PhotocraftApp, fields: &Map<String, Value>) -> Result<Value, String> {
|
||||
let index = fields.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok()).ok_or(tl!("No note to delete"))?;
|
||||
let doc = app.session.active().map(|s| (s.doc.id.0, s.doc.notes.len()));
|
||||
if doc.map(|d| d.0) != fields.get("document").and_then(Value::as_u64) || doc.is_none_or(|d| index >= d.1) {
|
||||
return Err(tl!("The document or its notes changed. Please delete the note again.").into());
|
||||
}
|
||||
let result = app.run("notes.delete", json!({"index": index}))?;
|
||||
app.ui.analysis.note_selected = None;
|
||||
if fields.get("skip").and_then(Value::as_bool) == Some(true) {
|
||||
app.session.edit_prefs(|prefs| {
|
||||
prefs.dialogs.insert(DELETE_NOTE_PREF.into(), json!({"skip": true}));
|
||||
});
|
||||
if let Err(error) = crate::prefs_ui::save_preferences(app) {
|
||||
app.ui.status = crate::i18n::fmt(tl!("Note deleted, but the preference could not be saved: {error}"), &[("error", &error)]);
|
||||
app.ui.status_error = true;
|
||||
}
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The Note tool with a note selected: ⌫/Delete asks to delete the note (#11788), never the
|
||||
/// layer (Delete Layer) or the pixels (Edit › Clear). Text fields keep the keys.
|
||||
pub fn note_keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool {
|
||||
use crate::shortcut_dispatch::Focus;
|
||||
let Some(index) = app.ui.analysis.note_selected else { return false };
|
||||
if app.ui.tool != Tool::Note || app.ui.text_edit.is_some() || matches!(Focus::of(ctx), Focus::Text | Focus::DeletingWidget) {
|
||||
return false;
|
||||
}
|
||||
if app.session.active().is_none_or(|s| index >= s.doc.notes.len()) {
|
||||
return false;
|
||||
}
|
||||
let mods = ctx.input(|i| i.modifiers);
|
||||
if !mods.is_none() || !ctx.input_mut(|i| i.consume_key(mods, egui::Key::Delete) || i.consume_key(mods, egui::Key::Backspace)) {
|
||||
return false;
|
||||
}
|
||||
ask_delete_note(app, index);
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "note_delete_key_tests.rs"]
|
||||
mod note_delete_key_tests;
|
||||
@@ -0,0 +1,107 @@
|
||||
//! #11788: with the Note tool, ⌫/Delete on a selected note asks "Delete this note?" and deletes
|
||||
//! the note, never the layer; the Notes panel's trash asks the same.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A document with a second layer and one note, the Note tool on and the note selected.
|
||||
fn app() -> PhotocraftApp {
|
||||
let mut s = photocraft_engine::Session::new();
|
||||
s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
s.execute("layer.new.layer", json!({"name": "Ink"})).unwrap();
|
||||
s.execute("notes.add", json!({"x": 10, "y": 12, "text": "fix this"})).unwrap();
|
||||
let mut app = PhotocraftApp::new(s, crate::Services::default());
|
||||
app.ui.tool = Tool::Note;
|
||||
app.ui.analysis.note_selected = Some(0);
|
||||
app
|
||||
}
|
||||
|
||||
/// A key through the app's shortcut handling, as the canvas gets it.
|
||||
fn press(app: &mut PhotocraftApp, key: egui::Key) {
|
||||
let ctx = egui::Context::default();
|
||||
let m = egui::Modifiers::NONE;
|
||||
let raw = egui::RawInput {
|
||||
events: vec![egui::Event::ModifiersChanged(m), egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: m }],
|
||||
..Default::default()
|
||||
};
|
||||
ctx.begin_pass(raw);
|
||||
crate::shortcuts::handle(app, &ctx);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
}
|
||||
|
||||
fn layers(app: &PhotocraftApp) -> usize {
|
||||
app.session.active().unwrap().doc.layers.len()
|
||||
}
|
||||
|
||||
fn notes(app: &PhotocraftApp) -> usize {
|
||||
app.session.active().unwrap().doc.notes.len()
|
||||
}
|
||||
|
||||
fn alert(app: &PhotocraftApp) -> Option<u64> {
|
||||
app.ui.dialogs.iter().find(|d| owns_delete_note(&d.fields)).map(|d| d.id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delete_with_a_note_selected_asks_and_deletes_the_note_not_the_layer() {
|
||||
for key in [egui::Key::Delete, egui::Key::Backspace] {
|
||||
let mut app = app();
|
||||
let steps = app.session.active().unwrap().history.past_len();
|
||||
press(&mut app, key);
|
||||
let id = alert(&app).unwrap_or_else(|| panic!("{key:?}: the alert"));
|
||||
assert_eq!((layers(&app), notes(&app)), (2, 1), "{key:?}: nothing changes before the answer");
|
||||
crate::dialogs::confirm(&mut app, id).unwrap();
|
||||
assert_eq!((layers(&app), notes(&app)), (2, 0), "{key:?}: the note goes, the layers stay");
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.history.past_len(), steps + 1);
|
||||
assert_eq!(st.history.undo_label(), Some("Delete Note"));
|
||||
assert_eq!(app.ui.analysis.note_selected, None, "nothing selected after");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_keeps_the_document_and_history() {
|
||||
let mut app = app();
|
||||
let steps = app.session.active().unwrap().history.past_len();
|
||||
press(&mut app, egui::Key::Delete);
|
||||
let id = alert(&app).expect("the alert");
|
||||
crate::dialogs::cancel(&mut app, id).unwrap();
|
||||
assert_eq!((layers(&app), notes(&app)), (2, 1));
|
||||
assert_eq!(app.session.active().unwrap().history.past_len(), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dont_show_again_skips_the_alert_next_time() {
|
||||
let mut app = app();
|
||||
app.run("notes.add", json!({"x": 30, "y": 30})).unwrap();
|
||||
press(&mut app, egui::Key::Delete);
|
||||
let id = alert(&app).expect("the alert");
|
||||
app.ui.dialog_mut(id).unwrap().fields.insert("skip".into(), json!(true));
|
||||
crate::dialogs::confirm(&mut app, id).unwrap();
|
||||
assert_eq!(notes(&app), 1);
|
||||
// The panel's trash goes the same way: no alert, the note is deleted at once.
|
||||
ask_delete_note(&mut app, 0);
|
||||
assert!(alert(&app).is_none());
|
||||
assert_eq!((layers(&app), notes(&app)), (2, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_notes_panel_trash_asks_too() {
|
||||
let mut app = app();
|
||||
ask_delete_note(&mut app, 0);
|
||||
assert!(alert(&app).is_some());
|
||||
assert_eq!(notes(&app), 1, "nothing goes before Yes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_selected_note_delete_keeps_its_usual_route() {
|
||||
let mut app = app();
|
||||
app.ui.analysis.note_selected = None;
|
||||
press(&mut app, egui::Key::Delete);
|
||||
assert!(alert(&app).is_none());
|
||||
assert_eq!(notes(&app), 1, "the note stays");
|
||||
// Another tool with a note still selected: the note isn't asked about.
|
||||
let mut other = self::app();
|
||||
other.ui.tool = Tool::Move;
|
||||
press(&mut other, egui::Key::Delete);
|
||||
assert!(alert(&other).is_none());
|
||||
assert_eq!(notes(&other), 1);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use super::{PhotocraftApp, Tool, ToolEvent, json};
|
||||
use crate::control::{ControlRequest, Outcome, handle};
|
||||
|
||||
/// Open a document with the Note tool active and no notes yet.
|
||||
fn note_tool() -> (PhotocraftApp, egui::Context) {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 200, "height": 120})).unwrap();
|
||||
app.ui.tool = Tool::Note;
|
||||
(app, egui::Context::default())
|
||||
}
|
||||
|
||||
/// Send a click or drag to the canvas in document coordinates.
|
||||
fn gesture(app: &mut PhotocraftApp, [x, y]: [f64; 2], [end_x, end_y]: [f64; 2]) {
|
||||
crate::canvas::tool_event(app, ToolEvent::Down { x, y, pressure: 1.0 }, egui::Modifiers::NONE);
|
||||
if [x, y] != [end_x, end_y] {
|
||||
crate::canvas::tool_event(app, ToolEvent::Move { x: end_x, y: end_y, pressure: 1.0 }, egui::Modifiers::NONE);
|
||||
}
|
||||
crate::canvas::tool_event(app, ToolEvent::Up { x: end_x, y: end_y }, egui::Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// A new note reveals both icons, and the menu can hide them again.
|
||||
#[test]
|
||||
fn creating_a_note_rechecks_show_notes_and_reveals_both_notes() {
|
||||
let (mut app, ctx) = note_tool();
|
||||
crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap();
|
||||
app.run("notes.add", json!({"x": 20, "y": 20})).unwrap();
|
||||
assert!(!app.ui.view.show.notes && !app.ui.analysis.notes);
|
||||
assert!(!app.ui.view.shows(app.ui.view.show.notes));
|
||||
|
||||
app.ui.analysis.note_author = "QA".into();
|
||||
app.ui.analysis.note_color = [0.25, 0.5, 1.0];
|
||||
gesture(&mut app, [130.0, 70.0], [130.0, 70.0]);
|
||||
|
||||
let notes = &app.session.active().unwrap().doc.notes;
|
||||
assert_eq!(notes.len(), 2);
|
||||
assert_eq!(notes[0].position, [20.0, 20.0]);
|
||||
assert_eq!(notes[1].position, [130.0, 70.0]);
|
||||
assert_eq!(notes[1].author, "QA");
|
||||
assert_eq!(notes[1].color.to_rgb(), [0.25, 0.5, 1.0]);
|
||||
assert_eq!(app.ui.analysis.note_selected, Some(1));
|
||||
assert!(app.ui.analysis.notes && app.ui.view.shows(app.ui.view.show.notes));
|
||||
|
||||
crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap();
|
||||
assert!(!app.ui.view.shows(app.ui.view.show.notes));
|
||||
}
|
||||
|
||||
/// Selecting or moving a stored note keeps Show Notes off.
|
||||
#[test]
|
||||
fn selecting_and_dragging_an_existing_note_preserve_hidden_notes() {
|
||||
let (mut app, ctx) = note_tool();
|
||||
app.run("notes.add", json!({"x": 30, "y": 40, "author": "QA"})).unwrap();
|
||||
crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap();
|
||||
|
||||
gesture(&mut app, [32.0, 42.0], [32.0, 42.0]);
|
||||
assert!(!app.ui.view.show.notes);
|
||||
assert_eq!(app.ui.analysis.note_selected, Some(0));
|
||||
assert_eq!(app.ui.analysis.note_author, "QA");
|
||||
|
||||
gesture(&mut app, [32.0, 42.0], [62.0, 52.0]);
|
||||
assert!(!app.ui.view.show.notes);
|
||||
let notes = &app.session.active().unwrap().doc.notes;
|
||||
assert_eq!(notes.len(), 1);
|
||||
assert_eq!(notes[0].position, [60.0, 50.0]);
|
||||
}
|
||||
|
||||
/// Creating a note rechecks Show Notes while Extras still suppresses the overlay.
|
||||
#[test]
|
||||
fn creating_a_note_leaves_extras_off() {
|
||||
let (mut app, ctx) = note_tool();
|
||||
crate::menus::invoke(&mut app, &ctx, "view.show.notes", json!({})).unwrap();
|
||||
crate::menus::invoke(&mut app, &ctx, "view.extras", json!({})).unwrap();
|
||||
assert!(!app.ui.view.show.notes && !app.ui.view.extras);
|
||||
|
||||
gesture(&mut app, [130.0, 70.0], [130.0, 70.0]);
|
||||
|
||||
assert_eq!(app.session.active().unwrap().doc.notes.len(), 1);
|
||||
assert!(app.ui.view.show.notes);
|
||||
assert!(!app.ui.view.extras && !app.ui.view.shows(app.ui.view.show.notes));
|
||||
}
|
||||
|
||||
/// A denied canvas creation preserves the selected note and visibility settings.
|
||||
#[test]
|
||||
fn rejected_note_creation_does_not_change_visibility_or_selection() {
|
||||
let (mut app, ctx) = note_tool();
|
||||
app.run("notes.add", json!({"x": 20, "y": 20})).unwrap();
|
||||
app.run("notes.add", json!({"x": 70, "y": 20})).unwrap();
|
||||
gesture(&mut app, [72.0, 22.0], [72.0, 22.0]);
|
||||
assert_eq!(app.ui.analysis.note_selected, Some(1));
|
||||
app.ui.view.show.notes = false;
|
||||
app.ui.analysis.notes = false;
|
||||
app.ui.view.extras = false;
|
||||
|
||||
let denials = Rc::new(Cell::new(0));
|
||||
let observed_denials = Rc::clone(&denials);
|
||||
app.services.automation_command = Some(Box::new(move |id, _| {
|
||||
if id == "notes.add" {
|
||||
observed_denials.set(observed_denials.get() + 1);
|
||||
return Err("note creation denied".into());
|
||||
}
|
||||
Ok(())
|
||||
}));
|
||||
app.automation_input = true;
|
||||
let (request, _reply) = ControlRequest::new("ui.pointer", json!({"events": [{"kind": "down", "x": 130, "y": 70}, {"kind": "up", "x": 130, "y": 70}]}));
|
||||
let Outcome::Done(reply) = handle(&mut app, &ctx, &request) else { panic!("ui.pointer should reply immediately") };
|
||||
|
||||
assert_eq!(reply["ok"], true);
|
||||
assert_eq!(denials.get(), 1);
|
||||
assert!(!app.ui.view.show.notes && !app.ui.analysis.notes && !app.ui.view.extras);
|
||||
assert_eq!(app.ui.analysis.note_selected, Some(1));
|
||||
assert_eq!(app.session.active().unwrap().doc.notes.len(), 2);
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::panel::chevron_icon;
|
||||
use super::scrub::take_label_scrub_name;
|
||||
use super::slider::wheel_notches_of;
|
||||
use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, type_ahead, vec2};
|
||||
use super::{Pos2, Rect, Response, Sense, Stroke, Tokens, Ui, Vec2, pos2, type_ahead, vec2};
|
||||
|
||||
/// A compact labelled dropdown in the studio style.
|
||||
pub fn dropdown<T: PartialEq + Clone>(ui: &mut Ui, id: &str, name: &str, current: &mut T, options: &[(T, &str)], width: f32) -> bool {
|
||||
@@ -245,20 +245,100 @@ fn combo_box_arrow_keys<T: PartialEq + Clone>(ui: &mut Ui, response: &Response,
|
||||
/// seen (clear of a taskbar a too-tall window runs under, #315), scrolling past that, so long
|
||||
/// context menus (a layer's, the canvas tools') stay reachable on small windows instead of running
|
||||
/// off the bottom. egui moves a popup up to keep it in the window, so a menu opened low on the
|
||||
/// screen first shifts up and only scrolls when it is taller than the window.
|
||||
/// screen first shifts up and only scrolls when it is taller than the window. An overflowing
|
||||
/// menu's ▲/▼ scroll arrows (#2091) count toward that height, so both stay on screen.
|
||||
pub fn menu_scroll<R>(ui: &mut Ui, add_contents: impl FnOnce(&mut Ui) -> R) -> R {
|
||||
// The popup frame's margin and stroke, and a small gap to the window's edges.
|
||||
let frame = ui.spacing().menu_margin.sum().y + 2.0 + 2.0 * MENU_EDGE;
|
||||
let room = (crate::work_area::visible_rect(ui.ctx()).height() - frame).max(MENU_MIN_HEIGHT);
|
||||
// An overflowing menu gets Photoshop's scroll arrows above and below its rows (#2091): the
|
||||
// thin floating scroll bar alone gave no hint that more items were hidden. Whether it
|
||||
// overflows is known only after layout, so it is remembered from the last frame.
|
||||
let id = ui.scope_id().with("menu_scroll");
|
||||
let overflow = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);
|
||||
let offset = ui.data(|d| d.get_temp::<f32>(id.with("offset"))).unwrap_or(0.0);
|
||||
// The arrows are as wide as the rows were last frame, not the popup's whole available width:
|
||||
// that widened an overflowing menu on every later open (a layer menu went from ~230 to ~600
|
||||
// pt). The output's `inner_rect` is the width asked for, before auto-shrink fits the rows.
|
||||
let width = ui.data(|d| d.get_temp::<f32>(id.with("width"))).unwrap_or(0.0);
|
||||
// The arrows come out of the room, so both stay on screen: the minimum is the whole menu's
|
||||
// height, arrows included. `room` is at least `MENU_MIN_HEIGHT`, which is taller than the two
|
||||
// arrows, so the rows always keep a positive height; a window shorter than that minimum still
|
||||
// gets a menu of that height, as one without arrows does.
|
||||
let arrows = if overflow { 2.0 * MENU_ARROW_HEIGHT } else { 0.0 };
|
||||
let room = (room - arrows).max(MENU_MIN_HEIGHT - arrows);
|
||||
// The arrows sit flush against the rows, so no item spacing is added around them that `room`
|
||||
// doesn't count; the rows keep the menu's own spacing.
|
||||
let spacing = ui.spacing().item_spacing.y;
|
||||
ui.spacing_mut().item_spacing.y = 0.0;
|
||||
let mut step = 0.0;
|
||||
if overflow {
|
||||
step += menu_scroll_arrow(ui, true, offset > 0.5, width);
|
||||
}
|
||||
// A popup's Ui is only as tall as the popup was last frame (400 pt on the first), so ask for
|
||||
// the whole room: the area still shrinks to its rows when they need less.
|
||||
egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).show(ui, add_contents).inner
|
||||
let mut area = egui::ScrollArea::vertical().id_salt(id).max_height(room).min_scrolled_height(room);
|
||||
// A step is taken on the pass after the arrow was hovered, and only then: a menu closed while
|
||||
// an arrow was hovered doesn't jump when it next opens.
|
||||
let now = ui.ctx().cumulative_pass_nr();
|
||||
let pending = ui.data(|d| d.get_temp::<(f32, u64)>(id.with("step"))).filter(|&(_, pass)| pass.saturating_add(1) == now).map_or(0.0, |(step, _)| step);
|
||||
if pending != 0.0 {
|
||||
area = area.vertical_scroll_offset((offset + pending).max(0.0));
|
||||
}
|
||||
let out = area.show(ui, |ui| {
|
||||
ui.spacing_mut().item_spacing.y = spacing;
|
||||
add_contents(ui)
|
||||
});
|
||||
let max = (out.content_size.y - out.inner_rect.height()).max(0.0);
|
||||
let offset = out.state.clamped_offset().y.clamp(0.0, max);
|
||||
if overflow {
|
||||
step += menu_scroll_arrow(ui, false, offset < max - 0.5, width);
|
||||
}
|
||||
ui.spacing_mut().item_spacing.y = spacing;
|
||||
ui.data_mut(|d| {
|
||||
d.insert_temp(id, max > 0.5);
|
||||
d.insert_temp(id.with("offset"), offset);
|
||||
d.insert_temp(id.with("width"), out.content_size.x);
|
||||
d.insert_temp(id.with("step"), (step, now));
|
||||
});
|
||||
out.inner
|
||||
}
|
||||
|
||||
/// Gap kept between a context menu and the window's edges, and the shortest it gets.
|
||||
const MENU_EDGE: f32 = 4.0;
|
||||
/// One scroll arrow of an overflowing menu: hovering scrolls that way, as in Photoshop's and the
|
||||
/// system menus. It doesn't page on a click: egui closes a context menu on any click inside it,
|
||||
/// so the page would never be seen. `width` is the rows' width. Returns the scroll step for the
|
||||
/// next frame.
|
||||
fn menu_scroll_arrow(ui: &mut Ui, up: bool, enabled: bool, width: f32) -> f32 {
|
||||
let width = if width.is_finite() { width.max(MENU_ARROW_HEIGHT) } else { MENU_ARROW_HEIGHT };
|
||||
let (rect, resp) = ui.allocate_exact_size(vec2(width, MENU_ARROW_HEIGHT), Sense::hover());
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let color = if enabled { t.text } else { t.text_dim.gamma_multiply(0.5) };
|
||||
let (c, h) = (rect.center(), 3.5);
|
||||
let pts = if up {
|
||||
vec![pos2(c.x - h * 1.4, c.y + h * 0.6), pos2(c.x + h * 1.4, c.y + h * 0.6), pos2(c.x, c.y - h * 0.8)]
|
||||
} else {
|
||||
vec![pos2(c.x - h * 1.4, c.y - h * 0.6), pos2(c.x + h * 1.4, c.y - h * 0.6), pos2(c.x, c.y + h * 0.8)]
|
||||
};
|
||||
ui.painter().add(egui::Shape::convex_polygon(pts, color, Stroke::NONE));
|
||||
if !enabled {
|
||||
return 0.0;
|
||||
}
|
||||
if !resp.hovered() {
|
||||
return 0.0;
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
let sign = if up { -1.0 } else { 1.0 };
|
||||
sign * MENU_ARROW_SPEED * ui.input(|i| i.stable_dt).clamp(0.0, 0.1)
|
||||
}
|
||||
|
||||
const MENU_MIN_HEIGHT: f32 = 120.0;
|
||||
/// Gap kept between a context menu and the window's edges.
|
||||
const MENU_EDGE: f32 = 4.0;
|
||||
/// The shortest a context menu gets, scroll arrows included.
|
||||
pub(super) const MENU_MIN_HEIGHT: f32 = 120.0;
|
||||
/// Height of an overflowing menu's scroll arrows, and how fast hovering one scrolls (points per
|
||||
/// second).
|
||||
pub(super) const MENU_ARROW_HEIGHT: f32 = 14.0;
|
||||
const MENU_ARROW_SPEED: f32 = 400.0;
|
||||
|
||||
/// The colour picker popup of a colour swatch: a click on `swatch` toggles it, a click outside
|
||||
/// closes it. While open, its left edge stays where it first showed (at the swatch, or further
|
||||
|
||||
@@ -1443,6 +1443,144 @@ fn the_wheel_leaves_a_plain_dropdown_alone() {
|
||||
assert_eq!(*h.state(), 0);
|
||||
}
|
||||
|
||||
/// The middle of an overflowing menu's lower scroll arrow, from the menu's laid-out rect.
|
||||
fn lower_menu_arrow(menu: egui::Rect) -> egui::Pos2 {
|
||||
let half = super::dropdown::MENU_ARROW_HEIGHT / 2.0;
|
||||
egui::pos2(menu.left() + half, menu.bottom() - half)
|
||||
}
|
||||
|
||||
/// #2091: a menu taller than the window shows scroll arrows; hovering the lower one scrolls
|
||||
/// it, and a short menu gets none.
|
||||
#[test]
|
||||
fn overflowing_menus_get_scroll_arrows_that_scroll_on_hover() {
|
||||
// (rows, overflowing, scroll offset, the menu's rect)
|
||||
type S = (usize, bool, f32, egui::Rect);
|
||||
let run = |rows: usize| {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state(
|
||||
|ui, s: &mut S| {
|
||||
let id = ui.scope_id().with("menu_scroll");
|
||||
super::menu_scroll(ui, |ui| {
|
||||
for i in 0..s.0 {
|
||||
ui.label(format!("Item {i}"));
|
||||
}
|
||||
});
|
||||
s.1 = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);
|
||||
s.2 = ui.data(|d| d.get_temp::<f32>(id.with("offset"))).unwrap_or(0.0);
|
||||
s.3 = ui.min_rect();
|
||||
},
|
||||
(rows, false, 0.0, egui::Rect::NOTHING),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h
|
||||
};
|
||||
let short = run(3);
|
||||
assert!(!short.state().1, "a short menu has no arrows");
|
||||
let mut long = run(80);
|
||||
assert!(long.state().1, "a long menu overflows");
|
||||
assert_eq!(long.state().2, 0.0);
|
||||
let below = lower_menu_arrow(long.state().3);
|
||||
long.event(egui::Event::PointerMoved(below));
|
||||
long.run_steps(10);
|
||||
assert!(long.state().2 > 0.0, "hovering the lower arrow scrolls down");
|
||||
}
|
||||
|
||||
/// #2091: the step a hovered arrow leaves for the next frame isn't taken when a menu closed
|
||||
/// while hovering it opens again.
|
||||
#[test]
|
||||
fn a_reopened_menu_takes_no_stale_scroll_step() {
|
||||
// (shown, scroll offset, the menu's rect)
|
||||
type S = (bool, f32, egui::Rect);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(220.0, 300.0)).build_ui_state(
|
||||
|ui, s: &mut S| {
|
||||
let id = ui.scope_id().with("menu_scroll");
|
||||
if s.0 {
|
||||
super::menu_scroll(ui, |ui| {
|
||||
for i in 0..80 {
|
||||
ui.label(format!("Item {i}"));
|
||||
}
|
||||
});
|
||||
s.2 = ui.min_rect();
|
||||
}
|
||||
s.1 = ui.data(|d| d.get_temp::<f32>(id.with("offset"))).unwrap_or(0.0);
|
||||
},
|
||||
(true, 0.0, egui::Rect::NOTHING),
|
||||
);
|
||||
h.run_steps(3);
|
||||
h.event(egui::Event::PointerMoved(lower_menu_arrow(h.state().2)));
|
||||
h.run_steps(3);
|
||||
let offset = h.state().1;
|
||||
assert!(offset > 0.0, "hovering the lower arrow scrolls down");
|
||||
h.state_mut().0 = false;
|
||||
h.run();
|
||||
h.state_mut().0 = true;
|
||||
h.event(egui::Event::PointerGone);
|
||||
h.run();
|
||||
assert_eq!(h.state().1, offset, "the reopened menu stays where it was left");
|
||||
}
|
||||
|
||||
/// #2091: an overflowing menu's scroll arrows are as wide as its rows, so they don't widen the
|
||||
/// menu to the whole width it is offered.
|
||||
#[test]
|
||||
fn menu_scroll_arrows_do_not_widen_the_menu() {
|
||||
// (overflowing, width of the menu)
|
||||
type S = (bool, f32);
|
||||
let mut h = Harness::builder().with_size(egui::vec2(600.0, 300.0)).build_ui_state(
|
||||
|ui, s: &mut S| {
|
||||
let id = ui.scope_id().with("menu_scroll");
|
||||
super::menu_scroll(ui, |ui| {
|
||||
for i in 0..80 {
|
||||
ui.label(format!("Item {i}"));
|
||||
}
|
||||
});
|
||||
s.0 = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);
|
||||
s.1 = ui.min_rect().width();
|
||||
},
|
||||
(false, 0.0),
|
||||
);
|
||||
h.run_steps(4);
|
||||
assert!(h.state().0, "the menu overflows");
|
||||
assert!(h.state().1 < 200.0, "the arrows follow the rows' width, not the 600 pt window: {}", h.state().1);
|
||||
}
|
||||
|
||||
/// #2091: in a short window, between the shortest menu and that plus its arrows, an overflowing
|
||||
/// menu's arrows come out of the room rather than being added under it, so the lower arrow stays
|
||||
/// on screen. A window shorter than a menu's minimum gets a menu of the minimum height, arrows
|
||||
/// included.
|
||||
#[test]
|
||||
fn menu_scroll_arrows_stay_inside_a_short_window() {
|
||||
// (overflowing, the menu's rect)
|
||||
type S = (bool, egui::Rect);
|
||||
let run = |height: f32| {
|
||||
let mut h = Harness::builder().with_size(egui::vec2(220.0, height)).build_ui_state(
|
||||
|ui, s: &mut S| {
|
||||
let id = ui.scope_id().with("menu_scroll");
|
||||
super::menu_scroll(ui, |ui| {
|
||||
for i in 0..80 {
|
||||
ui.label(format!("Item {i}"));
|
||||
}
|
||||
});
|
||||
s.0 = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);
|
||||
s.1 = ui.min_rect();
|
||||
},
|
||||
(false, egui::Rect::NOTHING),
|
||||
);
|
||||
h.run_steps(4);
|
||||
let screen = h.ctx.content_rect();
|
||||
(h.state().0, h.state().1, screen)
|
||||
};
|
||||
// The room is 150 - 22 (the popup frame and edge gaps) = 128 pt: more than the shortest menu,
|
||||
// less than it plus both 14 pt arrows.
|
||||
let (overflow, menu, screen) = run(150.0);
|
||||
assert!(overflow, "the menu overflows and shows its arrows");
|
||||
assert!(menu.top() >= screen.top(), "the upper arrow is on screen: {menu:?} in {screen:?}");
|
||||
assert!(menu.bottom() <= screen.bottom(), "the lower arrow is on screen: {menu:?} in {screen:?}");
|
||||
assert!(menu.height() <= 128.5, "the menu, arrows included, fits the room: {}", menu.height());
|
||||
let (overflow, menu, _) = run(60.0);
|
||||
assert!(overflow, "a tiny window's menu overflows too");
|
||||
let min = super::dropdown::MENU_MIN_HEIGHT;
|
||||
assert!((menu.height() - min).abs() < 0.5, "a tiny window's menu is the minimum height, arrows included: {}", menu.height());
|
||||
}
|
||||
|
||||
/// [`MODES`] in a wheel dropdown whose list draws a line above each option `starts_group` picks,
|
||||
/// opened: the open list's rect and each option's row in it.
|
||||
fn open_grouped_modes(starts_group: fn(&usize) -> bool) -> (egui::Rect, Vec<egui::Rect>) {
|
||||
|
||||
@@ -108,6 +108,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|
||||
- Preferences (`ui.menu.invoke {id: "edit.preferences.interface"}`) exposes the sections in its `values` field. Apply (`ui.dialog.apply`) and OK (`ui.dialog.confirm`) on Preferences are refused over control because automation denies whole-preferences updates and filesystem-bearing preference sections. A refused `ui.dialog.apply` returns an error and keeps the dialog open; a refused `ui.dialog.confirm` returns an error but closes and removes the dialog. `ui.dialog.cancel` closes the dialog without saving. Individual safe preferences can instead be changed with `engine.execute` using `prefs.set` (e.g. `{"command": "prefs.set", "params": {"path": "interface.showTooltips", "value": false}}`). Settings marked for the next launch still require a restart.
|
||||
- Select › Select and Mask… (`ui.menu.invoke {id: "select.selectAndMask"}`, Ctrl+Alt+R) opens Photoshop's workspace; `ui.inspect` reports it as `distort.selectAndMask`. Drive it with `ui.menu.invoke {id: "select.selectAndMask", params: {ui: {…}}}`: `tool` (`quick|refineEdge|brush|object|lasso|polygonalLasso|hand|zoom`), `mode` (`add|subtract`), `size`, `hardness`, `sampleAllLayers`, `hideView` (true shows the image without the view, as holding X does), `stroke: {points: [[x,y],…], alt?}` (a drag with the current tool in document px: Object Selection takes a click or the rectangle's corners, the lassos the polygon), `selectSubject`, `clearSelection`, `invert`, the settings (`view`, `opacity`, `showEdge`, `showOriginal`, `realTimeRefinement`, `highQualityPreview`, `overlayColor`, `indicates`, `radius`, `smartRadius`, `smooth`, `feather`, `contrast`, `shiftEdge`, `decontaminate`, `amount`, `output`, `remember`), `undo`, `redo`, `reset`, `waitPreview`, `commit` (OK: `select.refineEdge` with the workspace's `edits` and `refineStrokes`, one history step) and `cancel`. The reply describes the workspace (`edits`, `strokes`, `selectedProxyPixels`, `previewReady`, …).
|
||||
- Edit › Fill… (`ui.menu.invoke {id: "edit.fill"}`, Shift+F5, Shift+Backspace) opens the Fill dialog; its fields are `edit.fill`'s params (`contents`, `color`, `pattern`, `colorAdaptation`, `mode`, `opacity`, `preserveTransparency`), and OK remembers them in the preferences (`dialogs["edit.fill"]`).
|
||||
- Image › Adjustments › Levels… (`ui.menu.invoke {id: "image.adjustments.levels"}`): `__clipping` (`"shadows"` or `"highlights"`; `null` turns it off) shows Photoshop's clipping display on the canvas instead of the preview, what the black or white Input slider clips. The app sets it while Alt and the mouse button are held on one of those sliders; it never reaches OK. The display shows only for RGB and Grayscale documents whose target is a raster layer's pixels, on the main canvas. Other targets (CMYK or Lab documents, a channel, mask or Quick Mask target, a non-pixel layer, a Smart Filter) accept the value and keep the normal preview.
|
||||
- Save for Web (`ui.menu.invoke {id: "file.export.saveForWebLegacy"}`) is resizable with independently scrolling settings. Dialog fields `__view` (`original|optimized|2up|4up`), `__zoom` (`null` = Fit, otherwise a factor; 1 = 100% in physical display pixels), and `__center: [u,v]` control the shared preview navigation. `__previewRects` reports pane rectangles in screen points. Drag a preview to pan, scroll/pinch to zoom at the pointer, or double-click to fit. GIF/PNG-8 expose `colorTable: ["#rrggbb", …]` (opaque source entries) and `colorTableEdits: {"0":"#rrggbb", …}` (zero-based replacements after quantization). A swatch opens a color picker; edits update the preview and saved file without remapping pixel indices or changing the document. Reset clears replacements. Changing palette/size/matte/transparency settings regenerates the table and clears index-based edits. Previews and generated tables use a bounded 2048-pixel proxy; full-size export uses that explicit table unchanged. `__paletteApproximate` reports proxy-derived palette generation, and enlarged proxy previews are labelled. The engine export command accepts the same table/edit parameters; its no-path estimate returns the source `colorTable` and `transparentIndex` as well as size statistics. Opening a new dialog does not carry a previous image's table across. Image Size has `width` and `height` (px), `percent` and `resample` (`nearest|bilinear|bicubic|bicubicSmoother|bicubicSharper`, default `bicubic`); `__constrain` (default true at each opening) links the two sides in proportion. A side edit sets both sides and removes `percent`, which the export command otherwise applies first; a Percent edit sets both sides from it. Each opening starts at the document's full size, while `resample` is remembered with the encoding choices. The document is never resized.
|
||||
- A pixel tool pressed on a type, shape, Smart Object or fill layer (e.g. through `ui.pointer`) opens the "Rasterize?" prompt instead of painting: a dialog with `__rasterize` (`type|shape|smartObject|fill`), `message`, `layer`, `tool` and `at`. `ui.dialog.confirm` runs the `layer.rasterize.*` command and then paints at `at` (two history states, `{"rasterized", "painted"}`); `ui.dialog.cancel` does nothing.
|
||||
- Edit › Transform › Warp on editable type (`ui.menu.invoke {"id":"edit.transform.warp"}`, or the warp toggle of an open transform box) opens Warp mode with no prompt, as in Photoshop: the mesh can't be dragged or split, only the options bar's warp style, Bend, H and V apply, and the commit sets the layer's Warp Text in one step, so the type stays editable. Directly: `engine.execute {"command":"edit.transform.warp","params":{"style":"flag","bend":40}}` on a type layer. Distort and Perspective stay greyed for type.
|
||||
|
||||
Reference in new issue
Block a user