mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge PR #9139: Rebuild the Histogram panel
# Conflicts: # crates/ui-egui/src/control.rs # docs/scorecard.md # docs/ui-parity.md
This commit is contained in:
commit
ff479a2c01
14 files changed
+1491
-269
No files matched your search
@@ -350,8 +350,14 @@ pub struct UiSetParams {
|
||||
/// "mode"), kinds (a list of layer kinds), name (matches part of the layer name) and mode (a
|
||||
/// blend mode name) for the Layers panel filter). strokeTrace (true, false, "stderr" or "off":
|
||||
/// the stroke latency trace at runtime; a CSV file is set at launch with --stroke-trace, not
|
||||
/// over this channel). updatesOpen (bool, the Help › Check for Updates window). Other fields
|
||||
/// are an error.
|
||||
/// over this channel). updatesOpen (bool, the Help › Check for Updates window).
|
||||
/// histogramPanel (an object patching view ("compact", "expanded" or "allChannels"), channel
|
||||
/// ("composite", "red", "green", "blue", "cyan", "magenta", "yellow", "black", "a", "b",
|
||||
/// "luminosity" or "colors"), showChannelsInColor, showStatistics and source ("entireImage",
|
||||
/// "selectedLayer" or "adjustmentComposite") for the Histogram panel), histogramRange ([from,
|
||||
/// to] levels 0..255 whose Count and Percentile the panel shows, or null) and histogramRefresh
|
||||
/// (true: an Uncached Refresh); `ui.inspect` reports them and the statistics under
|
||||
/// `histogram`. Other fields are an error.
|
||||
pub fields: Value,
|
||||
}
|
||||
|
||||
|
||||
@@ -556,7 +556,11 @@ pub struct Performance {
|
||||
pub memory_usage_mb: u32,
|
||||
/// Undo steps kept per document (History panel states).
|
||||
pub history_states: u32,
|
||||
/// Display cache levels (mip levels kept for zoomed-out views).
|
||||
/// Cache Levels, 1–8: the highest cache level the Histogram panel counts a large document at
|
||||
/// (level n counts a proxy 2^(n-1) times smaller; 1 counts every pixel). Lower is more
|
||||
/// accurate, higher faster. The panel picks the level from the document's size up to this;
|
||||
/// the web build, which counts on the UI thread, reduces documents from a quarter of the size
|
||||
/// the desktop does. Uncached Refresh always counts at level 1.
|
||||
pub cache_levels: u32,
|
||||
/// Side of the GPU canvas texture tiles, in pixels (applies at next launch).
|
||||
pub cache_tile_size: u32,
|
||||
@@ -1156,7 +1160,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[
|
||||
"general.colorPicker",
|
||||
"workspace.autoShowHiddenPanels",
|
||||
"workspace.enableFloatingDocumentWindowDocking",
|
||||
"performance.cacheLevels",
|
||||
"performance.effectCacheMb",
|
||||
"performance.legacyCompositing",
|
||||
"scratchDisks.disks",
|
||||
|
||||
@@ -133,7 +133,7 @@ pub enum Outcome {
|
||||
/// field's value is validated before the first one is applied, so a typo, an unknown field, a
|
||||
/// bad value or a bad nested key can't reply with success while nothing — or only half of it —
|
||||
/// changed (#412).
|
||||
pub const UI_SET_FIELDS: [&str; 40] = [
|
||||
pub const UI_SET_FIELDS: [&str; 43] = [
|
||||
"updatesOpen",
|
||||
"tool",
|
||||
"strokeTrace",
|
||||
@@ -174,6 +174,9 @@ pub const UI_SET_FIELDS: [&str; 40] = [
|
||||
"camTransformOnDrop",
|
||||
"tileGrid",
|
||||
"layerFilter",
|
||||
"histogramPanel",
|
||||
"histogramRange",
|
||||
"histogramRefresh",
|
||||
];
|
||||
|
||||
/// Most clicks one `ui.click` may queue (#982). Each click is a press and a release that the app
|
||||
@@ -592,6 +595,17 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
if crop_shield.as_ref().is_some_and(|s| !(0.0..=100.0).contains(&s.opacity)) {
|
||||
return Err("cropShield.opacity must be 0..100".into());
|
||||
}
|
||||
// The Histogram panel: its options, the dragged tonal range ([from, to] levels or
|
||||
// null) and Uncached Refresh.
|
||||
let histogram_panel = merged_object(&app.ui.histogram_panel, p.get("histogramPanel"), "histogramPanel")?;
|
||||
let histogram_range = match p.get("histogramRange") {
|
||||
Some(v) => Some(
|
||||
serde_json::from_value::<Option<[u8; 2]>>(v.clone())
|
||||
.map_err(|_| "histogramRange must be [from, to] levels 0..255, or null".to_string())?,
|
||||
),
|
||||
None => None,
|
||||
};
|
||||
let histogram_refresh = bool_field(p, "histogramRefresh")?;
|
||||
let panels = merged_object(&app.ui.panels, p.get("panels"), "panels")?;
|
||||
let mask_target = bool_field(p, "maskTarget")?;
|
||||
let updates_open = bool_field(p, "updatesOpen")?;
|
||||
@@ -751,6 +765,16 @@ fn dispatch(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest)
|
||||
if let Some(f) = layer_filter {
|
||||
crate::layer_filter_ui::apply(&mut app.ui, f);
|
||||
}
|
||||
if let Some(h) = histogram_panel {
|
||||
app.ui.histogram_panel = h;
|
||||
crate::histogram_panel::persist_options(app);
|
||||
}
|
||||
if let Some(r) = histogram_range {
|
||||
app.ui.histogram_range = r;
|
||||
}
|
||||
if histogram_refresh == Some(true) {
|
||||
crate::histogram_panel::uncached_refresh(app);
|
||||
}
|
||||
if let Some(k) = crop_overlay {
|
||||
app.ui.tool_options.crop_overlay = k;
|
||||
}
|
||||
@@ -1456,6 +1480,7 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
|
||||
"brush": {"size": app.session.tools.brush.size, "hardness": app.session.tools.brush.hardness, "opacity": app.session.tools.brush.opacity},
|
||||
"distort": app.distort.describe(),
|
||||
"jobs": crate::jobs_ui::inspect(app),
|
||||
"histogram": crate::histogram_panel::inspect(app),
|
||||
"cameraRaw": app.camera_raw.as_ref().map(|d| d.describe(&app.ui.camera_raw_scope, &app.ui.camera_raw_preview)),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -642,6 +642,10 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, shown: &[Group], mut bod
|
||||
crate::brush_panel::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
if tabs.get(sel) == Some(&"Histogram") {
|
||||
crate::histogram_panel::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
if tabs.get(sel) == Some(&"Actions") {
|
||||
crate::actions::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
|
||||
@@ -0,0 +1,869 @@
|
||||
//! Histogram panel (Window › Histogram): Compact, Expanded and All Channels
|
||||
//! views, a channel and a source selector, statistics for the level under the pointer or a
|
||||
//! dragged tonal range, the cached-data warning and Uncached Refresh, and the adjusted histogram
|
||||
//! over the original while an adjustment previews.
|
||||
//!
|
||||
//! Histograms are counted off the UI thread (`tone::compute_histograms_at`) for the document
|
||||
//! revision, source and preview they describe, and kept until one of those changes; the panel
|
||||
//! shows the last one with the cached-data warning until the new one lands.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Rect, Sense, pos2, vec2};
|
||||
use photocraft_color::ColorMode;
|
||||
use photocraft_doc::adjust::ToneSpace;
|
||||
use photocraft_doc::{DocId, Document, LayerContent};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::theme::Tokens;
|
||||
use crate::tone::{self, HistSource, Histograms};
|
||||
|
||||
/// Where the panel options are kept between launches (`prefs.dialogs`).
|
||||
const OPTIONS_PREF: &str = "histogramPanel";
|
||||
|
||||
/// The panel's view (its menu's Compact / Expanded / All Channels View).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HistView {
|
||||
/// The histogram alone, of the entire image (Photoshop's default view).
|
||||
#[default]
|
||||
Compact,
|
||||
/// The histogram with the channel and source selectors, refresh and statistics.
|
||||
Expanded,
|
||||
/// Expanded, plus one histogram per colour channel (no alpha, spot or mask channels).
|
||||
AllChannels,
|
||||
}
|
||||
|
||||
/// The Channel menu. Which entries a document offers depends on its colour mode
|
||||
/// ([`channel_options`]); one it lacks shows as its composite.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HistChannel {
|
||||
/// RGB, CMYK, Lab's Lightness or Gray.
|
||||
#[default]
|
||||
Composite,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
Cyan,
|
||||
Magenta,
|
||||
Yellow,
|
||||
Black,
|
||||
A,
|
||||
B,
|
||||
Luminosity,
|
||||
/// The colour channels overlaid in their colours.
|
||||
Colors,
|
||||
}
|
||||
|
||||
/// What the histogram counts (the Source menu, shown for documents with several layers).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum HistSourceChoice {
|
||||
/// The composite of every layer.
|
||||
#[default]
|
||||
EntireImage,
|
||||
/// The selected layer on its own.
|
||||
SelectedLayer,
|
||||
/// The selected adjustment layer and every layer beneath it.
|
||||
AdjustmentComposite,
|
||||
}
|
||||
|
||||
/// The panel options (its menu and selectors), kept between launches.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct HistogramPanelState {
|
||||
pub view: HistView,
|
||||
/// Kept when the view changes (Expanded ↔ All Channels); in All Channels View it picks only
|
||||
/// the top histogram.
|
||||
pub channel: HistChannel,
|
||||
/// Show Channels in Color: single channels in Expanded and All Channels View in their colour
|
||||
/// (Compact View always colours them; Colors is always in colour).
|
||||
pub show_channels_in_color: bool,
|
||||
pub show_statistics: bool,
|
||||
pub source: HistSourceChoice,
|
||||
}
|
||||
|
||||
impl Default for HistogramPanelState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
view: HistView::Compact,
|
||||
channel: HistChannel::Composite,
|
||||
show_channels_in_color: false,
|
||||
show_statistics: true,
|
||||
source: HistSourceChoice::EntireImage,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves the panel options with the preferences.
|
||||
pub fn persist_options(app: &mut PhotocraftApp) {
|
||||
if let Ok(value) = serde_json::to_value(app.ui.histogram_panel) {
|
||||
app.session.prefs.edit(|p| {
|
||||
p.dialogs.insert(OPTIONS_PREF.into(), value);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores the saved panel options; unreadable ones keep the defaults.
|
||||
pub fn restore_options(app: &mut PhotocraftApp) {
|
||||
if let Some(v) = app.session.prefs().dialogs.get(OPTIONS_PREF)
|
||||
&& let Ok(state) = serde_json::from_value(v.clone())
|
||||
{
|
||||
app.ui.histogram_panel = state;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Channels
|
||||
|
||||
/// The channels a document in `mode` offers, with their labels, in menu order.
|
||||
pub fn channel_options(mode: ColorMode) -> Vec<(HistChannel, &'static str)> {
|
||||
use HistChannel::*;
|
||||
match tone_space(mode) {
|
||||
_ if gray(mode) => vec![(Composite, "Gray")],
|
||||
ToneSpace::Cmyk => vec![
|
||||
(Composite, "CMYK"),
|
||||
(Cyan, "Cyan"),
|
||||
(Magenta, "Magenta"),
|
||||
(Yellow, "Yellow"),
|
||||
(Black, "Black"),
|
||||
(Luminosity, "Luminosity"),
|
||||
(Colors, "Colors"),
|
||||
],
|
||||
ToneSpace::Lab => vec![(Composite, "Lightness"), (A, "a"), (B, "b"), (Luminosity, "Luminosity")],
|
||||
ToneSpace::Rgb => vec![(Composite, "RGB"), (Red, "Red"), (Green, "Green"), (Blue, "Blue"), (Luminosity, "Luminosity"), (Colors, "Colors")],
|
||||
}
|
||||
}
|
||||
|
||||
fn gray(mode: ColorMode) -> bool {
|
||||
matches!(mode, ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone)
|
||||
}
|
||||
|
||||
/// The space the panel counts a document of `mode` in.
|
||||
pub fn tone_space(mode: ColorMode) -> ToneSpace {
|
||||
photocraft_engine::adjust_params::default_space(mode)
|
||||
}
|
||||
|
||||
/// `want`, or the composite when a document of `mode` doesn't have it.
|
||||
pub fn resolve_channel(mode: ColorMode, want: HistChannel) -> HistChannel {
|
||||
if channel_options(mode).iter().any(|(c, _)| *c == want) { want } else { HistChannel::Composite }
|
||||
}
|
||||
|
||||
/// The single colour channels of a document of `mode` (All Channels View; Colors overlays them).
|
||||
pub fn color_channels(mode: ColorMode) -> &'static [HistChannel] {
|
||||
use HistChannel::*;
|
||||
match tone_space(mode) {
|
||||
_ if gray(mode) => &[],
|
||||
ToneSpace::Cmyk => &[Cyan, Magenta, Yellow, Black],
|
||||
ToneSpace::Lab => &[A, B],
|
||||
ToneSpace::Rgb => &[Red, Green, Blue],
|
||||
}
|
||||
}
|
||||
|
||||
/// The 256 bins of `channel` in `h` (counted in the space of a document of `mode`).
|
||||
pub fn bins(h: &Histograms, mode: ColorMode, channel: HistChannel) -> &[u32; 256] {
|
||||
use HistChannel::*;
|
||||
let i = match (tone_space(mode), channel) {
|
||||
(_, Luminosity) => return &h.lum,
|
||||
(ToneSpace::Rgb, Red) | (ToneSpace::Cmyk, Cyan) | (ToneSpace::Lab, A) => 1,
|
||||
(ToneSpace::Rgb, Green) | (ToneSpace::Cmyk, Magenta) | (ToneSpace::Lab, B) => 2,
|
||||
(ToneSpace::Rgb, Blue) | (ToneSpace::Cmyk, Yellow) => 3,
|
||||
(ToneSpace::Cmyk, Black) => 4,
|
||||
_ => 0,
|
||||
};
|
||||
&h[i]
|
||||
}
|
||||
|
||||
/// The label a channel is listed under in a document of `mode`.
|
||||
pub fn channel_label(mode: ColorMode, channel: HistChannel) -> &'static str {
|
||||
channel_options(mode).into_iter().find(|(c, _)| *c == channel).map_or("", |(_, l)| l)
|
||||
}
|
||||
|
||||
/// The id of a channel (`ui.inspect`, the serde name).
|
||||
fn channel_id(channel: HistChannel) -> String {
|
||||
serde_json::to_value(channel).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The colour a single channel draws in (saturated, as in All Channels View).
|
||||
pub fn channel_paint(channel: HistChannel) -> Option<Color32> {
|
||||
use HistChannel::*;
|
||||
Some(match channel {
|
||||
Red => Color32::from_rgb(235, 30, 30),
|
||||
Green => Color32::from_rgb(30, 235, 30),
|
||||
Blue => Color32::from_rgb(40, 40, 240),
|
||||
Cyan => Color32::from_rgb(0, 200, 235),
|
||||
Magenta => Color32::from_rgb(230, 0, 160),
|
||||
Yellow => Color32::from_rgb(240, 220, 0),
|
||||
Black => Color32::from_gray(110),
|
||||
A => Color32::from_rgb(220, 90, 140),
|
||||
B => Color32::from_rgb(200, 180, 60),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The level of `channel` at a straight RGBA 0..1 pixel, as the histogram bins it (the Color
|
||||
/// Sampler marks).
|
||||
pub fn channel_level(mode: ColorMode, channel: HistChannel, rgba: [f32; 4]) -> u8 {
|
||||
use HistChannel::*;
|
||||
let rgb = [rgba[0], rgba[1], rgba[2]].map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) });
|
||||
let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
let lum = || q(rgb.iter().zip(tone::LUMINOSITY).map(|(v, w)| v * w).sum());
|
||||
match (tone_space(mode), channel) {
|
||||
(_, Luminosity) => lum(),
|
||||
(ToneSpace::Rgb, Red) => q(rgb[0]),
|
||||
(ToneSpace::Rgb, Green) => q(rgb[1]),
|
||||
(ToneSpace::Rgb, Blue) => q(rgb[2]),
|
||||
(ToneSpace::Rgb, _) => ((u16::from(q(rgb[0])) + u16::from(q(rgb[1])) + u16::from(q(rgb[2]))) / 3) as u8,
|
||||
(ToneSpace::Cmyk, c) => {
|
||||
let ink = photocraft_color::convert::rgb_to_cmyk(rgb);
|
||||
let v = match c {
|
||||
Cyan => ink[0],
|
||||
Magenta => ink[1],
|
||||
Yellow => ink[2],
|
||||
Black => ink[3],
|
||||
_ => ink.iter().sum::<f32>() / 4.0,
|
||||
};
|
||||
q(1.0 - v)
|
||||
}
|
||||
(ToneSpace::Lab, c) => {
|
||||
let l = photocraft_color::convert::srgb_to_lab(rgb);
|
||||
match c {
|
||||
A => q((l[1] + 128.0) / 255.0),
|
||||
B => q((l[2] + 128.0) / 255.0),
|
||||
_ => q(l[0] / 100.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Statistics
|
||||
|
||||
/// The Histogram statistics. Mean, Std Dev, Median and Pixels describe the whole
|
||||
/// histogram; Level, Count and Percentile the level under the pointer or the dragged range.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Stats {
|
||||
pub mean: f64,
|
||||
pub std_dev: f64,
|
||||
pub median: u8,
|
||||
pub pixels: u64,
|
||||
/// The inspected levels, `lo..=hi` (one level when they are equal), if any.
|
||||
pub level: Option<[u8; 2]>,
|
||||
/// Pixels at the inspected levels.
|
||||
pub count: Option<u64>,
|
||||
/// Percent of the pixels at or below the inspected level; for a range, in it.
|
||||
pub percentile: Option<f64>,
|
||||
/// Percent of the pixels at 0 and at 255: shadow and highlight clipping.
|
||||
pub clipped: [f64; 2],
|
||||
}
|
||||
|
||||
/// The statistics of `h`, inspecting `levels` (a level or a range, in either order). None when
|
||||
/// nothing was counted.
|
||||
pub fn stats(h: &[u32; 256], levels: Option<[u8; 2]>) -> Option<Stats> {
|
||||
let n: u64 = h.iter().map(|v| u64::from(*v)).sum();
|
||||
if n == 0 {
|
||||
return None;
|
||||
}
|
||||
let nf = n as f64;
|
||||
let mean = h.iter().enumerate().map(|(i, v)| i as f64 * f64::from(*v)).sum::<f64>() / nf;
|
||||
let var = h.iter().enumerate().map(|(i, v)| (i as f64 - mean).powi(2) * f64::from(*v)).sum::<f64>() / nf;
|
||||
let mut acc = 0u64;
|
||||
let median = h
|
||||
.iter()
|
||||
.position(|v| {
|
||||
acc += u64::from(*v);
|
||||
acc * 2 >= n
|
||||
})
|
||||
.unwrap_or(0) as u8;
|
||||
let level = levels.map(|[a, b]| [a.min(b), a.max(b)]);
|
||||
let sum = |lo: u8, hi: u8| h.get(usize::from(lo)..=usize::from(hi)).map_or(0, |s| s.iter().map(|v| u64::from(*v)).sum::<u64>());
|
||||
let count = level.map(|[lo, hi]| sum(lo, hi));
|
||||
let percentile = level.map(|[lo, hi]| 100.0 * if lo == hi { sum(0, hi) } else { sum(lo, hi) } as f64 / nf);
|
||||
let clipped = [100.0 * f64::from(h[0]) / nf, 100.0 * f64::from(h[255]) / nf];
|
||||
Some(Stats { mean, std_dev: var.sqrt(), median, pixels: n, level, count, percentile, clipped })
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Computing and caching
|
||||
|
||||
/// What one panel histogram was counted from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct HistKey {
|
||||
pub doc: DocId,
|
||||
pub revision: u64,
|
||||
/// `tone::tag` of the source and space.
|
||||
pub source: u64,
|
||||
/// The adjustment preview's display key; 0 for the document itself.
|
||||
pub preview: u64,
|
||||
/// The highest cache level allowed (1: an Uncached Refresh).
|
||||
pub max_level: u32,
|
||||
}
|
||||
|
||||
/// A counted panel histogram.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PanelHist {
|
||||
pub key: HistKey,
|
||||
/// When it landed (ms), for throttling recounts while the document keeps changing.
|
||||
pub at: f64,
|
||||
pub hist: Arc<Histograms>,
|
||||
}
|
||||
|
||||
/// A histogram being counted off the UI thread: its key, and the receiver of (key, ms, result).
|
||||
pub(crate) type HistJob = (HistKey, std::sync::mpsc::Receiver<(HistKey, f64, Arc<Histograms>)>);
|
||||
|
||||
/// The source the panel counts for `choice` in `st`: Entire Image whenever the choice doesn't
|
||||
/// apply (a single layer, no selected layer, or Adjustment Composite without an adjustment layer
|
||||
/// selected).
|
||||
pub fn resolve_source(st: &photocraft_engine::DocState, choice: HistSourceChoice) -> (HistSourceChoice, HistSource) {
|
||||
if st.doc.layer_count() < 2 {
|
||||
return (HistSourceChoice::EntireImage, tone::IMAGE);
|
||||
}
|
||||
let selected = st.active_layer.and_then(|id| st.doc.layer(id));
|
||||
match (choice, selected) {
|
||||
(HistSourceChoice::SelectedLayer, Some(l)) => (choice, HistSource::Layer(l.id)),
|
||||
(HistSourceChoice::AdjustmentComposite, Some(l)) if matches!(l.content, LayerContent::Adjustment(_)) => (choice, HistSource::UpTo(l.id)),
|
||||
_ => (HistSourceChoice::EntireImage, tone::IMAGE),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether Adjustment Composite applies to `st` (an adjustment layer is selected).
|
||||
fn adjustment_selected(st: &photocraft_engine::DocState) -> bool {
|
||||
st.active_layer.and_then(|id| st.doc.layer(id)).is_some_and(|l| matches!(l.content, LayerContent::Adjustment(_)))
|
||||
}
|
||||
|
||||
/// Preferences › Performance › Cache Levels: the highest level the panel counts at by default.
|
||||
fn max_cache_level(app: &PhotocraftApp) -> u32 {
|
||||
app.session.prefs().performance.cache_levels.clamp(1, tone::MAX_CACHE_LEVEL)
|
||||
}
|
||||
|
||||
/// The source the panel counts: Compact View shows no Source menu and represents the entire image.
|
||||
fn source_choice(opts: &HistogramPanelState) -> HistSourceChoice {
|
||||
if opts.view == HistView::Compact { HistSourceChoice::EntireImage } else { opts.source }
|
||||
}
|
||||
|
||||
/// The key of the document's histogram the panel wants now, with the space and source it counts.
|
||||
fn committed_key(app: &PhotocraftApp) -> Option<(HistKey, ToneSpace, HistSource)> {
|
||||
let st = app.session.active()?;
|
||||
let (doc, revision) = (st.doc.id, st.revision);
|
||||
let space = tone_space(st.doc.mode);
|
||||
let (_, source) = resolve_source(st, source_choice(&app.ui.histogram_panel));
|
||||
let max_level = if app.hist_uncached == Some((doc, revision)) { 1 } else { max_cache_level(app) };
|
||||
Some((HistKey { doc, revision, source: tone::tag(source, space), preview: 0, max_level }, space, source))
|
||||
}
|
||||
|
||||
/// The document an open adjustment previews on the canvas (an Image › Adjustments dialog through
|
||||
/// its preview layer, or an adjustment layer's Properties drag) and its display key.
|
||||
fn adjustment_preview(app: &mut PhotocraftApp) -> Option<(Arc<Document>, u64)> {
|
||||
let idx = app.session.active_index()?;
|
||||
if let Some(shown) = crate::adjust_preview::display_doc(app, idx) {
|
||||
return Some(shown);
|
||||
}
|
||||
app.live_adjust.as_ref()?;
|
||||
let (doc, key) = crate::canvas::display_doc(app, idx);
|
||||
(key != 0).then_some((doc, key))
|
||||
}
|
||||
|
||||
/// What the panel wants shown now: the document's histogram key, and the preview's document and
|
||||
/// key while an adjustment previews.
|
||||
struct Want {
|
||||
committed: HistKey,
|
||||
preview: Option<(Arc<Document>, HistKey)>,
|
||||
space: ToneSpace,
|
||||
source: HistSource,
|
||||
}
|
||||
|
||||
fn want(app: &mut PhotocraftApp) -> Option<Want> {
|
||||
let preview = adjustment_preview(app);
|
||||
let (committed, space, source) = committed_key(app)?;
|
||||
let preview = preview.map(|(d, k)| (d, HistKey { preview: k | 1, ..committed }));
|
||||
Some(Want { committed, preview, space, source })
|
||||
}
|
||||
|
||||
/// Brings the panel's histograms up to date as far as one frame should: lands a finished count,
|
||||
/// keeps entries a view-only revision didn't invalidate, and starts the next count (at most one at
|
||||
/// a time, at most every 250 ms per entry). `ctx` repaints when a worker delivers.
|
||||
pub fn update(app: &mut PhotocraftApp, ctx: &egui::Context) {
|
||||
// A finished worker lands its histogram in the slot its key names. A worker that died
|
||||
// without sending clears the job so the next frame schedules a new one.
|
||||
if let Some((_, rx)) = &app.hist_job {
|
||||
match rx.try_recv() {
|
||||
Ok((key, ms, hist)) => {
|
||||
app.perf.span("histogram", ms);
|
||||
// egui's clock works on every target; `gpu_canvas::now_ms` is always 0 on wasm32.
|
||||
let entry = PanelHist { key, at: ctx.input(|i| i.time) * 1000.0, hist };
|
||||
if key.preview == 0 {
|
||||
app.doc_hist = Some(entry);
|
||||
} else {
|
||||
app.doc_hist_preview = Some(entry);
|
||||
}
|
||||
app.hist_job = None;
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => app.hist_job = None,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
// A revision that changed no pixels (selecting a layer, say) keeps the histogram of the one
|
||||
// before (#125), and an Uncached Refresh with it.
|
||||
if let Some(st) = app.session.active()
|
||||
&& tone::view_only(st)
|
||||
{
|
||||
let (doc, rev) = (st.doc.id, st.revision);
|
||||
if app.hist_uncached == Some((doc, rev.wrapping_sub(1))) {
|
||||
app.hist_uncached = Some((doc, rev));
|
||||
}
|
||||
if let Some(e) = app.doc_hist.as_mut()
|
||||
&& e.key.doc == doc
|
||||
&& e.key.revision.wrapping_add(1) == rev
|
||||
{
|
||||
e.key.revision = rev;
|
||||
}
|
||||
}
|
||||
let Some(want) = want(app) else { return };
|
||||
if want.preview.is_none() {
|
||||
app.doc_hist_preview = None;
|
||||
}
|
||||
if app.hist_job.is_some() {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(30));
|
||||
return;
|
||||
}
|
||||
let now = ctx.input(|i| i.time) * 1000.0;
|
||||
let due = |e: &Option<PanelHist>| e.as_ref().is_none_or(|e| e.key.doc != want.committed.doc || now - e.at > 250.0);
|
||||
let stale = |e: &Option<PanelHist>, k: &HistKey| e.as_ref().is_none_or(|e| e.key != *k);
|
||||
// An Uncached Refresh is asked for, so it doesn't wait out the throttle (Cache Levels 1 alone
|
||||
// counts at level 1 too, and still waits).
|
||||
let forced = app.hist_uncached == Some((want.committed.doc, want.committed.revision));
|
||||
let job = if stale(&app.doc_hist, &want.committed) {
|
||||
(forced || due(&app.doc_hist)).then(|| (app.session.active().map(|st| st.doc.clone()), want.committed))
|
||||
} else if let Some((doc, key)) = &want.preview
|
||||
&& stale(&app.doc_hist_preview, key)
|
||||
{
|
||||
due(&app.doc_hist_preview).then(|| (Some(doc.clone()), *key))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
match job {
|
||||
Some((Some(doc), key)) => spawn(app, ctx, doc, key, want.source, want.space),
|
||||
Some((None, _)) => {}
|
||||
None if stale(&app.doc_hist, &want.committed) || want.preview.as_ref().is_some_and(|(_, k)| stale(&app.doc_hist_preview, k)) => {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(260));
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts `doc` for `key` on a worker thread (inline on the web, where there are none, or when a
|
||||
/// spawn fails), delivered through `app.hist_job`.
|
||||
fn spawn(app: &mut PhotocraftApp, ctx: &egui::Context, doc: Arc<Document>, key: HistKey, source: HistSource, space: ToneSpace) {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let spawned = {
|
||||
let doc = doc.clone();
|
||||
let tx = tx.clone();
|
||||
let ctx = ctx.clone();
|
||||
std::thread::Builder::new()
|
||||
.name("histogram".into())
|
||||
.spawn(move || {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let h = Arc::new(tone::compute_histograms_at(&doc, source, space, key.max_level));
|
||||
let _ = tx.send((key, crate::gpu_canvas::now_ms() - t0, h));
|
||||
ctx.request_repaint();
|
||||
})
|
||||
.is_ok()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let spawned = {
|
||||
let _ = ctx;
|
||||
false
|
||||
};
|
||||
if !spawned {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let h = Arc::new(tone::compute_histograms_at(&doc, source, space, key.max_level));
|
||||
let _ = tx.send((key, crate::gpu_canvas::now_ms() - t0, h));
|
||||
}
|
||||
app.hist_job = Some((key, rx));
|
||||
}
|
||||
|
||||
/// Uncached Refresh: recount the active document's current state at cache level 1 (every pixel).
|
||||
pub fn uncached_refresh(app: &mut PhotocraftApp) {
|
||||
if let Some(st) = app.session.active() {
|
||||
app.hist_uncached = Some((st.doc.id, st.revision));
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram the panel shows now: the preview's while an adjustment previews (with the
|
||||
/// document's as the original), else the document's. `stale` when it isn't the one wanted yet.
|
||||
struct Shown {
|
||||
hist: Arc<Histograms>,
|
||||
original: Option<Arc<Histograms>>,
|
||||
stale: bool,
|
||||
mode: ColorMode,
|
||||
layers: usize,
|
||||
adjustment: bool,
|
||||
}
|
||||
|
||||
fn shown(app: &mut PhotocraftApp) -> Option<Shown> {
|
||||
let want = want(app)?;
|
||||
let st = app.session.active()?;
|
||||
let (mode, layers, adjustment) = (st.doc.mode, st.doc.layer_count(), adjustment_selected(st));
|
||||
let same_doc = |e: &PanelHist| e.key.doc == want.committed.doc;
|
||||
let committed = app.doc_hist.as_ref().filter(|e| same_doc(e));
|
||||
let preview = app.doc_hist_preview.as_ref().filter(|e| same_doc(e) && want.preview.is_some());
|
||||
Some(match (preview, committed) {
|
||||
(Some(p), c) => Shown {
|
||||
hist: p.hist.clone(),
|
||||
original: c.map(|c| c.hist.clone()),
|
||||
stale: want.preview.as_ref().is_none_or(|(_, k)| *k != p.key),
|
||||
mode,
|
||||
layers,
|
||||
adjustment,
|
||||
},
|
||||
(None, Some(c)) => Shown { hist: c.hist.clone(), original: None, stale: c.key != want.committed || want.preview.is_some(), mode, layers, adjustment },
|
||||
(None, None) => return None,
|
||||
})
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Drawing
|
||||
|
||||
/// One histogram and its colour, for [`draw_overlaid`].
|
||||
type Layer<'a> = (&'a [u32; 256], Color32);
|
||||
|
||||
/// The colour of a band covered by `covering`: additive for light channels (red over green is
|
||||
/// yellow, all three grey), multiplied for inks (cyan over magenta is blue).
|
||||
fn mix(covering: impl Iterator<Item = Color32>, multiply: bool) -> Color32 {
|
||||
if multiply {
|
||||
covering.fold(Color32::WHITE, |a, b| {
|
||||
Color32::from_rgb(
|
||||
(u16::from(a.r()) * u16::from(b.r()) / 255) as u8,
|
||||
(u16::from(a.g()) * u16::from(b.g()) / 255) as u8,
|
||||
(u16::from(a.b()) * u16::from(b.b()) / 255) as u8,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
covering.fold(Color32::BLACK, |a, b| Color32::from_rgb(a.r().saturating_add(b.r()), a.g().saturating_add(b.g()), a.b().saturating_add(b.b())))
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws `layers` overlaid on one shared scale, each outlined like [`tone::draw_histogram`]
|
||||
/// (straight lines between the bin centres, down to the baseline at both ends). Where several
|
||||
/// cover a band it takes their [`mix`]ed colour. Each span between two centres is split where
|
||||
/// outlines cross, so the channel order is constant within every piece and the bands are exact
|
||||
/// trapezoids: no steps, and no draw-order-dependent blending.
|
||||
fn draw_overlaid(p: &egui::Painter, r: Rect, layers: &[Layer<'_>], multiply: bool) {
|
||||
p.add(overlaid_mesh(r, layers, multiply));
|
||||
}
|
||||
|
||||
fn overlaid_mesh(r: Rect, layers: &[Layer<'_>], multiply: bool) -> egui::Mesh {
|
||||
let top = layers.iter().map(|(h, _)| tone::histogram_scale_top(h)).fold(1.0f32, f32::max);
|
||||
// Outline points: the left baseline, the 256 bin centres, the right baseline (heights 0..1).
|
||||
let xs: Vec<f32> =
|
||||
std::iter::once(r.left()).chain((0..256).map(|i| r.left() + (i as f32 + 0.5) / 256.0 * r.width())).chain(std::iter::once(r.right())).collect();
|
||||
let height = |h: &[u32; 256], i: usize| if i == 0 || i > 256 { 0.0 } else { (h.get(i - 1).copied().unwrap_or(0) as f32 / top).min(1.0) };
|
||||
let mut mesh = egui::Mesh::default();
|
||||
let y = |v: f32| r.bottom() - v * r.height();
|
||||
for i in 0..xs.len().saturating_sub(1) {
|
||||
let (Some(&x0), Some(&x1)) = (xs.get(i), xs.get(i + 1)) else { continue };
|
||||
let a: Vec<f32> = layers.iter().map(|(h, _)| height(h, i)).collect();
|
||||
let b: Vec<f32> = layers.iter().map(|(h, _)| height(h, i + 1)).collect();
|
||||
// Where any two outlines cross within the span (as a fraction of it).
|
||||
let mut cuts = vec![0.0f32, 1.0];
|
||||
for j in 0..layers.len() {
|
||||
for k in j + 1..layers.len() {
|
||||
let (Some(aj), Some(bj), Some(ak), Some(bk)) = (a.get(j), b.get(j), a.get(k), b.get(k)) else { continue };
|
||||
let d = (bj - aj) - (bk - ak);
|
||||
if d.abs() > f32::EPSILON {
|
||||
let t = (ak - aj) / d;
|
||||
if t > 0.0 && t < 1.0 {
|
||||
cuts.push(t);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cuts.sort_by(f32::total_cmp);
|
||||
for w in cuts.windows(2) {
|
||||
let (t0, t1) = (w[0], w[1]);
|
||||
if t1 - t0 <= f32::EPSILON {
|
||||
continue;
|
||||
}
|
||||
let at = |t: f32| -> Vec<f32> { a.iter().zip(&b).map(|(a, b)| a + (b - a) * t).collect() };
|
||||
let (left, right, mid) = (at(t0), at(t1), at((t0 + t1) / 2.0));
|
||||
let mut order: Vec<usize> = (0..layers.len()).collect();
|
||||
order.sort_by(|&m, &n| mid.get(m).copied().unwrap_or(0.0).total_cmp(&mid.get(n).copied().unwrap_or(0.0)));
|
||||
let (px0, px1) = (x0 + (x1 - x0) * t0, x0 + (x1 - x0) * t1);
|
||||
// Bottom up: each band is covered by the channels at least that tall.
|
||||
let (mut below_l, mut below_r) = (0.0f32, 0.0f32);
|
||||
for (n, &c) in order.iter().enumerate() {
|
||||
let (Some(&tl), Some(&tr)) = (left.get(c), right.get(c)) else { continue };
|
||||
if tl > below_l || tr > below_r {
|
||||
let color = mix(order.iter().skip(n).filter_map(|&m| layers.get(m).map(|l| l.1)), multiply);
|
||||
let v = mesh.vertices.len() as u32;
|
||||
for q in [pos2(px0, y(below_l)), pos2(px0, y(tl)), pos2(px1, y(tr)), pos2(px1, y(below_r))] {
|
||||
mesh.colored_vertex(q, color);
|
||||
}
|
||||
mesh.add_triangle(v, v + 1, v + 2);
|
||||
mesh.add_triangle(v, v + 2, v + 3);
|
||||
}
|
||||
(below_l, below_r) = (tl.max(below_l), tr.max(below_r));
|
||||
}
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
|
||||
/// The colour a single-channel graph draws in: its channel colour when colourised, else the
|
||||
/// composite grey.
|
||||
fn graph_color(channel: HistChannel, colored: bool, t: &Tokens) -> Color32 {
|
||||
let grey = if t.pro { Color32::from_gray(215) } else { Color32::from_gray(70) };
|
||||
if colored { channel_paint(channel).unwrap_or(grey) } else { grey }
|
||||
}
|
||||
|
||||
/// Draws `channel` of `h` in `r` (Colors overlays the colour channels).
|
||||
fn draw_channel(p: &egui::Painter, r: Rect, h: &Histograms, mode: ColorMode, channel: HistChannel, colored: bool, t: &Tokens) {
|
||||
if channel == HistChannel::Colors {
|
||||
let layers: Vec<Layer<'_>> = color_channels(mode).iter().filter_map(|c| Some((bins(h, mode, *c), channel_paint(*c)?))).collect();
|
||||
draw_overlaid(p, r, &layers, tone_space(mode) == ToneSpace::Cmyk);
|
||||
} else {
|
||||
tone::draw_histogram(p, r, bins(h, mode, channel), graph_color(channel, colored, t));
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram graph with its marks and pointer interaction. Returns the levels under the
|
||||
/// pointer (hover) for the statistics.
|
||||
fn graph(app: &mut PhotocraftApp, ui: &mut egui::Ui, s: &Shown, channel: HistChannel, colored: bool, height: f32) -> Option<u8> {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let w = ui.available_width();
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(w, height), Sense::click_and_drag());
|
||||
let p = ui.painter_at(r);
|
||||
p.rect_filled(r, 0.0, t.field);
|
||||
let level_at = |x: f32| (((x - r.left()) / r.width().max(1.0)) * 256.0).floor().clamp(0.0, 255.0) as u8;
|
||||
let x_of = |l: u8| r.left() + (f32::from(l) + 0.5) / 256.0 * r.width();
|
||||
// The selected range behind the bars.
|
||||
if let Some([a, b]) = app.ui.histogram_range {
|
||||
let (lo, hi) = (a.min(b), a.max(b));
|
||||
let band = Rect::from_x_y_ranges(r.left() + f32::from(lo) / 256.0 * r.width()..=r.left() + (f32::from(hi) + 1.0) / 256.0 * r.width(), r.y_range());
|
||||
p.rect_filled(band, 0.0, t.accent.gamma_multiply(0.35));
|
||||
}
|
||||
draw_channel(&p, r, &s.hist, s.mode, channel, colored, &t);
|
||||
// The original histogram outlined over the adjusted one while an adjustment previews.
|
||||
if let Some(o) = &s.original {
|
||||
outline(&p, r, bins(o, s.mode, if channel == HistChannel::Colors { HistChannel::Composite } else { channel }), t.text);
|
||||
}
|
||||
// The Color Samplers' levels.
|
||||
let mark_channel = if channel == HistChannel::Colors { HistChannel::Composite } else { channel };
|
||||
for v in crate::panels::sampler_readouts(app).iter() {
|
||||
let rgb = v["rgb"].as_array().map(|a| a.iter().filter_map(Value::as_f64).map(|c| (c / 255.0) as f32).collect::<Vec<_>>()).unwrap_or_default();
|
||||
let (Some(&red), Some(&green), Some(&blue)) = (rgb.first(), rgb.get(1), rgb.get(2)) else { continue };
|
||||
let x = x_of(channel_level(s.mode, mark_channel, [red, green, blue, 1.0]));
|
||||
p.line_segment([pos2(x, r.bottom() - 9.0), pos2(x, r.bottom())], egui::Stroke::new(1.5, t.text));
|
||||
p.text(pos2(x + 2.0, r.bottom() - 9.0), egui::Align2::LEFT_BOTTOM, v["number"].to_string(), egui::FontId::proportional(9.0), t.text);
|
||||
}
|
||||
// The cached-data warning: click it (or double-click the graph) for an Uncached Refresh.
|
||||
if s.stale || s.hist.level > 1 {
|
||||
let icon = Rect::from_min_size(r.right_top() + vec2(-18.0, 2.0), vec2(16.0, 16.0));
|
||||
crate::icons::paint(ui, icon, "triangle-alert", 12.0, t.warning);
|
||||
let warn = ui.interact(icon, ui.id().with("hist-cached-warning"), Sense::click()).on_hover_text(tl!("Click to refresh histogram with uncached data"));
|
||||
if warn.clicked() {
|
||||
uncached_refresh(app);
|
||||
}
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
uncached_refresh(app);
|
||||
}
|
||||
let pointer = resp.interact_pointer_pos().or_else(|| resp.hover_pos());
|
||||
let id = ui.id().with("hist-drag-from");
|
||||
if resp.drag_started()
|
||||
&& let Some(pos) = resp.interact_pointer_pos()
|
||||
{
|
||||
ui.data_mut(|d| d.insert_temp(id, level_at(pos.x)));
|
||||
}
|
||||
if resp.dragged()
|
||||
&& let (Some(from), Some(pos)) = (ui.data(|d| d.get_temp::<u8>(id)), pointer)
|
||||
{
|
||||
app.ui.histogram_range = Some([from, level_at(pos.x)]);
|
||||
} else if resp.clicked() {
|
||||
app.ui.histogram_range = None;
|
||||
}
|
||||
pointer.filter(|_| resp.hovered() || resp.dragged()).map(|pos| level_at(pos.x))
|
||||
}
|
||||
|
||||
/// The outline of `h` (the original histogram over an adjusted one).
|
||||
fn outline(p: &egui::Painter, r: Rect, h: &[u32; 256], color: Color32) {
|
||||
let top = tone::histogram_scale_top(h);
|
||||
let pts: Vec<_> = h
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| pos2(r.left() + (i as f32 + 0.5) / 256.0 * r.width(), r.bottom() - (*v as f32 / top).min(1.0) * r.height()))
|
||||
.collect();
|
||||
p.add(egui::Shape::line(pts, egui::Stroke::new(1.0, color.gamma_multiply(0.8))));
|
||||
}
|
||||
|
||||
/// The statistics grid: Mean, Std Dev, Median, Pixels | Level, Count, Percentile, Cache Level.
|
||||
fn statistics(ui: &mut egui::Ui, h: &Histograms, mode: ColorMode, channel: HistChannel, levels: Option<[u8; 2]>, t: &Tokens) {
|
||||
let ch = if channel == HistChannel::Colors { HistChannel::Composite } else { channel };
|
||||
let Some(s) = stats(bins(h, mode, ch), levels) else { return };
|
||||
let level = match s.level {
|
||||
Some([a, b]) if a == b => a.to_string(),
|
||||
Some([a, b]) => format!("{a}..{b}"),
|
||||
None => String::new(),
|
||||
};
|
||||
let rows = [
|
||||
(tl!("Mean:"), format!("{:.2}", s.mean), tl!("Level:"), level),
|
||||
(tl!("Std Dev:"), format!("{:.2}", s.std_dev), tl!("Count:"), s.count.map(|c| c.to_string()).unwrap_or_default()),
|
||||
(tl!("Median:"), s.median.to_string(), tl!("Percentile:"), s.percentile.map(|p| format!("{p:.2}")).unwrap_or_default()),
|
||||
(tl!("Pixels:"), s.pixels.to_string(), tl!("Cache Level:"), h.level.max(1).to_string()),
|
||||
];
|
||||
let mono = crate::theme::mono(11.5);
|
||||
egui::Grid::new("hist-stats").num_columns(4).spacing(vec2(6.0, 2.0)).show(ui, |ui| {
|
||||
for (k1, v1, k2, v2) in rows {
|
||||
for (k, v) in [(k1, v1), (k2, v2)] {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
ui.label(egui::RichText::new(k).color(t.text_dim).size(11.5));
|
||||
});
|
||||
ui.label(egui::RichText::new(v).font(mono.clone()).color(t.text));
|
||||
}
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Histogram panel (Window › Histogram).
|
||||
pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
if app.session.active().is_none() {
|
||||
ui.label(egui::RichText::new(tl!("No document")).color(t.text_faint));
|
||||
return;
|
||||
}
|
||||
update(app, ui.ctx());
|
||||
let Some(s) = shown(app) else {
|
||||
ui.label(egui::RichText::new(tl!("Calculating…")).color(t.text_faint));
|
||||
return;
|
||||
};
|
||||
let opts = app.ui.histogram_panel;
|
||||
let channel = resolve_channel(s.mode, opts.channel);
|
||||
if opts.view == HistView::Compact {
|
||||
// Compact View: the graph alone; a single channel is always in its colour.
|
||||
graph(app, ui, &s, channel, true, 100.0);
|
||||
return;
|
||||
}
|
||||
let mut changed = false;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Channel:")).color(t.text_dim).size(12.0));
|
||||
let mut ch = channel;
|
||||
let options = channel_options(s.mode);
|
||||
if crate::widgets::dropdown(ui, "histogram-panel-ch", &mut ch, &options, 110.0) {
|
||||
app.ui.histogram_panel.channel = ch;
|
||||
changed = true;
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if crate::icons::button(ui, "rotate-cw", 20.0, false, tl!("Uncached Refresh")).clicked() {
|
||||
uncached_refresh(app);
|
||||
}
|
||||
});
|
||||
});
|
||||
let colored = opts.show_channels_in_color;
|
||||
let hover = graph(app, ui, &s, channel, colored, 100.0);
|
||||
// Source: only for documents with several layers.
|
||||
if s.layers > 1 {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(tl!("Source:")).color(t.text_dim).size(12.0));
|
||||
let mut src = opts.source;
|
||||
let mut options = vec![(HistSourceChoice::EntireImage, "Entire Image"), (HistSourceChoice::SelectedLayer, "Selected Layer")];
|
||||
if s.adjustment {
|
||||
options.push((HistSourceChoice::AdjustmentComposite, "Adjustment Composite"));
|
||||
} else if src == HistSourceChoice::AdjustmentComposite {
|
||||
src = HistSourceChoice::EntireImage;
|
||||
}
|
||||
if crate::widgets::dropdown(ui, "histogram-panel-src", &mut src, &options, 150.0) {
|
||||
app.ui.histogram_panel.source = src;
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
if opts.show_statistics {
|
||||
ui.add_space(4.0);
|
||||
let levels = app.ui.histogram_range.or_else(|| hover.map(|l| [l, l]));
|
||||
statistics(ui, &s.hist, s.mode, channel, levels, &t);
|
||||
}
|
||||
if opts.view == HistView::AllChannels {
|
||||
for c in color_channels(s.mode) {
|
||||
ui.add_space(4.0);
|
||||
ui.label(egui::RichText::new(tl!(channel_label(s.mode, *c))).color(t.text).size(11.5));
|
||||
let w = ui.available_width();
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, 90.0), Sense::hover());
|
||||
let p = ui.painter_at(r);
|
||||
p.rect_filled(r, 0.0, t.field);
|
||||
tone::draw_histogram(&p, r, bins(&s.hist, s.mode, *c), graph_color(*c, colored, &t));
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
persist_options(app);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Histogram items of the panel menu.
|
||||
pub fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
if ui.add_enabled(app.session.active().is_some(), egui::Button::new(tl!("Uncached Refresh"))).clicked() {
|
||||
uncached_refresh(app);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
let mut changed = false;
|
||||
for (view, label) in [(HistView::Compact, "Compact View"), (HistView::Expanded, "Expanded View"), (HistView::AllChannels, "All Channels View")] {
|
||||
if ui.radio(app.ui.histogram_panel.view == view, tl!(label)).clicked() {
|
||||
// The channel is one setting for every view, so it is kept.
|
||||
app.ui.histogram_panel.view = view;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
let mut stats_on = app.ui.histogram_panel.show_statistics;
|
||||
if crate::widgets::checkbox(ui, &mut stats_on, tl!("Show Statistics")).changed() {
|
||||
app.ui.histogram_panel.show_statistics = stats_on;
|
||||
changed = true;
|
||||
}
|
||||
let mut color = app.ui.histogram_panel.show_channels_in_color;
|
||||
if crate::widgets::checkbox(ui, &mut color, tl!("Show Channels in Color")).changed() {
|
||||
app.ui.histogram_panel.show_channels_in_color = color;
|
||||
changed = true;
|
||||
}
|
||||
if changed {
|
||||
persist_options(app);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel's state for `ui.inspect` (`histogram`): its options as they apply to the active
|
||||
/// document, and the shown histogram's statistics for the selected range.
|
||||
pub fn inspect(app: &PhotocraftApp) -> Value {
|
||||
let opts = app.ui.histogram_panel;
|
||||
let Some(st) = app.session.active() else { return json!({"options": opts}) };
|
||||
let mode = st.doc.mode;
|
||||
let channel = resolve_channel(mode, opts.channel);
|
||||
let (source, _) = resolve_source(st, source_choice(&opts));
|
||||
let preview = app.doc_hist_preview.as_ref().filter(|e| e.key.doc == st.doc.id);
|
||||
let entry = preview.or(app.doc_hist.as_ref()).filter(|e| e.key.doc == st.doc.id);
|
||||
let committed = committed_key(app).map(|(k, _, _)| k);
|
||||
let ch = if channel == HistChannel::Colors { HistChannel::Composite } else { channel };
|
||||
json!({
|
||||
"options": opts,
|
||||
"channel": channel_id(channel),
|
||||
"channels": channel_options(mode).iter().map(|(c, _)| channel_id(*c)).collect::<Vec<_>>(),
|
||||
"source": source,
|
||||
"sourceShown": st.doc.layer_count() > 1 && opts.view != HistView::Compact,
|
||||
"range": app.ui.histogram_range,
|
||||
"preview": preview.is_some(),
|
||||
"revision": entry.map(|e| e.key.revision),
|
||||
"current": entry.zip(committed).is_some_and(|(e, k)| e.key == HistKey { preview: e.key.preview, ..k }),
|
||||
"cacheLevel": entry.map(|e| e.hist.level.max(1)),
|
||||
"maxCacheLevel": max_cache_level(app),
|
||||
"stats": entry.and_then(|e| stats(bins(&e.hist, mode, ch), app.ui.histogram_range)),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "histogram_panel_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,416 @@
|
||||
use super::*;
|
||||
use crate::PhotocraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
fn app_with(params: Value) -> PhotocraftApp {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", params).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// One panel frame through a minimal egui pass.
|
||||
fn frame(app: &mut PhotocraftApp) {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.begin_pass(Default::default());
|
||||
let mut ui =
|
||||
egui::Ui::new(ctx.clone(), egui::Id::new("hist-test"), egui::UiBuilder::new().max_rect(Rect::from_min_size(egui::Pos2::ZERO, vec2(300.0, 900.0))));
|
||||
show(app, &mut ui);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
}
|
||||
|
||||
/// Frames until the panel shows the histogram it wants (the throttle skipped), or panics after 5 s.
|
||||
fn settle(app: &mut PhotocraftApp) {
|
||||
let t0 = std::time::Instant::now();
|
||||
loop {
|
||||
for e in [app.doc_hist.as_mut(), app.doc_hist_preview.as_mut()].into_iter().flatten() {
|
||||
e.at = -1e12;
|
||||
}
|
||||
frame(app);
|
||||
let done = app.hist_job.is_none() && shown(app).is_some_and(|s| !s.stale);
|
||||
if done {
|
||||
return;
|
||||
}
|
||||
assert!(t0.elapsed() < std::time::Duration::from_secs(5), "the histogram never settled");
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
fn ui_set(app: &mut PhotocraftApp, ctx: &egui::Context, params: Value) -> Value {
|
||||
let (req, _rx) = crate::control::ControlRequest::new("ui.set", params);
|
||||
match crate::control::handle(app, ctx, &req) {
|
||||
crate::control::Outcome::Done(v) => v,
|
||||
_ => panic!("ui.set: expected an immediate reply"),
|
||||
}
|
||||
}
|
||||
|
||||
fn inspect_stats(app: &PhotocraftApp) -> Value {
|
||||
inspect(app)["stats"].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stats_match_their_definitions() {
|
||||
let mut h = [0u32; 256];
|
||||
h[0] = 25;
|
||||
h[100] = 50;
|
||||
h[255] = 25;
|
||||
let s = stats(&h, None).unwrap();
|
||||
assert_eq!(s.pixels, 100);
|
||||
assert!((s.mean - (5000.0 + 6375.0) / 100.0).abs() < 1e-9);
|
||||
assert_eq!(s.median, 100);
|
||||
assert_eq!(s.clipped, [25.0, 25.0], "a quarter of the pixels clip at each end");
|
||||
// One level: its count and the percent at or below it.
|
||||
let one = stats(&h, Some([100, 100])).unwrap();
|
||||
assert_eq!((one.count, one.percentile), (Some(50), Some(75.0)));
|
||||
// A dragged range (either direction): the count and percent within it.
|
||||
let range = stats(&h, Some([200, 50])).unwrap();
|
||||
assert_eq!((range.level, range.count, range.percentile), (Some([50, 200]), Some(50), Some(50.0)));
|
||||
assert!(stats(&[0; 256], Some([0, 255])).is_none(), "an empty histogram has no statistics");
|
||||
assert!(stats(&h, None).unwrap().std_dev > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_follow_the_colour_mode() {
|
||||
let ids = |m| channel_options(m).into_iter().map(|(c, _)| c).collect::<Vec<_>>();
|
||||
use HistChannel::*;
|
||||
assert_eq!(ids(ColorMode::Rgb), [Composite, Red, Green, Blue, Luminosity, Colors]);
|
||||
assert_eq!(ids(ColorMode::Cmyk), [Composite, Cyan, Magenta, Yellow, Black, Luminosity, Colors]);
|
||||
assert_eq!(ids(ColorMode::Lab), [Composite, A, B, Luminosity]);
|
||||
assert_eq!(ids(ColorMode::Grayscale), [Composite]);
|
||||
assert_eq!(resolve_channel(ColorMode::Cmyk, Red), Composite, "a channel the mode lacks shows its composite");
|
||||
assert_eq!(resolve_channel(ColorMode::Rgb, Red), Red);
|
||||
assert!(color_channels(ColorMode::Grayscale).is_empty(), "All Channels lists colour channels only");
|
||||
assert_eq!(color_channels(ColorMode::Rgb), [Red, Green, Blue]);
|
||||
// Pointer marks bin pixels the way the histogram does.
|
||||
let px = [1.0, 0.5, 0.0, 1.0];
|
||||
assert_eq!(channel_level(ColorMode::Rgb, Red, px), 255);
|
||||
assert_eq!(channel_level(ColorMode::Rgb, Green, px), 128);
|
||||
assert_eq!(channel_level(ColorMode::Rgb, Composite, px), 127);
|
||||
assert_eq!(channel_level(ColorMode::Rgb, Luminosity, px), ((0.30 + 0.59 * 0.5) * 255.0f32).round() as u8);
|
||||
assert_eq!(channel_level(ColorMode::Rgb, Blue, [f32::NAN, 0.0, 2.0, 1.0]), 255, "hostile samples clamp, never panic");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn luminosity_and_rgb_channels_are_counted() {
|
||||
let mut app = app_with(json!({"width": 40, "height": 20}));
|
||||
app.run("select.rect", json!({"x": 0, "y": 0, "width": 20, "height": 20})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#ff0000"})).unwrap();
|
||||
let doc = &app.session.active().unwrap().doc;
|
||||
let h = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb);
|
||||
assert_eq!(bins(&h, doc.mode, HistChannel::Red)[255], 800);
|
||||
assert_eq!(bins(&h, doc.mode, HistChannel::Green)[0], 400);
|
||||
let red_lum = (0.30f32 * 255.0).round() as usize;
|
||||
assert_eq!(h.lum[red_lum], 400, "red is 30% luminosity");
|
||||
assert_eq!(h.lum[255], 400, "white is full luminosity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sources_count_the_image_the_layer_or_the_adjustment_composite() {
|
||||
let mut app = app_with(json!({"width": 32, "height": 32})); // white
|
||||
app.run("layer.newAdjustmentLayer.invert", json!({})).unwrap();
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("select.rect", json!({"x": 0, "y": 0, "width": 16, "height": 32})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#808080"})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
let invert = st.doc.layers[1].id;
|
||||
let doc = &st.doc;
|
||||
let image = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb);
|
||||
assert_eq!((image[0][0], image[0][128]), (512, 512), "black (inverted white) and the grey above it");
|
||||
let upto = tone::compute_histograms(doc, HistSource::UpTo(invert), ToneSpace::Rgb);
|
||||
assert_eq!(upto[0][0], 1024, "the adjustment composite hides the grey layer above");
|
||||
// The panel offers Adjustment Composite only with an adjustment layer selected.
|
||||
assert_eq!(resolve_source(st, HistSourceChoice::AdjustmentComposite).0, HistSourceChoice::EntireImage);
|
||||
assert_eq!(resolve_source(st, HistSourceChoice::SelectedLayer).1, HistSource::Layer(st.active_layer.unwrap()));
|
||||
app.run("layer.select", json!({"layer": invert.0})).unwrap();
|
||||
let st = app.session.active().unwrap();
|
||||
assert_eq!(st.active_layer, Some(invert));
|
||||
assert_eq!(resolve_source(st, HistSourceChoice::AdjustmentComposite), (HistSourceChoice::AdjustmentComposite, HistSource::UpTo(invert)));
|
||||
// A single-layer document counts the entire image whatever is chosen.
|
||||
let one = app_with(json!({"width": 8, "height": 8}));
|
||||
let st = one.session.active().unwrap();
|
||||
assert_eq!(resolve_source(st, HistSourceChoice::SelectedLayer).0, HistSourceChoice::EntireImage);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_level_follows_size_and_the_preference_cap() {
|
||||
let big = app_with(json!({"width": 6000, "height": 3000}));
|
||||
let doc = &big.session.active().unwrap().doc;
|
||||
let auto = tone::cache_level(doc, tone::MAX_CACHE_LEVEL);
|
||||
assert!(auto > 1, "a large document counts a proxy, level {auto}");
|
||||
assert_eq!(tone::cache_level(doc, 2), 2, "capped by Cache Levels");
|
||||
assert_eq!(tone::cache_level(doc, 0), 1, "out-of-range caps clamp");
|
||||
let exact = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, 1);
|
||||
assert_eq!(exact.level, 1);
|
||||
assert_eq!(exact[0][255], 6000 * 3000, "level 1 counts every pixel");
|
||||
let small = app_with(json!({"width": 64, "height": 64}));
|
||||
assert_eq!(tone::cache_level(&small.session.active().unwrap().doc, 8), 1, "small documents are exact");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_counts_off_thread_and_recounts_after_an_edit() {
|
||||
let mut app = app_with(json!({"width": 64, "height": 48}));
|
||||
settle(&mut app);
|
||||
let s = inspect_stats(&app);
|
||||
assert_eq!(s["pixels"], 64 * 48);
|
||||
assert_eq!(s["median"], 255);
|
||||
assert_eq!(inspect(&app)["current"], true);
|
||||
app.run("edit.fill", json!({"color": "#000000"})).unwrap();
|
||||
assert_eq!(inspect(&app)["current"], false, "stale until recounted");
|
||||
frame(&mut app);
|
||||
// The old histogram stays shown, marked stale, while the new one counts.
|
||||
assert!(shown(&mut app).is_some());
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect_stats(&app)["median"], 0, "refreshed without a manual refresh");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dead_histogram_worker_clears_the_job() {
|
||||
let mut app = app_with(json!({"width": 64, "height": 48}));
|
||||
let st = app.session.active().unwrap();
|
||||
let key = HistKey { doc: st.doc.id, revision: st.revision, source: 0, preview: 0, max_level: 4 };
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
drop(tx);
|
||||
app.hist_job = Some((key, rx));
|
||||
let ctx = egui::Context::default();
|
||||
update(&mut app, &ctx);
|
||||
assert!(app.doc_hist.is_none(), "nothing landed from the dead worker");
|
||||
// …and the next count was scheduled in its place.
|
||||
assert!(app.hist_job.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uncached_refresh_counts_every_pixel_for_the_current_state() {
|
||||
let mut app = app_with(json!({"width": 6000, "height": 3000}));
|
||||
app.run("prefs.set", json!({"path": "performance.cacheLevels", "value": 8})).unwrap();
|
||||
settle(&mut app);
|
||||
assert!(inspect(&app)["cacheLevel"].as_u64().unwrap() > 1, "cached first");
|
||||
uncached_refresh(&mut app);
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["cacheLevel"], 1);
|
||||
assert_eq!(inspect_stats(&app)["pixels"], 6000u64 * 3000);
|
||||
// Cache Levels caps what the panel counts at.
|
||||
app.run("prefs.set", json!({"path": "performance.cacheLevels", "value": 2})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#000000"})).unwrap();
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["cacheLevel"], 2);
|
||||
assert_eq!(inspect(&app)["maxCacheLevel"], 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_preview_is_counted_over_the_original() {
|
||||
let mut app = app_with(json!({"width": 32, "height": 32})); // white
|
||||
app.run("layer.newAdjustmentLayer.levels", json!({})).unwrap();
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect_stats(&app)["median"], 255);
|
||||
let id = app.session.active().unwrap().active_layer.unwrap();
|
||||
app.live_adjust = Some((id, json!({"outWhite": 100})));
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["preview"], true);
|
||||
assert_eq!(inspect_stats(&app)["median"], 100, "the previewed levels");
|
||||
let s = shown(&mut app).unwrap();
|
||||
let original = s.original.expect("the original is kept for the overlay");
|
||||
assert_eq!(original[0][255], 1024, "the original is the image before the preview");
|
||||
app.live_adjust = None;
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["preview"], false);
|
||||
assert_eq!(inspect_stats(&app)["median"], 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_keep_the_channel_and_the_menu_toggles_options() {
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
let mut app = app_with(json!({"width": 16, "height": 16}));
|
||||
app.ui.histogram_panel.channel = HistChannel::Green;
|
||||
let mut h = Harness::builder().with_size(vec2(260.0, 320.0)).build_ui_state(|ui, app: &mut PhotocraftApp| panel_menu(app, ui), app);
|
||||
h.run_steps(2);
|
||||
h.get_by_label("All Channels View").click();
|
||||
h.run_steps(2);
|
||||
assert_eq!(h.state().ui.histogram_panel.view, HistView::AllChannels);
|
||||
assert_eq!(h.state().ui.histogram_panel.channel, HistChannel::Green, "the channel is kept");
|
||||
h.get_by_label("Show Channels in Color").click();
|
||||
h.run_steps(2);
|
||||
assert!(h.state().ui.histogram_panel.show_channels_in_color);
|
||||
h.get_by_label("Show Statistics").click();
|
||||
h.run_steps(2);
|
||||
assert!(!h.state().ui.histogram_panel.show_statistics);
|
||||
// Kept with the preferences.
|
||||
let mut again = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let saved = h.state().session.prefs().dialogs.get(OPTIONS_PREF).cloned().unwrap();
|
||||
again.session.prefs.edit(|p| {
|
||||
p.dialogs.insert(OPTIONS_PREF.into(), saved);
|
||||
});
|
||||
restore_options(&mut again);
|
||||
assert_eq!(again.ui.histogram_panel.view, HistView::AllChannels);
|
||||
assert!(again.ui.histogram_panel.show_channels_in_color);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_view_and_channel_draws_without_panicking() {
|
||||
for mode in ["rgb", "cmyk", "lab", "grayscale"] {
|
||||
let mut app = app_with(json!({"width": 24, "height": 24, "mode": mode}));
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
settle(&mut app);
|
||||
for view in [HistView::Compact, HistView::Expanded, HistView::AllChannels] {
|
||||
for channel in [HistChannel::Composite, HistChannel::Red, HistChannel::Cyan, HistChannel::A, HistChannel::Luminosity, HistChannel::Colors] {
|
||||
for range in [[200, 10], [0, 255]] {
|
||||
app.ui.histogram_panel.view = view;
|
||||
app.ui.histogram_panel.channel = channel;
|
||||
app.ui.histogram_range = Some(range);
|
||||
frame(&mut app);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(inspect(&app)["stats"]["count"].is_u64(), "{mode}: the range has a count");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlaid_colors_mix_where_channels_overlap() {
|
||||
let ctx = egui::Context::default();
|
||||
ctx.begin_pass(Default::default());
|
||||
let p = ctx.layer_painter(egui::LayerId::background());
|
||||
let h = [100u32; 256];
|
||||
draw_overlaid(&p, Rect::from_min_size(egui::Pos2::ZERO, vec2(256.0, 50.0)), &[(&h, Color32::RED), (&h, Color32::GREEN)], false);
|
||||
draw_overlaid(&p, Rect::from_min_size(egui::Pos2::ZERO, vec2(256.0, 50.0)), &[], true);
|
||||
ctx.end_pass().textures_delta.clear();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ui_set_drives_the_panel() {
|
||||
let mut app = app_with(json!({"width": 16, "height": 16}));
|
||||
let ctx = egui::Context::default();
|
||||
let r = ui_set(
|
||||
&mut app,
|
||||
&ctx,
|
||||
json!({"histogramPanel": {"view": "allChannels", "channel": "luminosity"}, "histogramRange": [10, 20], "histogramRefresh": true}),
|
||||
);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(app.ui.histogram_panel.view, HistView::AllChannels);
|
||||
assert_eq!(app.ui.histogram_panel.channel, HistChannel::Luminosity);
|
||||
assert_eq!(app.ui.histogram_range, Some([10, 20]));
|
||||
assert!(app.hist_uncached.is_some());
|
||||
for bad in [
|
||||
json!({"histogramPanel": {"view": "tiny"}}),
|
||||
json!({"histogramPanel": {"nope": 1}}),
|
||||
json!({"histogramRange": [0, 300]}),
|
||||
json!({"histogramRefresh": "yes"}),
|
||||
] {
|
||||
let r = ui_set(&mut app, &ctx, bad.clone());
|
||||
assert_eq!(r["ok"], false, "{bad}: {r}");
|
||||
}
|
||||
assert_eq!(app.ui.histogram_panel.view, HistView::AllChannels, "a rejected call changes nothing");
|
||||
}
|
||||
|
||||
/// The Colors overlay follows the same outline as a single channel: straight lines between bin
|
||||
/// centres, not one flat step per level, and its bands tile without gaps where outlines cross.
|
||||
#[test]
|
||||
fn colors_overlay_is_a_continuous_outline_not_steps() {
|
||||
let r = Rect::from_min_size(egui::Pos2::ZERO, vec2(512.0, 100.0));
|
||||
let ramp: [u32; 256] = std::array::from_fn(|i| i as u32 * 10);
|
||||
let fall: [u32; 256] = std::array::from_fn(|i| (255 - i) as u32 * 10);
|
||||
let mesh = overlaid_mesh(r, &[(&ramp, Color32::RED), (&fall, Color32::GREEN)], false);
|
||||
let quads: Vec<&[egui::epaint::Vertex]> = mesh.vertices.chunks(4).collect();
|
||||
assert!(!quads.is_empty());
|
||||
// Every band's top edge slopes on a ramp: no flat steps.
|
||||
let sloped = quads.iter().filter(|q| (q[1].pos.y - q[2].pos.y).abs() > 1e-4).count();
|
||||
assert!(sloped * 10 > quads.len() * 9, "{sloped} of {} bands slope", quads.len());
|
||||
// The two ramps cross mid-way: there the overlap is yellow and each side keeps its own colour.
|
||||
let colors: std::collections::HashSet<_> = mesh.vertices.iter().map(|v| v.color).collect();
|
||||
assert!(colors.contains(&Color32::from_rgb(255, 255, 0)) && colors.contains(&Color32::RED) && colors.contains(&Color32::GREEN));
|
||||
// Nothing is drawn above the taller outline at any x.
|
||||
for q in &quads {
|
||||
for v in q.iter() {
|
||||
assert!(v.pos.y >= r.top() - 1e-3 && v.pos.y <= r.bottom() + 1e-3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A white Background under a black layer, with the Background selected: the entire image is
|
||||
/// black, the selected layer white.
|
||||
fn black_over_white_background_selected() -> PhotocraftApp {
|
||||
let mut app = app_with(json!({"width": 32, "height": 32}));
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
app.run("edit.fill", json!({"color": "#000000"})).unwrap();
|
||||
let background = app.session.active().unwrap().doc.layers[0].id;
|
||||
app.run("layer.select", json!({"layer": background.0})).unwrap();
|
||||
app
|
||||
}
|
||||
|
||||
/// Preferences › Cache Levels 1 counts at level 1 like an Uncached Refresh, but only the refresh
|
||||
/// was asked for: edits in a row still wait out the 250 ms throttle.
|
||||
#[test]
|
||||
fn cache_levels_one_still_throttles_recounts_and_an_uncached_refresh_does_not() {
|
||||
let mut app = app_with(json!({"width": 64, "height": 48}));
|
||||
app.run("prefs.set", json!({"path": "performance.cacheLevels", "value": 1})).unwrap();
|
||||
settle(&mut app);
|
||||
// The count just landed, so the next edit falls inside the throttle.
|
||||
app.doc_hist.as_mut().unwrap().at = 0.0;
|
||||
app.run("edit.fill", json!({"color": "#000000"})).unwrap();
|
||||
frame(&mut app);
|
||||
assert!(app.hist_job.is_none(), "an edit within 250 ms of the last count waits");
|
||||
uncached_refresh(&mut app);
|
||||
frame(&mut app);
|
||||
assert!(app.hist_job.is_some(), "an Uncached Refresh counts at once");
|
||||
}
|
||||
|
||||
/// The Levels, Curves and Threshold dialogs count uncapped: their proxy is as small as before
|
||||
/// Cache Levels (about 768 pixels on the longest side), and only a cap halves by powers of two.
|
||||
#[test]
|
||||
fn uncapped_counts_keep_their_proxy_and_a_cap_reduces_by_powers_of_two() {
|
||||
let big = app_with(json!({"width": 6000, "height": 3000}));
|
||||
let doc = &big.session.active().unwrap().doc;
|
||||
let pixels = |h: &Histograms| h[0].iter().map(|&c| u64::from(c)).sum::<u64>();
|
||||
// 6000 / 768 = 7: a 7x proxy, 858 x 429 (rounded up), not an 8x one.
|
||||
let auto = tone::compute_histograms(doc, tone::IMAGE, ToneSpace::Rgb);
|
||||
assert_eq!(pixels(&auto), 858 * 429);
|
||||
let capped = tone::compute_histograms_at(doc, tone::IMAGE, ToneSpace::Rgb, 3);
|
||||
assert_eq!(capped.level, 3);
|
||||
assert_eq!(pixels(&capped), 1500 * 750, "level 3 is a 4x proxy");
|
||||
}
|
||||
|
||||
/// Photoshop opens the panel in Compact View, which shows no Source menu and represents the
|
||||
/// entire image whatever Source the Expanded View was left at.
|
||||
#[test]
|
||||
fn compact_view_is_the_default_and_counts_the_entire_image() {
|
||||
assert_eq!(HistogramPanelState::default().view, HistView::Compact);
|
||||
let mut app = black_over_white_background_selected();
|
||||
app.ui.histogram_panel = HistogramPanelState { source: HistSourceChoice::SelectedLayer, ..Default::default() };
|
||||
settle(&mut app);
|
||||
let i = inspect(&app);
|
||||
assert_eq!(i["source"], "entireImage");
|
||||
assert_eq!(i["stats"]["median"], 0, "the black layer over the Background, not the Background alone");
|
||||
app.ui.histogram_panel.view = HistView::Expanded;
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["source"], "selectedLayer");
|
||||
assert_eq!(inspect_stats(&app)["median"], 255, "Expanded View counts the chosen Source");
|
||||
}
|
||||
|
||||
/// `current` says whether the shown histogram is the one the panel wants: a Source change makes
|
||||
/// it stale until the recount lands, though the document's revision didn't move.
|
||||
#[test]
|
||||
fn inspect_current_follows_the_source_not_only_the_revision() {
|
||||
let mut app = black_over_white_background_selected();
|
||||
app.ui.histogram_panel.view = HistView::Expanded;
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["current"], true);
|
||||
let ctx = egui::Context::default();
|
||||
let r = ui_set(&mut app, &ctx, json!({"histogramPanel": {"source": "selectedLayer"}}));
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
assert_eq!(inspect(&app)["current"], false, "the entire image's histogram is not the selected layer's");
|
||||
settle(&mut app);
|
||||
assert_eq!(inspect(&app)["current"], true);
|
||||
assert_eq!(inspect_stats(&app)["median"], 255);
|
||||
}
|
||||
|
||||
/// `preview` reports only the active document's preview, not one left from another document.
|
||||
#[test]
|
||||
fn inspect_preview_is_the_active_documents() {
|
||||
let mut app = app_with(json!({"width": 16, "height": 16}));
|
||||
settle(&mut app);
|
||||
let mut other = app.doc_hist.clone().unwrap();
|
||||
other.key.preview = 1;
|
||||
app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
|
||||
assert_ne!(app.session.active().unwrap().doc.id, other.key.doc);
|
||||
app.doc_hist_preview = Some(other);
|
||||
assert_eq!(inspect(&app)["preview"], false);
|
||||
}
|
||||
@@ -115,6 +115,7 @@ pub mod gpu_status;
|
||||
pub mod gradient_ui;
|
||||
pub mod guide_layout_ui;
|
||||
pub mod guide_select;
|
||||
pub mod histogram_panel;
|
||||
pub mod history_menu_ui;
|
||||
pub mod hold_keys;
|
||||
pub mod i18n;
|
||||
@@ -693,10 +694,6 @@ pub struct Services {
|
||||
pub quit: Option<QuitFn>,
|
||||
}
|
||||
|
||||
/// A document histogram being computed off the UI thread: (document, revision, receiver of
|
||||
/// (document, compute ms, histograms)).
|
||||
pub(crate) type HistJob = (DocId, u64, std::sync::mpsc::Receiver<(DocId, f64, std::sync::Arc<tone::Histograms>)>);
|
||||
|
||||
/// The Info panel's cached sample: pixel x, y, document revision and Eyedropper Sample Size.
|
||||
type InfoSampleKey = (i32, i32, u64, u32);
|
||||
|
||||
@@ -882,10 +879,14 @@ pub struct PhotocraftApp {
|
||||
pub(crate) paused_playbacks: actions::PausedPlaybacks,
|
||||
/// Levels/Curves histogram cache: (document, adjustment layer, revision it is valid for).
|
||||
pub(crate) tone_hist: Option<(DocId, photocraft_doc::LayerId, u64, std::sync::Arc<tone::Histograms>)>,
|
||||
/// Histogram panel cache: (document, revision, computed at ms, histograms).
|
||||
pub(crate) doc_hist: Option<(DocId, u64, f64, std::sync::Arc<tone::Histograms>)>,
|
||||
/// The document histogram being computed on a worker thread: (document, revision, receiver).
|
||||
pub(crate) hist_job: Option<HistJob>,
|
||||
/// Histogram panel: the document's histogram (`histogram_panel`).
|
||||
pub(crate) doc_hist: Option<histogram_panel::PanelHist>,
|
||||
/// Histogram panel: the histogram of the adjustment previewing on the canvas.
|
||||
pub(crate) doc_hist_preview: Option<histogram_panel::PanelHist>,
|
||||
/// The panel histogram being computed on a worker thread.
|
||||
pub(crate) hist_job: Option<histogram_panel::HistJob>,
|
||||
/// The (document, revision) an Uncached Refresh asked to count at cache level 1.
|
||||
pub(crate) hist_uncached: Option<(DocId, u64)>,
|
||||
/// Free Transform preview (document without the moving pixels + their texture).
|
||||
pub(crate) transform_preview: Option<transform_tool::TransformPreview>,
|
||||
/// Move-tool ⇧/⌥ drag state (move_mods).
|
||||
@@ -1155,7 +1156,9 @@ impl PhotocraftApp {
|
||||
pending_after_prompt: None,
|
||||
tone_hist: None,
|
||||
doc_hist: None,
|
||||
doc_hist_preview: None,
|
||||
hist_job: None,
|
||||
hist_uncached: None,
|
||||
gpu: None,
|
||||
window_device: None,
|
||||
window_lost: false,
|
||||
@@ -1190,6 +1193,7 @@ impl PhotocraftApp {
|
||||
// Saved preferences are in place before the first frame; recovery starts in upkeep.
|
||||
prefs_ui::load(&mut app);
|
||||
layers_panel_ui::restore_options(&mut app);
|
||||
histogram_panel::restore_options(&mut app);
|
||||
// After the saved preferences, which say whether the set was already offered.
|
||||
kys_import::offer_import(&mut app);
|
||||
notices::wayland_file_drop_guidance(&mut app);
|
||||
|
||||
@@ -871,6 +871,10 @@ fn panel_menu(app: &mut PhotocraftApp, ui: &mut egui::Ui, panel: &str) {
|
||||
crate::actions::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
"histogram" => {
|
||||
crate::histogram_panel::panel_menu(app, ui);
|
||||
ui.separator();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1869,7 +1869,7 @@ pub(crate) fn dock_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, group: crate
|
||||
(Group::Properties, _) => adjustments_grid(app, ui),
|
||||
(Group::Character, tab) => crate::type_tool::character_panel(app, ui, tab == 1),
|
||||
(Group::Navigator, 0) => navigator(app, ui),
|
||||
(Group::Navigator, 1) => crate::tone::histogram_panel(app, ui),
|
||||
(Group::Navigator, 1) => crate::histogram_panel::show(app, ui),
|
||||
(Group::Navigator, _) => info_panel(app, ui),
|
||||
(Group::History, 0) => history(app, ui),
|
||||
(Group::History, 1) => crate::actions::panel(app, ui),
|
||||
@@ -1881,6 +1881,29 @@ pub(crate) fn dock_body(app: &mut PhotocraftApp, ui: &mut egui::Ui, group: crate
|
||||
}
|
||||
}
|
||||
|
||||
/// The active document's pixel under the pointer, if the pointer is over the image.
|
||||
pub(crate) fn hover_pixel(app: &PhotocraftApp) -> Option<(i32, i32)> {
|
||||
let size = app.session.active()?.doc.size;
|
||||
app.hover_doc.map(|p| (p[0].floor() as i32, p[1].floor() as i32)).filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32)
|
||||
}
|
||||
|
||||
/// The colour the Info panel reads at document pixel `(x, y)`, straight RGBA 0..1: averaged over
|
||||
/// the Eyedropper's Sample Size, as in Photoshop (#1649), and cached per pixel and revision.
|
||||
pub(crate) fn pointer_sample(app: &mut PhotocraftApp, (x, y): (i32, i32)) -> Option<[f32; 4]> {
|
||||
let rev = app.session.active()?.revision;
|
||||
let sample_size = app.ui.tool_options.eyedropper_size;
|
||||
if let Some(((cx, cy, cr, cs), v)) = app.info_sample
|
||||
&& (cx, cy, cr, cs) == (x, y, rev, sample_size)
|
||||
{
|
||||
return Some(v);
|
||||
}
|
||||
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size});
|
||||
let v: Vec<f32> = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?;
|
||||
let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?];
|
||||
app.info_sample = Some(((x, y, rev, sample_size), v));
|
||||
Some(v)
|
||||
}
|
||||
|
||||
/// Photoshop's Info panel: colour under the pointer (RGB and CMYK), position, selection size.
|
||||
fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
@@ -1888,7 +1911,7 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
empty(ui, tl!("No document"));
|
||||
return;
|
||||
};
|
||||
let (rev, size, origin) = (st.revision, st.doc.size, st.doc.ruler_origin);
|
||||
let (size, origin) = (st.doc.size, st.doc.ruler_origin);
|
||||
let cmyk_space = photocraft_compose::cmyk_space(&st.doc);
|
||||
// Positions and sizes in the ruler unit (Preferences › Units & Rulers).
|
||||
let units = app.session.prefs().units_and_rulers.clone();
|
||||
@@ -1897,10 +1920,7 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let units_y = app.session.prefs().units_and_rulers.clone();
|
||||
let fy = move |px: f64| units_y.format(px, dpi, size.height as f64);
|
||||
let sel = st.doc.selection.as_ref().map(photocraft_compose::bounds::content_bounds);
|
||||
let pos = app
|
||||
.hover_doc
|
||||
.map(|p| (p[0].floor() as i32, p[1].floor() as i32))
|
||||
.filter(|(x, y)| *x >= 0 && *y >= 0 && *x < size.width as i32 && *y < size.height as i32);
|
||||
let pos = hover_pixel(app);
|
||||
// While a guide is dragged (#5728), the Info panel shows its position in one axis only, even
|
||||
// when the pointer is outside the canvas (ruler drags do not update `hover_doc` there).
|
||||
let (guide_x, guide_y) = match app.guide_drag {
|
||||
@@ -1908,20 +1928,7 @@ fn info_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
Some(d) => (None, Some(d.pos)),
|
||||
None => (None, None),
|
||||
};
|
||||
// The readout averages the Eyedropper's Sample Size, as in Photoshop (#1649).
|
||||
let sample_size = app.ui.tool_options.eyedropper_size;
|
||||
let rgba = pos.and_then(|(x, y)| {
|
||||
if let Some(((cx, cy, cr, cs), v)) = app.info_sample
|
||||
&& (cx, cy, cr, cs) == (x, y, rev, sample_size)
|
||||
{
|
||||
return Some(v);
|
||||
}
|
||||
let params = json!({"x": f64::from(x) + 0.5, "y": f64::from(y) + 0.5, "size": sample_size});
|
||||
let v: Vec<f32> = serde_json::from_value(app.session.execute("document.sampleColor", params).ok()?).ok()?;
|
||||
let v = [*v.first()?, *v.get(1)?, *v.get(2)?, *v.get(3)?];
|
||||
app.info_sample = Some(((x, y, rev, sample_size), v));
|
||||
Some(v)
|
||||
});
|
||||
let rgba = pos.and_then(|p| pointer_sample(app, p));
|
||||
let mono = theme::mono(11.5);
|
||||
let row = |ui: &mut egui::Ui, k: &str, v: String| {
|
||||
ui.horizontal(|ui| {
|
||||
|
||||
@@ -1589,6 +1589,12 @@ pub struct UiState {
|
||||
/// Which chip the Color panel edits, and how it shows the colour.
|
||||
#[serde(default)]
|
||||
pub color_panel: ColorPanelState,
|
||||
/// Histogram panel options: view, channel, statistics, colours, source.
|
||||
#[serde(default)]
|
||||
pub histogram_panel: crate::histogram_panel::HistogramPanelState,
|
||||
/// The tonal range dragged across the Histogram panel's graph (its statistics), `[from, to]`.
|
||||
#[serde(default, skip_deserializing)]
|
||||
pub histogram_range: Option<[u8; 2]>,
|
||||
/// Brush Settings: selected section (0 = Brush Tip Shape) and tab (0 settings, 1 Brushes).
|
||||
#[serde(default)]
|
||||
pub brush_section: usize,
|
||||
@@ -1707,6 +1713,8 @@ impl Default for UiState {
|
||||
shell: Default::default(),
|
||||
layer_filter: Vec::new(),
|
||||
layers_panel_options: LayersPanelOptions::default(),
|
||||
histogram_panel: Default::default(),
|
||||
histogram_range: None,
|
||||
layers_panel_dialog: None,
|
||||
layer_filter_by: Default::default(),
|
||||
layer_filter_name: String::new(),
|
||||
|
||||
+106
-232
@@ -1,34 +1,41 @@
|
||||
//! Histograms for the tone editors (Levels, Curves, Threshold) and the Histogram panel.
|
||||
//!
|
||||
//! The adjustment editors themselves live in `adjust_editors`; this module computes and caches
|
||||
//! the histograms they draw behind their controls, in the channels of the adjustment's space
|
||||
//! (RGB, CMYK ink brightness, Lab), and draws them.
|
||||
//! The adjustment editors themselves live in `adjust_editors` and the panel in `histogram_panel`;
|
||||
//! this module computes and caches the histograms they draw, in the channels of the adjustment's
|
||||
//! space (RGB, CMYK ink brightness, Lab), and draws them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Rect, Sense, vec2};
|
||||
use egui::{Color32, Rect};
|
||||
use photocraft_doc::adjust::ToneSpace;
|
||||
use photocraft_doc::{Document, Layer, LayerId};
|
||||
|
||||
use crate::PhotocraftApp;
|
||||
use crate::theme::Tokens;
|
||||
|
||||
const CHANNELS: [(&str, &str); 4] = [("rgb", "RGB"), ("red", "Red"), ("green", "Green"), ("blue", "Blue")];
|
||||
|
||||
static EMPTY: [u32; 256] = [0; 256];
|
||||
|
||||
/// 256-bin histograms: the composite then one per channel of the space (RGB: luminosity, R, G, B;
|
||||
/// CMYK: composite, C, M, Y, K as channel brightness; Lab: L, a, b). `tag` identifies what they
|
||||
/// were computed from (see [`HistSource`]).
|
||||
#[derive(Clone, Debug, Default)]
|
||||
/// 256-bin histograms: the composite then one per channel of the space (RGB: the channel mean,
|
||||
/// R, G, B; CMYK: composite, C, M, Y, K as channel brightness; Lab: L, a, b). `tag` identifies
|
||||
/// what they were computed from (see [`HistSource`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Histograms {
|
||||
pub tag: u64,
|
||||
pub ch: Vec<[u32; 256]>,
|
||||
/// Luminosity of the composite (0.30 R + 0.59 G + 0.11 B), whatever the space;
|
||||
/// empty for a gray plane's.
|
||||
pub lum: [u32; 256],
|
||||
/// Photoshop's histogram cache level of a composite histogram: 1 when every document pixel
|
||||
/// was counted, `n` when a proxy 2^(n-1) times smaller stood in; 0 for a gray plane's.
|
||||
pub level: u32,
|
||||
}
|
||||
|
||||
impl Default for Histograms {
|
||||
fn default() -> Self {
|
||||
Self { tag: 0, ch: Vec::new(), lum: [0; 256], level: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Index<usize> for Histograms {
|
||||
type Output = [u32; 256];
|
||||
fn index(&self, i: usize) -> &[u32; 256] {
|
||||
@@ -46,9 +53,18 @@ pub enum HistSource {
|
||||
/// The gray plane a Curves target edits: a layer mask, a saved channel or the Quick Mask.
|
||||
/// The dialog shows this plane's own levels, not the colour layers beneath (#5335).
|
||||
Channel { layer: LayerId, surface: photocraft_engine::channel_cmds::GraySurface },
|
||||
/// A layer and everything beneath it, the layers above hidden (the Histogram panel's
|
||||
/// Adjustment Composite: what an adjustment layer outputs).
|
||||
UpTo(LayerId),
|
||||
}
|
||||
|
||||
fn tag(source: HistSource, space: ToneSpace) -> u64 {
|
||||
/// The whole composited image (the Histogram panel's Entire Image).
|
||||
pub const IMAGE: HistSource = HistSource::BelowLayer(LayerId(u64::MAX));
|
||||
|
||||
/// The highest histogram cache level: a proxy 2^7 = 128 times smaller.
|
||||
pub const MAX_CACHE_LEVEL: u32 = 8;
|
||||
|
||||
pub(crate) fn tag(source: HistSource, space: ToneSpace) -> u64 {
|
||||
let (k, id) = match source {
|
||||
HistSource::BelowLayer(l) => (1u64, l.0),
|
||||
HistSource::Layer(l) => (2, l.0),
|
||||
@@ -58,6 +74,7 @@ fn tag(source: HistSource, space: ToneSpace) -> u64 {
|
||||
photocraft_engine::channel_cmds::GraySurface::QuickMask => (5, layer.0),
|
||||
photocraft_engine::channel_cmds::GraySurface::FilterMask => (6, layer.0),
|
||||
},
|
||||
HistSource::UpTo(l) => (6, l.0),
|
||||
};
|
||||
let s = match space {
|
||||
ToneSpace::Rgb => 0u64,
|
||||
@@ -78,9 +95,31 @@ fn isolate(layers: &mut [Layer], id: LayerId) -> bool {
|
||||
found
|
||||
}
|
||||
|
||||
/// Histograms of `doc` as seen by `source`, in the channels of `space`.
|
||||
/// Hides every layer composited above `id` (later siblings, and the later siblings of each group
|
||||
/// holding it). Returns whether `id` is in `layers`.
|
||||
fn hide_above(layers: &mut [Layer], id: LayerId) -> bool {
|
||||
let mut found = false;
|
||||
for l in layers.iter_mut() {
|
||||
if found {
|
||||
l.visible = false;
|
||||
} else if l.id == id || l.children_mut().is_some_and(|c| hide_above(c, id)) {
|
||||
found = true;
|
||||
}
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Histograms of `doc` as seen by `source`, in the channels of `space`, at whatever cache level
|
||||
/// the document's size calls for (up to [`MAX_CACHE_LEVEL`]).
|
||||
pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace) -> Histograms {
|
||||
compute_histograms_at(doc, source, space, MAX_CACHE_LEVEL)
|
||||
}
|
||||
|
||||
/// [`compute_histograms`] at cache level `max_level` or below (Preferences › Performance › Cache
|
||||
/// Levels; 1 counts every pixel, the Histogram panel's Uncached Refresh).
|
||||
pub fn compute_histograms_at(doc: &Document, source: HistSource, space: ToneSpace, max_level: u32) -> Histograms {
|
||||
let mut level = 0;
|
||||
let mut lum = [0u32; 256];
|
||||
let mut h = vec![
|
||||
[0u32; 256];
|
||||
match space {
|
||||
@@ -107,16 +146,45 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace)
|
||||
*bin = gray_bins(s, doc.bounds());
|
||||
}
|
||||
}
|
||||
HistSource::BelowLayer(_) | HistSource::Layer(_) => {
|
||||
level = composite_bins(doc, source, space, &mut h);
|
||||
HistSource::BelowLayer(_) | HistSource::Layer(_) | HistSource::UpTo(_) => {
|
||||
// Luminosity rides along as one more histogram after the space's channels.
|
||||
h.push([0; 256]);
|
||||
level = composite_bins(doc, source, space, max_level, &mut h);
|
||||
if let Some(l) = h.pop() {
|
||||
lum = l;
|
||||
}
|
||||
}
|
||||
}
|
||||
Histograms { tag: tag(source, space), ch: h, level }
|
||||
Histograms { tag: tag(source, space), ch: h, lum, level }
|
||||
}
|
||||
|
||||
/// Bins of the composited image below (`BelowLayer`) or of one layer alone (`Layer`), in `space`.
|
||||
/// Returns the cache level counted: 1 when every document pixel was counted, higher when a
|
||||
/// downsampled proxy stood in (like Photoshop's histogram cache levels).
|
||||
/// The largest document counted pixel by pixel at the automatic cache level. The web build counts
|
||||
/// on the UI thread (it has no worker threads), so it reduces documents a quarter that size.
|
||||
fn exact_limit() -> u64 {
|
||||
if cfg!(target_arch = "wasm32") { photocraft_compose::PROXY_THUMBNAIL_PIXELS / 4 } else { photocraft_compose::PROXY_THUMBNAIL_PIXELS }
|
||||
}
|
||||
|
||||
/// The cache level a histogram of `doc` is counted at: 1 (every pixel) up to the size a proxy
|
||||
/// would stand in for, else the level whose 2^(n-1) reduction leaves about 768 pixels on the
|
||||
/// longest side, at most `max_level` (clamped to 1..=[`MAX_CACHE_LEVEL`]).
|
||||
pub fn cache_level(doc: &Document, max_level: u32) -> u32 {
|
||||
let longest = doc.size.width.max(doc.size.height);
|
||||
let k = longest / 768;
|
||||
let auto = if k >= 2 && doc.size.area() > exact_limit() && photocraft_compose::proxy::proxy_faithful(doc) { k.next_power_of_two().ilog2() + 1 } else { 1 };
|
||||
auto.min(max_level.clamp(1, MAX_CACHE_LEVEL))
|
||||
}
|
||||
|
||||
/// How many times smaller the proxy counted at `level` (> 1) is: about 768 pixels on the longest
|
||||
/// side (as at the automatic level), or 2^(level-1) when Cache Levels caps the level below that.
|
||||
fn proxy_factor(doc: &Document, level: u32) -> u32 {
|
||||
let k = doc.size.width.max(doc.size.height) / 768;
|
||||
k.min(1 << (level.clamp(1, MAX_CACHE_LEVEL) - 1)).max(1)
|
||||
}
|
||||
|
||||
/// Bins of the composited image below (`BelowLayer`), up to (`UpTo`) or of one layer alone
|
||||
/// (`Layer`), in `space`, then luminosity in the last of `h`. Returns the cache level counted
|
||||
/// (see [`cache_level`]): 1 when every document pixel was counted, higher when a downsampled proxy
|
||||
/// stood in (like Photoshop's histogram cache levels).
|
||||
///
|
||||
/// The pixels are counted as they are, never blended: an area-averaged thumbnail invented greys
|
||||
/// that aren't in the image wherever an edge fell inside one of its cells (#6538). Documents up to
|
||||
@@ -124,7 +192,7 @@ pub fn compute_histograms(doc: &Document, source: HistSource, space: ToneSpace)
|
||||
/// composited in bands and counted exactly, which costs what the thumbnail did (it reduced the
|
||||
/// same full composite). Larger ones count a nearest-neighbour proxy composite of about the old
|
||||
/// thumbnail's work: it only holds values the layers have.
|
||||
fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut [[u32; 256]]) -> u32 {
|
||||
fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, max_level: u32, h: &mut [[u32; 256]]) -> u32 {
|
||||
let mut d = doc.clone();
|
||||
match source {
|
||||
HistSource::BelowLayer(hide) => {
|
||||
@@ -135,15 +203,13 @@ fn composite_bins(doc: &Document, source: HistSource, space: ToneSpace, h: &mut
|
||||
HistSource::Layer(id) => {
|
||||
isolate(&mut d.layers, id);
|
||||
}
|
||||
HistSource::UpTo(id) => {
|
||||
hide_above(&mut d.layers, id);
|
||||
}
|
||||
HistSource::Channel { .. } => {}
|
||||
}
|
||||
let longest = d.size.width.max(d.size.height);
|
||||
let k = longest / 768;
|
||||
let (d, level) = if k >= 2 && d.size.area() > photocraft_compose::PROXY_THUMBNAIL_PIXELS && photocraft_compose::proxy::proxy_faithful(&d) {
|
||||
(photocraft_compose::proxy::proxy_document(&d, k), k.next_power_of_two().ilog2() + 1)
|
||||
} else {
|
||||
(d, 1)
|
||||
};
|
||||
let level = cache_level(&d, max_level);
|
||||
let d = if level > 1 { photocraft_compose::proxy::proxy_document(&d, proxy_factor(&d, level)) } else { d };
|
||||
let _ = photocraft_compose::render_bands(&d, d.bounds(), 0, |band| -> Result<(), ()> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let part = {
|
||||
@@ -184,10 +250,18 @@ fn add_bins(mut a: Vec<[u32; 256]>, b: Vec<[u32; 256]>) -> Vec<[u32; 256]> {
|
||||
a
|
||||
}
|
||||
|
||||
/// Counts straight-alpha composite pixels into `h` (one histogram per channel of `space`);
|
||||
/// transparent pixels are skipped.
|
||||
/// Luminosity weights (the Histogram panel's Luminosity channel).
|
||||
pub const LUMINOSITY: [f32; 3] = [0.30, 0.59, 0.11];
|
||||
|
||||
/// Counts straight-alpha composite pixels into `h` (one histogram per channel of `space`, then
|
||||
/// luminosity when `h` has room for it); transparent pixels are skipped.
|
||||
fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) {
|
||||
let bin = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as usize;
|
||||
let lum_at = match space {
|
||||
ToneSpace::Rgb => 4,
|
||||
ToneSpace::Cmyk => 5,
|
||||
ToneSpace::Lab => 3,
|
||||
};
|
||||
let mut add = |c: usize, b: usize| {
|
||||
if let Some(n) = h.get_mut(c).and_then(|ch| ch.get_mut(b)) {
|
||||
*n = n.saturating_add(1);
|
||||
@@ -198,6 +272,8 @@ fn count_pixels(px: &[[f32; 4]], space: ToneSpace, h: &mut [[u32; 256]]) {
|
||||
if p[3].is_nan() || p[3] <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let rgb = [p[0], p[1], p[2]].map(|v| v.clamp(0.0, 1.0));
|
||||
add(lum_at, bin(rgb.iter().zip(LUMINOSITY).map(|(v, w)| v * w).sum()));
|
||||
match space {
|
||||
ToneSpace::Rgb => {
|
||||
let q = [p[0], p[1], p[2]].map(bin);
|
||||
@@ -250,7 +326,7 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace)
|
||||
let (doc_id, rev) = (st.doc.id, st.revision);
|
||||
let want = tag(source, space);
|
||||
let layer = match source {
|
||||
HistSource::BelowLayer(l) | HistSource::Layer(l) => l,
|
||||
HistSource::BelowLayer(l) | HistSource::Layer(l) | HistSource::UpTo(l) => l,
|
||||
HistSource::Channel { layer, .. } => layer,
|
||||
};
|
||||
let pixels_kept = view_only(st);
|
||||
@@ -272,7 +348,7 @@ pub fn histograms(app: &mut PhotocraftApp, source: HistSource, space: ToneSpace)
|
||||
|
||||
/// Whether the latest revision changed no pixels (selecting a layer, say): cached histograms of
|
||||
/// the previous revision still hold (#125).
|
||||
fn view_only(st: &photocraft_engine::DocState) -> bool {
|
||||
pub(crate) fn view_only(st: &photocraft_engine::DocState) -> bool {
|
||||
st.last_damage.is_some_and(|r| r.is_empty())
|
||||
}
|
||||
|
||||
@@ -335,134 +411,6 @@ pub fn channel_color(name: &str, t: &Tokens) -> Color32 {
|
||||
}
|
||||
}
|
||||
|
||||
fn channel_picker(ui: &mut egui::Ui, id: egui::Id, label: &str) -> usize {
|
||||
let mut ch: usize = ui.data(|d| d.get_temp(id)).unwrap_or(0);
|
||||
ui.horizontal(|ui| {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
ui.label(egui::RichText::new(tl!(&label)).color(t.text_dim).size(12.0));
|
||||
let opts: Vec<(usize, &str)> = CHANNELS.iter().enumerate().map(|(i, (_, l))| (i, *l)).collect();
|
||||
crate::widgets::dropdown(ui, &format!("{id:?}-ch"), &mut ch, &opts, 110.0);
|
||||
});
|
||||
ui.data_mut(|d| d.insert_temp(id, ch));
|
||||
ch
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Histogram panel
|
||||
|
||||
/// Histogram panel (Window › Histogram): whole-image histogram with Photoshop's statistics.
|
||||
/// Recomputed at most every 250 ms while the document keeps changing (e.g. during painting).
|
||||
pub fn histogram_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let Some(st) = app.session.active() else {
|
||||
ui.label(egui::RichText::new(tl!("No document")).color(t.text_faint));
|
||||
return;
|
||||
};
|
||||
let (doc_id, rev) = (st.doc.id, st.revision);
|
||||
let now = crate::gpu_canvas::now_ms();
|
||||
if view_only(st)
|
||||
&& let Some((d, r, _, _)) = app.doc_hist.as_mut()
|
||||
&& *d == doc_id
|
||||
&& *r + 1 == rev
|
||||
{
|
||||
*r = rev;
|
||||
}
|
||||
let stale = !matches!(&app.doc_hist, Some((d, r, _, _)) if *d == doc_id && *r == rev);
|
||||
let due = app.doc_hist.as_ref().is_none_or(|(d, _, at, _)| *d != doc_id || now - at > 250.0);
|
||||
if stale && due {
|
||||
// Computed off the UI thread (doc clone + proxy + pixel counts cost tens of ms on
|
||||
// large documents): the panel keeps showing the previous histogram with the existing
|
||||
// "cached data" warning until the worker delivers.
|
||||
let pending = app.hist_job.as_ref().is_some_and(|(d, r, _)| *d == doc_id && *r == rev);
|
||||
if !pending {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
// No threads on the web (and a spawn can fail natively): compute inline then, and
|
||||
// deliver through the same channel so one receive path lands both.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let spawned = {
|
||||
let doc = st.doc.clone();
|
||||
let tx = tx.clone();
|
||||
let ctx = ui.ctx().clone();
|
||||
std::thread::Builder::new()
|
||||
.name("histogram".into())
|
||||
.spawn(move || {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let h = Arc::new(compute_histograms(&doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb));
|
||||
let _ = tx.send((doc.id, crate::gpu_canvas::now_ms() - t0, h));
|
||||
ctx.request_repaint();
|
||||
})
|
||||
.is_ok()
|
||||
};
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let spawned = false;
|
||||
if !spawned {
|
||||
let t0 = crate::gpu_canvas::now_ms();
|
||||
let h = Arc::new(compute_histograms(&st.doc, HistSource::BelowLayer(LayerId(u64::MAX)), ToneSpace::Rgb));
|
||||
let _ = tx.send((doc_id, crate::gpu_canvas::now_ms() - t0, h));
|
||||
}
|
||||
app.hist_job = Some((doc_id, rev, rx));
|
||||
}
|
||||
} else if stale {
|
||||
ui.ctx().request_repaint_after(std::time::Duration::from_millis(260));
|
||||
}
|
||||
// A finished worker lands its histogram; the revision check keeps a stale result from
|
||||
// overwriting a newer one. A worker that died without sending clears the job so the next
|
||||
// frame schedules a new one.
|
||||
if let Some((jd, jr, rx)) = &app.hist_job {
|
||||
match rx.try_recv() {
|
||||
Ok((_, ms, h)) => {
|
||||
app.perf.span("histogram", ms);
|
||||
if *jd == doc_id {
|
||||
app.doc_hist = Some((doc_id, *jr, crate::gpu_canvas::now_ms(), h));
|
||||
}
|
||||
app.hist_job = None;
|
||||
}
|
||||
Err(std::sync::mpsc::TryRecvError::Disconnected) => app.hist_job = None,
|
||||
Err(std::sync::mpsc::TryRecvError::Empty) => {}
|
||||
}
|
||||
}
|
||||
let Some((_, _, _, h)) = app.doc_hist.clone() else { return };
|
||||
// 1 when the statistics count every pixel; higher when a downsampled proxy stood in.
|
||||
let level = h.level.max(1);
|
||||
let ch = channel_picker(ui, egui::Id::new("histogram-panel-ch"), "Channel:");
|
||||
let w = ui.available_width();
|
||||
let (r, _) = ui.allocate_exact_size(vec2(w, 100.0), Sense::hover());
|
||||
let p = ui.painter_at(r);
|
||||
p.rect_filled(r, 0.0, t.field);
|
||||
let color = if ch == 0 { Color32::from_gray(if t.pro { 190 } else { 70 }) } else { channel_color(CHANNELS[ch.min(3)].0, &t) };
|
||||
draw_histogram(&p, r, &h[ch], color);
|
||||
if stale {
|
||||
// Photoshop's "cached data" warning triangle while the histogram lags the image.
|
||||
crate::icons::paint(ui, Rect::from_min_size(r.right_top() + vec2(-18.0, 2.0), vec2(16.0, 16.0)), "triangle-alert", 12.0, t.warning);
|
||||
}
|
||||
let hist = &h[ch];
|
||||
let n: u64 = hist.iter().map(|v| *v as u64).sum();
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
let mean = hist.iter().enumerate().map(|(i, v)| i as f64 * *v as f64).sum::<f64>() / n as f64;
|
||||
let var = hist.iter().enumerate().map(|(i, v)| (i as f64 - mean).powi(2) * *v as f64).sum::<f64>() / n as f64;
|
||||
let mut acc = 0u64;
|
||||
let median = hist.iter().position(|v| {
|
||||
acc += *v as u64;
|
||||
acc * 2 >= n
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
egui::Grid::new("hist-stats").num_columns(2).spacing(vec2(12.0, 2.0)).show(ui, |ui| {
|
||||
for (k, v) in [
|
||||
(tl!("Mean:"), format!("{mean:.2}")),
|
||||
(tl!("Std Dev:"), format!("{:.2}", var.sqrt())),
|
||||
(tl!("Median:"), median.unwrap_or(0).to_string()),
|
||||
(tl!("Pixels:"), n.to_string()),
|
||||
(tl!("Cache Level:"), level.to_string()),
|
||||
] {
|
||||
ui.label(egui::RichText::new(k).color(t.text_dim).size(11.5));
|
||||
ui.label(egui::RichText::new(v).font(crate::theme::mono(11.5)).color(t.text));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -633,77 +581,3 @@ mod tests {
|
||||
assert!((mean(&hist[0]) - 255.0 * 3999.0 / 6000.0).abs() < 1.0, "mean {}", mean(&hist[0]));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod hist_async_tests {
|
||||
use super::*;
|
||||
use crate::PhotocraftApp;
|
||||
use serde_json::json;
|
||||
|
||||
/// The panel schedules the histogram on a worker and keeps showing the previous data
|
||||
/// until it lands: right after the trigger the job exists (nothing computed in this
|
||||
/// frame), the receiver delivers, and a stale result cannot overwrite a newer revision.
|
||||
#[test]
|
||||
fn panel_histogram_is_computed_off_the_ui_thread() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
let ctx = egui::Context::default();
|
||||
let _ = &ctx;
|
||||
app.run("file.new", json!({"width": 640, "height": 480})).unwrap();
|
||||
let (doc_id, rev) = {
|
||||
let st = app.session.active().unwrap();
|
||||
(st.doc.id, st.revision)
|
||||
};
|
||||
// Drive one panel frame through a minimal egui pass.
|
||||
let ctx = egui::Context::default();
|
||||
ctx.begin_pass(Default::default());
|
||||
let panel_ui = egui::Ui::new(
|
||||
ctx.clone(),
|
||||
egui::Id::new("hist-test"),
|
||||
egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))),
|
||||
);
|
||||
let mut panel_ui = panel_ui;
|
||||
histogram_panel(&mut app, &mut panel_ui);
|
||||
// A fast worker (or the inline fallback) may already have landed the result this frame.
|
||||
if let Some(job) = app.hist_job.take() {
|
||||
assert_eq!(job.0, doc_id);
|
||||
assert_eq!(job.1, rev);
|
||||
// The worker delivers (its repaint request is a no-op outside a frame).
|
||||
let (did, _, h) = job.2.recv().expect("the worker delivers the histogram");
|
||||
assert_eq!(did, doc_id);
|
||||
assert!(!h.ch.is_empty(), "the histogram has data");
|
||||
// Delivering it for the revision it was computed from lands in the cache.
|
||||
app.doc_hist = Some((doc_id, rev, crate::gpu_canvas::now_ms(), h.clone()));
|
||||
}
|
||||
assert_eq!(app.doc_hist.as_ref().map(|h| (h.0, h.1)), Some((doc_id, rev)));
|
||||
// …and a newer revision keeps the old entry stale instead of being overwritten by it.
|
||||
app.run("layer.new.layer", json!({})).unwrap();
|
||||
let rev2 = app.session.active().unwrap().revision;
|
||||
assert_ne!(rev, rev2);
|
||||
assert_ne!(app.doc_hist.as_ref().unwrap().1, rev2, "stale after an edit");
|
||||
}
|
||||
|
||||
/// A worker that died without sending (its sender dropped) clears the job, so the next
|
||||
/// frame schedules a new one instead of waiting forever.
|
||||
#[test]
|
||||
fn a_dead_histogram_worker_clears_the_job() {
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
|
||||
app.run("file.new", json!({"width": 64, "height": 48})).unwrap();
|
||||
let (doc_id, rev) = {
|
||||
let st = app.session.active().unwrap();
|
||||
(st.doc.id, st.revision)
|
||||
};
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
drop(tx);
|
||||
app.hist_job = Some((doc_id, rev, rx));
|
||||
let ctx = egui::Context::default();
|
||||
ctx.begin_pass(Default::default());
|
||||
let mut ui = egui::Ui::new(
|
||||
ctx.clone(),
|
||||
egui::Id::new("hist-dead"),
|
||||
egui::UiBuilder::new().max_rect(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 200.0))),
|
||||
);
|
||||
histogram_panel(&mut app, &mut ui);
|
||||
assert!(app.hist_job.is_none(), "a disconnected job is dropped");
|
||||
assert!(app.doc_hist.is_none(), "nothing landed from the dead worker");
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
|
||||
- `ui.set` also accepts `tileGrid` (boolean), a developer overlay of the active layer's storage tiles: the tile grid over the document, every stored tile filled and labelled `tx,ty`, tiles with identical pixels in a shared colour and unique ones in blue. It has no menu item and View › Extras doesn't hide it. `ui.inspect` reports it as `view.tile_grid`.
|
||||
- `ui.set` also accepts `strokeTrace` (`true`, `false`, `"stderr"` or `"off"`): turn the stroke latency trace on or off at runtime; each stroke's summary is in `ui.inspect` `perf.strokeTrace`. A CSV file of every frame is set only at launch (`PHOTOCRAFT_STROKE_TRACE=<file.csv>` / `--stroke-trace <file.csv>`): the control channel doesn't write files outside the automation write root
|
||||
- `ui.set` also accepts `layerFilter` (#5048), the Layers panel filter row: `{by?, kinds?, name?, mode?}`, any subset. `by` is `kind`, `name` or `mode` (the filter-type dropdown); `kinds` lists the Kind toggles that are on (`pixel`, `adjustment`, `type`, `shape`, `smart`); `name` matches part of a layer name, ignoring case; `mode` is a blend mode name (`Multiply`, `Pass Through`). Kind and Name filter only once a kind is on or text is typed; Mode always filters, by Normal at first, as in Photoshop. Fields left out keep their value; a bad one is an error and changes nothing.
|
||||
- `ui.set` also accepts the Histogram panel: `histogramPanel` `{view?, channel?, showChannelsInColor?, showStatistics?, source?}` (any subset, kept with the preferences): `view` is `compact`, `expanded` or `allChannels`; `channel` is `composite`, `red`, `green`, `blue`, `cyan`, `magenta`, `yellow`, `black`, `a`, `b`, `luminosity` or `colors` (one the document's mode lacks shows as its composite); `source` is `entireImage`, `selectedLayer` or `adjustmentComposite` (Entire Image is counted in Compact View, when the document has one layer, or when no adjustment layer is selected for Adjustment Composite). `histogramRange` is `[from, to]` (levels 0..255) or `null`: the dragged tonal range whose Count and Percentile the statistics show. `histogramRefresh: true` is Uncached Refresh: the current state is recounted at cache level 1. `ui.inspect` › `histogram` reports the options, the channel and source as they apply, the channels the document offers, whether the shown histogram is `current` (counted for the document's revision, source and cache level the panel wants now), its `cacheLevel`, `maxCacheLevel` (Preferences › Performance › Cache Levels), `preview` (an adjustment's preview is counted) and `stats` (`mean`, `stdDev`, `median`, `pixels`, `level`, `count`, `percentile`, `clipped` percent at 0 and 255). Histograms are counted while the panel is shown.
|
||||
- Each painting tool keeps its own brush, as in Photoshop: `tools.setBrush` and `ui.set {brushSize}` change the active tool's brush, and switching tools swaps in that tool's own (size, hardness, mode, opacity, flow, dynamics, smoothing). A tool used for the first time starts from the brush in hand. The colours, the erase flag and the stroke seed stay shared. So `ui.set {tool: "eraser", brushSize: 12}` sets the Eraser's size, and `ui.set {tool: "brush"}` afterwards brings the Brush's own size back.
|
||||
- Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error.
|
||||
- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255).
|
||||
|
||||
+3
-3
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
|
||||
| [Performance](#performance) | 3 | 22 | 31 | 65 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 27 not run, 4 not measurable yet (baseline 2026-10-05) |
|
||||
| [File compatibility](#file-compatibility) | 10 | 14 | 3 | io corpus: oracle ≥ 148/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 249/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 190/258, round trip ≥ 258/258 |
|
||||
| [Tools](#tools) | 36 | 9 | 0 | |
|
||||
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 18 of 177 (target 0) |
|
||||
| [Workspace and UI](#workspace-and-ui) | 15 | 6 | 2 | settings that do nothing: 17 of 177 (target 0) |
|
||||
| [Type](#type) | 5 | 5 | 0 | |
|
||||
| [Automation](#automation) | 5 | 2 | 4 | 631 of 631 menu items live (100.0%) |
|
||||
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 30 of 30 crates; panic_hunt present |
|
||||
@@ -187,9 +187,9 @@ Corpus floors (`crates/io/tests/it/corpus.rs`): the enforced minimums; the corpu
|
||||
|
||||
## Workspace and UI
|
||||
|
||||
**Settings that do nothing: 18 of 177** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
**Settings that do nothing: 17 of 177** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
|
||||
|
||||
Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.cache_levels`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`.
|
||||
Unread: `general.color_picker`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `performance.gpu_adapter`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `type_.text_engine`, `enhanced_controls.scrubby_slider_acceleration`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`.
|
||||
|
||||
| Id | Target | Status | Issue | Note |
|
||||
|---|---|---|---|---|
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
# UI parity: tools, handles, modifiers and feel
|
||||
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests) · **Target:** Adobe Photoshop 2026
|
||||
> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-24 · **Change:** minor (Histogram panel: Compact / Expanded / All Channels views, Luminosity and Colors channels, Source, range statistics, Uncached Refresh, live adjustment overlay, Cache Levels preference; the font menu opens on the current family, marked in the recent group when it is a recent one, #9160; Type options bar alignment and direction follow the target paragraph; a swatch click recolours selected type and shape layers with any tool, #9238; UI scale presets done: 105–120% steps, #3222; ⇧⌥ blend mode letters; painting tool Mode menus; ⌥ + an adjustment's shortcut reopens it at its last settings, ⌥⌘L / ⌥⌘M, #8900; Crop default mode: moving the image under the box snaps the frame's edges and centre, #8580; View › Extras hides the Move transform controls, #6699; adjustment clipping stays visible in compact Properties, #5231; Color panel modes from its panel menu, the same in every theme, UI-217-17, #6000; a picked colour recolours the selected type and shapes; Hand tool ⌘ / ⌥ are Zoom In / Zoom Out while held, #6434; the wheel steps value fields, #5473; a dragged guide shows its X or Y beside the pointer, #7680; Type options bar "T" icon scrubs the font size, #6437; Move tool: dragged selected pixels take their own outline as the selection, #7538; artboard backgrounds remain below child Free Transform previews; ⌫/Delete removes the selected smart filter, #4751; Object Finder foreground/background discrimination (#6548); rounded triangle, polygon and star corners; shape Fill/Stroke popovers accept hex RGB values, #6176; a guide let go over either ruler is removed, #6286; Crop rows corrected: saved crop presets and Delete Cropped Pixels off are done, #6562; marching ants in device pixels, #7489; Animated Zoom: holding the Zoom tool zooms continuously, #6210; shape Density and Feather, TOOL-214-12, #5846; Pen Auto Add/Delete on the path being drawn, #6140; Show Transform Controls frames every selected layer; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed; selection-modifier and ⌥-wheel rows match their tests) · **Target:** Adobe Photoshop 2026
|
||||
|
||||
How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, the
|
||||
handles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,
|
||||
@@ -227,6 +227,7 @@ Paragraph; the rest open as in-app floating windows.
|
||||
| Color panel modes from its panel menu (Hue Cube, Brightness Cube, Color Wheel, Grayscale/RGB/HSB/CMYK/Lab/Web Color sliders), colour ramp (RGB/CMYK Spectrum, Grayscale Ramp, Current Colors, Make Ramp Web Safe; Shift-click cycles, Alt-click picks the other colour), Copy Color as HTML / Hex Code; the same in every theme | done | `color_panel_ui.rs`, `color_panel_tests.rs`; UI-217-17, #2569, #6000 |
|
||||
| A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools, the Move tool too; a swatch click recolours the selected type layers and shape fills whatever the tool (#9238); one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | |
|
||||
| Window size and dock width remembered | done | UI-217-2 |
|
||||
| Histogram panel: Compact (the default, of the entire image), Expanded and All Channels views (the channel kept across them); RGB/CMYK/Lab/Gray channels, Luminosity and Colors (overlaid, mixed where they overlap); Show Channels in Color and Show Statistics; Source (Entire Image, Selected Layer, Adjustment Composite) for multilayer documents; Mean, Std Dev, Median, Pixels, Level, Count, Percentile and Cache Level for the pointer level or a dragged range; the cached-data warning, Uncached Refresh (menu, button, warning click, double-click); the adjusted histogram over the original while an adjustment previews; Cache Levels 1–8 in Preferences › Performance; Color Sampler levels marked on the graph | partial | `histogram_panel.rs`, `histogram_panel_tests.rs`, `tone.rs`; differs: filter dialogs that preview on the CPU proxy aren't counted live, a selection doesn't limit the histogram yet, with Source Selected Layer an adjustment dialog's preview isn't counted, and new strings are English-only so far |
|
||||
| Command palette with recents | done | UI-217-7 |
|
||||
| Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar |
|
||||
| Every preference takes effect | partial | 46 of 149 do nothing (scorecard) |
|
||||
|
||||
Reference in new issue
Block a user