Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Layers mask thumbnails + chains; Channels/Paths temporary rows and footers (#153, #154) (#191)

Brandon Thomasb22deaa944ba
diff --git a/Cargo.lock b/Cargo.lock
index a8bb6c77a..fa4e727d2 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3681,6 +3681,7 @@ dependencies = [
"photocraft-plugins",
"photocraft-raster",
"photocraft-text",
+ "photocraft-vector",
"rayon",
"serde",
"serde_json",
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index 8a5b4f745..a4b8cba5a 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -18,6 +18,7 @@ photocraft-engine = { workspace = true }
photocraft-plugins = { workspace = true }
photocraft-algo = { workspace = true }
photocraft-text = { workspace = true }
+photocraft-vector = { workspace = true }
egui = { workspace = true }
egui_extras = { version = "0.36", default-features = false, features = ["svg"] }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
diff --git a/crates/ui-egui/src/channels_panel.rs b/crates/ui-egui/src/channels_panel.rs
index 1f4ed1321..32129a878 100644
--- a/crates/ui-egui/src/channels_panel.rs
+++ b/crates/ui-egui/src/channels_panel.rs
@@ -17,6 +17,8 @@ enum Row {
Color(usize),
Alpha(usize),
QuickMask,
+ /// The selected layer's mask: a temporary channel, listed while the layer is selected.
+ LayerMask,
}
impl Row {
@@ -27,6 +29,7 @@ impl Row {
Row::Color(k) => json!({ "color": k }),
Row::Alpha(i) => json!(i),
Row::QuickMask => json!("quickMask"),
+ Row::LayerMask => json!("mask"),
}
}
}
@@ -50,25 +53,38 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
};
let doc = st.doc.clone();
let view = st.channel_view.clone();
+ let active_layer = st.active_layer;
let mode = doc.pixel_format().mode;
let colors = mode.color_channels();
let quick = doc.quick_mask.is_some();
let ctx = ui.ctx().clone();
let thumbs = app.channel_thumbs(&ctx);
+ // The active layer's mask (Photoshop lists it, in italics, below the colour channels).
+ let masked = active_layer.and_then(|id| doc.layer(id)).filter(|l| l.mask.is_some()).cloned();
+ let mask_tex = masked.as_ref().and_then(|l| Some(app.mask_thumb(&ctx, &doc, l.id, l.mask.as_ref()?)));
+ let mask_targeted = masked.is_some() && app.ui.mask_target && view.target == ChannelTarget::Composite && !quick;
// Multichannel images are their ink channels only (no composite or colour rows).
let multichannel = doc.mode == photocraft_doc::ColorMode::Multichannel;
let mut rows = if multichannel { Vec::new() } else { vec![Row::Composite] };
if colors > 1 && !multichannel {
rows.extend((0..colors).map(Row::Color));
}
+ if masked.is_some() {
+ rows.push(Row::LayerMask);
+ }
rows.extend((0..doc.channels.len()).map(Row::Alpha));
if quick {
rows.push(Row::QuickMask);
}
let shown_colors = if colors > 1 { colors } else { 0 };
let mut actions: Vec<(String, Value)> = Vec::new();
+ // The buttons sit in a footer at the panel's bottom, like Photoshop's.
let footer = 34.0;
- egui::ScrollArea::vertical().max_height((ui.available_height() - footer).max(60.0)).auto_shrink([false, true]).show(ui, |ui| {
+ let fill = ui.available_height() > footer + 60.0;
+ let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY };
+ let mut mask_click = None;
+ let mut drawn = Vec::new();
+ egui::ScrollArea::vertical().max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show(ui, |ui| {
for row in rows {
let (name, thumb_idx, slot, visible, selected) = match row {
Row::Composite => (
@@ -76,14 +92,14 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
0,
Some(2),
view.visible_colors(colors) == colors,
- view.target == ChannelTarget::Composite && !quick,
+ view.target == ChannelTarget::Composite && !quick && !mask_targeted,
),
Row::Color(k) => (
channel_cmds::color_names(mode)[k].to_string(),
1 + k,
Some(3 + k),
view.color_visible(k),
- (view.target == ChannelTarget::Composite && !quick) || view.target == ChannelTarget::Color(k),
+ (view.target == ChannelTarget::Composite && !quick && !mask_targeted) || view.target == ChannelTarget::Color(k),
),
Row::Alpha(i) => (
doc.channels[i].name.clone(),
@@ -95,6 +111,7 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
Row::QuickMask => {
("Quick Mask".to_string(), 1 + shown_colors + doc.channels.len(), None, !view.quick_mask_hidden, view.target == ChannelTarget::Composite)
}
+ Row::LayerMask => (masked.as_ref().map(|l| format!("{} Mask", l.name)).unwrap_or_default(), usize::MAX, None, false, mask_targeted),
};
let row_h = if t.pro { 36.0 } else { 40.0 };
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), row_h), Sense::click());
@@ -110,15 +127,24 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
let eye = Rect::from_min_size(pos2(rect.left() + 6.0, rect.center().y - 11.0), vec2(22.0, 22.0));
let eye_resp = ui.interact(eye, ui.id().with(("chan-eye", format!("{:?}", row.reference()))), Sense::click());
- icons::paint(ui, eye, if visible { "eye" } else { "eye-off" }, 14.0, if visible { t.icon } else { t.text_faint });
- if eye_resp.clicked() {
+ // The layer mask's eye slot stays empty: its overlay view isn't supported yet.
+ if row != Row::LayerMask {
+ icons::paint(ui, eye, if visible { "eye" } else { "eye-off" }, 14.0, if visible { t.icon } else { t.text_faint });
+ }
+ if eye_resp.clicked() && row != Row::LayerMask {
actions.push(("channel.setVisible".into(), json!({ "channel": row.reference(), "visible": !visible })));
}
let ts = if t.pro { 28.0 } else { 30.0 };
- let thumb = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - ts / 2.0), vec2(ts, ts));
- if let Some(tex) = thumbs.get(thumb_idx) {
- painter.image(*tex, thumb, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ let cell = Rect::from_min_size(pos2(rect.left() + 36.0, rect.center().y - ts / 2.0), vec2(ts, ts));
+ // Thumbnails keep the document's aspect ratio (the textures are letterboxed squares).
+ let (thumb, uv) = fit_thumb(cell, doc.size.width, doc.size.height);
+ let tex = if row == Row::LayerMask { mask_tex } else { thumbs.get(thumb_idx).copied() };
+ if let Some(tex) = tex {
+ painter.image(tex, thumb, uv, Color32::WHITE);
}
+ drawn.push((name.clone(), thumb));
+ // Rows are painted: name them for screen readers and UI tests.
+ resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name));
// Spot channels: a swatch of the ink on the thumbnail corner.
if let Row::Alpha(i) = row
&& let Some((ink, _)) = doc.channels[i].spot
@@ -127,12 +153,12 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
painter.rect_filled(Rect::from_min_size(thumb.right_bottom() - vec2(9.0, 9.0), vec2(9.0, 9.0)), 0.0, Color32::from_rgb(c[0], c[1], c[2]));
}
painter.rect_stroke(thumb, 0.0, Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }), StrokeKind::Outside);
- let italic = row == Row::QuickMask || matches!(row, Row::Alpha(i) if doc.channels[i].spot.is_some());
+ let italic = matches!(row, Row::QuickMask | Row::LayerMask) || matches!(row, Row::Alpha(i) if doc.channels[i].spot.is_some());
let mut job = egui::text::LayoutJob::default();
let font = if selected && !t.pro { theme::medium(12.5) } else { egui::FontId::proportional(12.0) };
job.append(&name, 0.0, egui::TextFormat { font_id: font, color: t.text, italics: italic, ..Default::default() });
let galley = painter.layout_job(job);
- let text_pos = pos2(thumb.right() + 10.0, rect.center().y - galley.size().y / 2.0);
+ let text_pos = pos2(cell.right() + 10.0, rect.center().y - galley.size().y / 2.0);
painter.galley(text_pos, galley, t.text);
if let Some(slot) = slot {
painter.text(
@@ -146,9 +172,19 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let rename_id = egui::Id::new(("chan-rename", doc.id.0, format!("{:?}", row.reference())));
if resp.clicked() && !eye_resp.clicked() {
let m = ui.input(|i| i.modifiers);
- if m.command {
+ if m.command && row == Row::LayerMask {
+ let layer = masked.as_ref().map(|l| l.id.0);
+ actions.push(("select.loadSelection".into(), json!({ "channel": "mask", "layer": layer, "operation": load_operation(m) })));
+ } else if m.command {
actions.push(("select.loadSelection".into(), json!({ "channel": row.reference(), "operation": load_operation(m) })));
+ } else if row == Row::LayerMask {
+ // Targets the mask, as clicking its thumbnail in the Layers panel does.
+ mask_click = Some(true);
+ actions.push(("channel.target".into(), json!({ "channel": "composite" })));
} else {
+ if matches!(row, Row::Composite | Row::Color(_)) {
+ mask_click = Some(false);
+ }
let target = if row == Row::QuickMask { json!("composite") } else { row.reference() };
actions.push(("channel.target".into(), json!({ "channel": target })));
}
@@ -200,6 +236,11 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
Row::Composite | Row::Color(_) => {
item(ui, a, "Duplicate Channel", "channel.duplicate", json!({ "channel": row.reference() }));
}
+ Row::LayerMask => {
+ let enabled = masked.as_ref().and_then(|l| l.mask.as_ref()).is_none_or(|m| m.enabled);
+ item(ui, a, if enabled { "Disable Layer Mask" } else { "Enable Layer Mask" }, "layer.layerMask.enabled", json!({}));
+ item(ui, a, "Delete Layer Mask", "layer.layerMask.delete", json!({}));
+ }
}
ui.separator();
item(ui, a, "New Channel…", "channel.new", json!({}));
@@ -235,6 +276,10 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
});
});
+ ctx.data_mut(|d| d.insert_temp(thumbs_id(), drawn));
+ if let Some(on) = mask_click {
+ app.ui.mask_target = on;
+ }
for (id, p) in actions {
if id == "ui.renameChannel" {
if let Some(i) = p.as_u64().and_then(|i| doc.channels.get(i as usize)) {
@@ -247,6 +292,25 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
+fn thumbs_id() -> egui::Id {
+ egui::Id::new("channel-thumb-rects")
+}
+
+/// The Channels rows drawn last frame: (name, thumbnail rect).
+pub fn recorded(ctx: &egui::Context) -> Vec<(String, Rect)> {
+ ctx.data(|d| d.get_temp(thumbs_id())).unwrap_or_default()
+}
+
+/// The part of a square `cell` a `w`×`h` document fills, and the matching UVs of a square,
+/// letterboxed thumbnail texture: thumbnails keep the document's aspect ratio.
+pub fn fit_thumb(cell: Rect, w: u32, h: u32) -> (Rect, Rect) {
+ let (w, h) = (w.max(1) as f32, h.max(1) as f32);
+ let (fw, fh) = (w / w.max(h), h / w.max(h));
+ let size = vec2(cell.width() * fw, cell.height() * fh).max(vec2(1.0, 1.0));
+ let uv = Rect::from_center_size(pos2(0.5, 0.5), vec2(fw, fh));
+ (Rect::from_center_size(cell.center(), size), uv)
+}
+
fn item(ui: &mut egui::Ui, actions: &mut Vec<(String, Value)>, label: &str, cmd: &str, p: Value) {
if ui.button(label).clicked() {
actions.push((cmd.into(), p));
diff --git a/crates/ui-egui/src/layer_row_ui.rs b/crates/ui-egui/src/layer_row_ui.rs
index 718fcd0ad..0ba530b6d 100644
--- a/crates/ui-egui/src/layer_row_ui.rs
+++ b/crates/ui-egui/src/layer_row_ui.rs
@@ -25,7 +25,7 @@ const ICON_W: f32 = 14.0;
/// Width of the effects triangle beside the fx badge.
const TRIANGLE_W: f32 = 10.0;
/// The blend-mode label is shown only while the name keeps at least this much room.
-const MIN_NAME_W: f32 = 64.0;
+pub const MIN_NAME_W: f32 = 64.0;
/// A right-hand row indicator.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
diff --git a/crates/ui-egui/src/layer_row_ui/tests.rs b/crates/ui-egui/src/layer_row_ui/tests.rs
index 914511ab5..beca545fc 100644
--- a/crates/ui-egui/src/layer_row_ui/tests.rs
+++ b/crates/ui-egui/src/layer_row_ui/tests.rs
@@ -21,6 +21,8 @@ fn busy() -> photocraft_engine::Session {
let a = s.execute("layer.new.layer", json!({"name": format!("{LONG} {depth}")})).unwrap()["layer"].as_u64().unwrap();
s.execute("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap();
s.execute("layer.layerStyle.dropShadow", json!({"layer": a})).unwrap();
+ // #153: the vector mask thumbnail and both link chains take row width too.
+ s.execute("layer.vectorMask.revealAll", json!({"layer": a})).unwrap();
s.execute("layer.setProps", json!({"layer": a, "blend": "Multiply", "locks": {"all": true}})).unwrap();
s.execute("layer.layerMask.revealAll", json!({"layer": a})).unwrap();
let b = s.execute("layer.new.layer", json!({"name": format!("{LONG} b{depth}")})).unwrap()["layer"].as_u64().unwrap();
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 60fc844c7..dc4cc5828 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -52,6 +52,7 @@ pub mod layer_style;
pub mod layer_tree_ui;
pub mod links;
pub mod liquify_ui;
+pub mod mask_thumbs_ui;
pub mod menu_catalog;
pub mod menu_nav;
pub mod menus;
@@ -226,7 +227,7 @@ pub struct PhotocraftApp {
pub last_canvas_rect: egui::Rect,
pub fps: f32,
last_frame_time: f64,
- thumbs: HashMap<(photocraft_doc::LayerId, bool), (u64, egui::TextureHandle)>,
+ thumbs: HashMap<(photocraft_doc::LayerId, u8), (u64, egui::TextureHandle)>,
/// Snapshots whose live layer/mask keys were last used to prune thumbnail handles.
thumb_documents: Vec<(DocId, std::sync::Weak<Document>)>,
/// Content bounds cached per (key, revision): scanning a 36 MP layer every frame cost ~77 ms.
@@ -807,9 +808,12 @@ impl PhotocraftApp {
let mut live = std::collections::HashSet::new();
let mut pending: Vec<_> = documents.iter().flat_map(|st| &st.doc.layers).collect();
while let Some(layer) = pending.pop() {
- live.insert((layer.id, false));
+ live.insert((layer.id, mask_thumbs_ui::THUMB_LAYER));
if layer.mask.is_some() {
- live.insert((layer.id, true));
+ live.insert((layer.id, mask_thumbs_ui::THUMB_MASK));
+ }
+ if layer.vector_mask.is_some() {
+ live.insert((layer.id, mask_thumbs_ui::THUMB_VECTOR));
}
if let Some(children) = layer.children() {
pending.extend(children);
@@ -833,7 +837,7 @@ impl PhotocraftApp {
// Key by content, not document revision: COW tiles change pointer only when their pixels
// change, so unrelated edits (e.g. painting another layer) don't rebuild this thumbnail.
let rev = layer.surface().map_or(0, surface_fingerprint) ^ (doc.size.width as u64) << 40;
- let key = (layer.id, false);
+ let key = (layer.id, mask_thumbs_ui::THUMB_LAYER);
if let Some((r, tex)) = self.thumbs.get(&key)
&& *r == rev
{
@@ -851,7 +855,7 @@ impl PhotocraftApp {
pub fn mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: photocraft_doc::LayerId, mask: &photocraft_doc::LayerMask) -> egui::TextureId {
let rev = surface_fingerprint(&mask.surface) ^ (doc.size.width as u64) << 40;
- let key = (id, true);
+ let key = (id, mask_thumbs_ui::THUMB_MASK);
if let Some((r, tex)) = self.thumbs.get(&key)
&& *r == rev
{
@@ -865,7 +869,7 @@ impl PhotocraftApp {
self.store_thumb(ctx, key, rev, img)
}
- fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, bool), rev: u64, img: egui::ColorImage) -> egui::TextureId {
+ fn store_thumb(&mut self, ctx: &egui::Context, key: (photocraft_doc::LayerId, u8), rev: u64, img: egui::ColorImage) -> egui::TextureId {
match self.thumbs.get_mut(&key) {
Some((r, tex)) => {
tex.set(img, egui::TextureOptions::LINEAR);
diff --git a/crates/ui-egui/src/mask_thumbs_ui.rs b/crates/ui-egui/src/mask_thumbs_ui.rs
new file mode 100644
index 000000000..cdca7f544
--- /dev/null
+++ b/crates/ui-egui/src/mask_thumbs_ui.rs
@@ -0,0 +1,242 @@
+//! Layers panel row: the mask thumbnails after the layer thumbnail (#153).
+//!
+//! Like Photoshop, each mask (the pixel mask, then the vector mask) gets a link chain and a
+//! thumbnail: the chain shows whether the mask moves with the layer and toggles it on click
+//! (`layer.layerMask.linked` / `layer.vectorMask.linked`); a disabled mask is crossed out with
+//! a red X and ⇧-clicking a mask thumbnail toggles it (`…enabled`). Vector masks render as a
+//! white (revealed) / grey (hidden) thumbnail, cached like the other row thumbnails.
+
+use egui::{Color32, Painter, Pos2, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+use photocraft_doc::{Document, Layer, LayerId, VectorMask};
+use serde_json::{Value, json};
+
+use crate::PhotocraftApp;
+use crate::theme::Tokens;
+
+/// Width of the link-chain slot in front of a mask thumbnail.
+pub const CHAIN_W: f32 = 12.0;
+/// Thumbnail cache kinds (the second half of `PhotocraftApp::thumbs` keys).
+pub const THUMB_LAYER: u8 = 0;
+pub const THUMB_MASK: u8 = 1;
+pub const THUMB_VECTOR: u8 = 2;
+
+/// Which of a layer's masks.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum MaskKind {
+ Pixel,
+ Vector,
+}
+
+impl MaskKind {
+ /// The engine command prefix for this mask.
+ fn command(self) -> &'static str {
+ match self {
+ MaskKind::Pixel => "layer.layerMask",
+ MaskKind::Vector => "layer.vectorMask",
+ }
+ }
+ fn label(self) -> &'static str {
+ match self {
+ MaskKind::Pixel => "layer mask",
+ MaskKind::Vector => "vector mask",
+ }
+ }
+}
+
+/// `(kind, enabled, linked)` for each of `l`'s masks, in row order.
+pub fn masks(l: &Layer) -> Vec<(MaskKind, bool, bool)> {
+ let mut v = Vec::with_capacity(2);
+ if let Some(m) = &l.mask {
+ v.push((MaskKind::Pixel, m.enabled, m.linked));
+ }
+ if let Some(m) = &l.vector_mask {
+ v.push((MaskKind::Vector, m.enabled, m.linked));
+ }
+ v
+}
+
+/// Width `l`'s masks take in a row with `ts`-point thumbnails (chain + thumbnail + gap each).
+pub fn width(l: &Layer, ts: f32) -> f32 {
+ masks(l).len() as f32 * (CHAIN_W + ts + 6.0)
+}
+
+/// Thumbnail size for `l`'s row: `ts`, shrunk (down to 14 pt) when the layer and mask
+/// thumbnails would leave the name less than its minimum of the `room` they share.
+pub fn thumb_size(l: &Layer, ts: f32, room: f32) -> f32 {
+ let n = masks(l).len() as f32;
+ let need = ts + 6.0 + width(l, ts) + crate::layer_row_ui::MIN_NAME_W;
+ let short = need - room;
+ if short <= 0.0 { ts } else { (ts - short / (1.0 + n)).clamp(14.0_f32.min(ts), ts) }
+}
+
+/// Where a row's mask thumbnails and chains went.
+#[derive(Clone, Debug, Default)]
+pub struct MaskRects {
+ pub thumbs: Vec<(MaskKind, Rect)>,
+ pub chains: Vec<(MaskKind, Rect)>,
+ /// A chain was clicked this frame (the row shouldn't treat the click as a selection).
+ pub clicked: bool,
+}
+
+impl MaskRects {
+ pub fn thumb(&self, kind: MaskKind) -> Option<Rect> {
+ self.thumbs.iter().find(|(k, _)| *k == kind).map(|(_, r)| *r)
+ }
+ /// The mask thumbnail under `p`, if any.
+ pub fn hit(&self, p: Pos2) -> Option<MaskKind> {
+ self.thumbs.iter().find(|(_, r)| r.expand(2.0).contains(p)).map(|(k, _)| *k)
+ }
+}
+
+/// Paint `l`'s chains and mask thumbnails from `*x` (just right of the layer thumbnail plus its
+/// gap), advancing `*x` past them, and push chain clicks as commands.
+#[allow(clippy::too_many_arguments)]
+pub fn paint(
+ app: &mut PhotocraftApp,
+ ctx: &egui::Context,
+ ui: &egui::Ui,
+ painter: &Painter,
+ doc: &Document,
+ l: &Layer,
+ x: &mut f32,
+ cy: f32,
+ ts: f32,
+ actions: &mut Vec<(String, Value)>,
+) -> MaskRects {
+ let t = Tokens::get(ctx);
+ let mut out = MaskRects::default();
+ for (kind, enabled, linked) in masks(l) {
+ // The chain sits in the gap before the thumbnail, centred between the two.
+ let chain = Rect::from_min_max(pos2(*x - 4.0, cy - ts / 2.0), pos2(*x - 4.0 + CHAIN_W, cy + ts / 2.0));
+ let resp = ui.interact(chain, ui.id().with(("mask-chain", l.id.0, kind == MaskKind::Vector)), Sense::click());
+ if linked {
+ paint_chain(painter, chain.center(), if resp.hovered() { t.text } else { t.icon });
+ } else if resp.hovered() {
+ paint_chain(painter, chain.center(), t.text_faint);
+ }
+ let (verb, what, name) = (if linked { "Unlink" } else { "Link" }, kind.label(), l.name.clone());
+ let resp = resp.on_hover_text(if linked { "Unlink the mask from the layer" } else { "Link the mask to the layer" });
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, format!("{verb} {what} {name}")));
+ if resp.clicked() {
+ out.clicked = true;
+ actions.push((format!("{}.linked", kind.command()), json!({"layer": l.id.0, "linked": !linked})));
+ }
+ out.chains.push((kind, chain));
+ *x += CHAIN_W - 2.0;
+ let r = Rect::from_min_size(pos2(*x, cy - ts / 2.0), vec2(ts, ts));
+ if ui.is_rect_visible(r) {
+ let tex = match kind {
+ MaskKind::Pixel => l.mask.as_ref().map(|m| app.mask_thumb(ctx, doc, l.id, m)),
+ MaskKind::Vector => l.vector_mask.as_ref().map(|m| app.vector_mask_thumb(ctx, doc, l.id, m)),
+ };
+ if let Some(tex) = tex {
+ painter.image(tex, r, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
+ }
+ if !enabled {
+ // Photoshop's red X over a disabled mask.
+ let st = Stroke::new(1.5, t.danger);
+ let k = r.shrink(1.0);
+ painter.line_segment([k.left_top(), k.right_bottom()], st);
+ painter.line_segment([k.right_top(), k.left_bottom()], st);
+ }
+ }
+ painter.rect_stroke(
+ r,
+ if t.pro { 0.0 } else { 4.0 },
+ Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }),
+ StrokeKind::Outside,
+ );
+ out.thumbs.push((kind, r));
+ *x += ts + 6.0 + 2.0;
+ }
+ let rects = (out.thumbs.clone(), out.chains.clone());
+ ctx.data_mut(|d| d.get_temp_mut_or_default::<std::collections::HashMap<u64, Rects>>(rects_id()).insert(l.id.0, rects));
+ out
+}
+
+type Rects = (Vec<(MaskKind, Rect)>, Vec<(MaskKind, Rect)>);
+
+fn rects_id() -> egui::Id {
+ egui::Id::new("mask-thumb-rects")
+}
+
+/// The mask thumbnails and chains last drawn for layer `id` (for tests and automation).
+pub fn recorded(ctx: &egui::Context, id: u64) -> Option<Rects> {
+ ctx.data(|d| d.get_temp::<std::collections::HashMap<u64, Rects>>(rects_id())).and_then(|m| m.get(&id).cloned())
+}
+
+/// A small vertical chain: two interlocking links.
+fn paint_chain(painter: &Painter, c: Pos2, color: Color32) {
+ let st = Stroke::new(1.2, color);
+ let link = vec2(5.0, 7.0);
+ painter.rect_stroke(Rect::from_center_size(c - vec2(0.0, 2.5), link), 2.0, st, StrokeKind::Middle);
+ painter.rect_stroke(Rect::from_center_size(c + vec2(0.0, 2.5), link), 2.0, st, StrokeKind::Middle);
+}
+
+/// The command a click on mask thumbnail `kind` issues with modifiers `m`, if it is one that
+/// replaces the normal click (⇧: toggle the mask on/off, like Photoshop).
+pub fn click_command(l: &Layer, kind: MaskKind, m: egui::Modifiers) -> Option<(String, Value)> {
+ if !m.shift || m.command {
+ return None;
+ }
+ let enabled = masks(l).into_iter().find(|(k, _, _)| *k == kind)?.1;
+ Some((format!("{}.enabled", kind.command()), json!({"layer": l.id.0, "enabled": !enabled})))
+}
+
+/// Cheap identity of a vector mask's geometry and state.
+pub fn vector_fingerprint(m: &VectorMask) -> u64 {
+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
+ let mut mix = |v: u64| h = (h ^ v).wrapping_mul(0x100_0000_01b3);
+ mix(u64::from(m.path.inverted) | u64::from(m.path.fill_rule == photocraft_doc::FillRule::EvenOdd) << 1);
+ mix(u64::from(m.density.to_bits()));
+ for s in &m.path.subpaths {
+ mix(u64::from(s.closed) | (s.op as u64) << 1 | (s.knots.len() as u64) << 8);
+ for k in &s.knots {
+ for p in [k.anchor, k.in_ctrl, k.out_ctrl] {
+ mix(p.x.to_bits());
+ mix(p.y.to_bits());
+ }
+ }
+ }
+ h
+}
+
+/// A `side`-pixel square thumbnail of vector mask `m`: white where it reveals, grey where it
+/// hides, letterboxed to the document's aspect like the other row thumbnails. Disabled masks
+/// still show their shape (the row crosses them out).
+pub fn vector_thumb_image(doc: &Document, m: &VectorMask, side: usize) -> egui::ColorImage {
+ let (w, h) = (f64::from(doc.size.width.max(1)), f64::from(doc.size.height.max(1)));
+ let s = side as f64 / w.max(h);
+ let (ox, oy) = ((side as f64 - w * s) / 2.0, (side as f64 - h * s) / 2.0);
+ let shown = VectorMask { path: m.path.transform(&photocraft_geom::Affine { m: [s, 0.0, 0.0, s, ox, oy] }), enabled: true, ..m.clone() };
+ let n = side as i32;
+ let values = photocraft_vector::vector_mask_values(&shown, photocraft_geom::Rect::new(0, 0, n, n));
+ let (x0, y0, x1, y1) = (ox.floor() as usize, oy.floor() as usize, (ox + w * s).ceil() as usize, (oy + h * s).ceil() as usize);
+ let mut px = vec![Color32::TRANSPARENT; side * side];
+ for (i, p) in px.iter_mut().enumerate() {
+ let (tx, ty) = (i % side, i / side);
+ if tx < x0 || ty < y0 || tx >= x1 || ty >= y1 {
+ continue;
+ }
+ let v = values.get(i).copied().unwrap_or(1.0).clamp(0.0, 1.0);
+ *p = Color32::from_gray((128.0 + 127.0 * v + 0.5) as u8);
+ }
+ egui::ColorImage::new([side, side], px)
+}
+
+impl PhotocraftApp {
+ /// Cached thumbnail of `l`'s vector mask (see [`vector_thumb_image`]).
+ pub fn vector_mask_thumb(&mut self, ctx: &egui::Context, doc: &Document, id: LayerId, m: &VectorMask) -> egui::TextureId {
+ let rev = vector_fingerprint(m) ^ (u64::from(doc.size.width) << 40) ^ (u64::from(doc.size.height) << 20);
+ let key = (id, THUMB_VECTOR);
+ if let Some((r, tex)) = self.thumbs.get(&key)
+ && *r == rev
+ {
+ return tex.id();
+ }
+ self.store_thumb(ctx, key, rev, vector_thumb_image(doc, m, 64))
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/crates/ui-egui/src/mask_thumbs_ui/tests.rs b/crates/ui-egui/src/mask_thumbs_ui/tests.rs
new file mode 100644
index 000000000..9726dba1f
--- /dev/null
+++ b/crates/ui-egui/src/mask_thumbs_ui/tests.rs
@@ -0,0 +1,204 @@
+//! #153: mask thumbnails, link chains and the red X in Layers rows; #154: the layer mask in
+//! Channels, the layer's path in Paths, aspect-correct channel thumbnails, the Paths footer.
+
+use egui::{Modifiers, PointerButton, Pos2, Rect, pos2, vec2};
+use egui_kittest::Harness;
+use egui_kittest::kittest::Queryable;
+use serde_json::json;
+
+use super::{MaskKind, THUMB_VECTOR, recorded, vector_thumb_image};
+use crate::PhotocraftApp;
+
+/// A 200×100 document: "Masked" (pixel + vector mask) and a "Badge" shape layer.
+fn session() -> (photocraft_engine::Session, u64, u64) {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 200, "height": 100})).unwrap();
+ let masked = s.execute("layer.new.layer", json!({"name": "Masked"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap();
+ s.execute("layer.layerMask.revealAll", json!({"layer": masked})).unwrap();
+ let path = json!({"subpaths": [{"knots": [[20, 10], [120, 10], [120, 90], [20, 90]]}]});
+ s.execute("layer.vectorMask.add", json!({"layer": masked, "path": path})).unwrap();
+ let shape =
+ s.execute("shape.create", json!({"kind": "rect", "rect": [140, 20, 40, 40], "fill": "#cc3333", "name": "Badge"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.select", json!({"layer": masked})).unwrap();
+ (s, masked, shape)
+}
+
+fn harness(session: photocraft_engine::Session, tab: usize, ppp: f32, dock_width: f32) -> Harness<'static, PhotocraftApp> {
+ let mut h = Harness::builder().with_size(vec2(1440.0, 1000.0)).with_pixels_per_point(ppp).with_max_steps(64).build_eframe(move |cc| {
+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
+ PhotocraftApp::new(session, crate::Services::default())
+ });
+ let ctx = h.ctx.clone();
+ let (req, _rx) = crate::control::ControlRequest::new(
+ "ui.set",
+ json!({"theme": "promedium", "dockWidth": dock_width, "dockTabs": {"layers": tab}, "dock": {"collapsed": ["color", "properties", "history", "navigator"]}}),
+ );
+ crate::control::handle(h.state_mut(), &ctx, &req);
+ h.run_steps(8);
+ h
+}
+
+fn click_with(h: &mut Harness<'_, PhotocraftApp>, at: Pos2, modifiers: Modifiers) {
+ h.hover_at(at);
+ h.event(egui::Event::ModifiersChanged(modifiers));
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers });
+ h.run_steps(1);
+ h.event(egui::Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers });
+ h.run_steps(1);
+ h.event(egui::Event::ModifiersChanged(Modifiers::NONE));
+ h.run_steps(2);
+}
+
+fn layer(h: &Harness<'_, PhotocraftApp>, id: u64) -> photocraft_doc::Layer {
+ let st = h.state().session.active().unwrap();
+ st.doc.layer(photocraft_doc::LayerId(id)).unwrap().clone()
+}
+
+#[test]
+fn rows_show_both_mask_thumbnails_with_chains_and_cache_the_vector_one() {
+ for ppp in [1.0, 2.0] {
+ let (s, masked, _) = session();
+ let h = harness(s, 0, ppp, 290.0);
+ let (thumbs, chains) = recorded(&h.ctx, masked).expect("mask thumbnails drawn");
+ assert_eq!(thumbs.iter().map(|(k, _)| *k).collect::<Vec<_>>(), [MaskKind::Pixel, MaskKind::Vector]);
+ assert_eq!(chains.len(), 2);
+ // layer thumbnail | chain | pixel mask | chain | vector mask, without overlaps.
+ for i in 0..2 {
+ assert!(chains[i].1.right() <= thumbs[i].1.left() + 0.01, "@{ppp}x chain {i} before its thumbnail");
+ }
+ assert!(thumbs[0].1.right() <= chains[1].1.left() + 0.01);
+ let row = crate::layer_row_ui::recorded(&h.ctx).into_iter().find(|r| r.layer == masked).unwrap();
+ assert!(row.name.unwrap().left() >= thumbs[1].1.right(), "@{ppp}x the name starts after the masks");
+ assert!(h.state().thumbs.contains_key(&(photocraft_doc::LayerId(masked), THUMB_VECTOR)), "vector thumbnail cached");
+ }
+}
+
+#[test]
+fn deleting_the_vector_mask_prunes_its_thumbnail() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ let key = (photocraft_doc::LayerId(masked), THUMB_VECTOR);
+ assert!(h.state().thumbs.contains_key(&key));
+ h.state_mut().run("layer.vectorMask.delete", json!({"layer": masked})).unwrap();
+ h.run_steps(3);
+ assert!(!h.state().thumbs.contains_key(&key));
+}
+
+#[test]
+fn the_chain_toggles_linking_and_it_survives_psd() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ let p = h.get_by_label("Unlink layer mask Masked").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert!(!layer(&h, masked).mask.unwrap().linked);
+ let p = h.get_by_label("Unlink vector mask Masked").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert!(!layer(&h, masked).vector_mask.unwrap().linked);
+ let doc = (*h.state().session.active().unwrap().doc).clone();
+ let bytes = photocraft_io::export(&doc, "m.psd", &Default::default()).unwrap().bytes;
+ let back = photocraft_io::import("m.psd", &bytes).unwrap().document;
+ let l = back.walk().into_iter().map(|(_, _, l)| l.clone()).find(|l| l.name == "Masked").unwrap();
+ assert!(!l.mask.unwrap().linked && !l.vector_mask.unwrap().linked, "unlinked state round-trips PSD");
+ // Clicking the (now empty) chain slot links again.
+ let p = h.get_by_label("Link layer mask Masked").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert!(layer(&h, masked).mask.unwrap().linked);
+}
+
+#[test]
+fn shift_click_disables_a_mask() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 0, 1.0, 290.0);
+ for kind in [MaskKind::Pixel, MaskKind::Vector] {
+ let r = recorded(&h.ctx, masked).unwrap().0.into_iter().find(|(k, _)| *k == kind).unwrap().1;
+ click_with(&mut h, r.center(), Modifiers::SHIFT);
+ h.run_steps(2);
+ }
+ let l = layer(&h, masked);
+ assert!(!l.mask.unwrap().enabled && !l.vector_mask.unwrap().enabled);
+}
+
+#[test]
+fn vector_thumbnail_is_white_inside_grey_outside_at_the_document_aspect() {
+ let (s, masked, _) = session();
+ let doc = s.active().unwrap().doc.clone();
+ let vm = doc.layer(photocraft_doc::LayerId(masked)).unwrap().vector_mask.clone().unwrap();
+ let img = vector_thumb_image(&doc, &vm, 64);
+ let at = |x: usize, y: usize| img.pixels[y * 64 + x];
+ // 200×100 doc in 64 px: 0.32 scale, rows 16..48. The mask covers x 20..120, y 10..90.
+ assert_eq!(at(20, 32), egui::Color32::from_gray(255), "inside reveals");
+ assert_eq!(at(55, 32), egui::Color32::from_gray(128), "outside hides");
+ assert_eq!(at(20, 4), egui::Color32::TRANSPARENT, "letterbox");
+}
+
+#[test]
+fn channels_list_the_layer_mask_and_keep_the_aspect() {
+ let (s, masked, _) = session();
+ let mut h = harness(s, 1, 1.0, 290.0);
+ let rows = crate::channels_panel::recorded(&h.ctx);
+ let names: Vec<_> = rows.iter().map(|(n, _)| n.as_str()).collect();
+ assert_eq!(names, ["RGB", "Red", "Green", "Blue", "Masked Mask"], "the mask is a temporary row below the colour channels");
+ for (n, r) in &rows {
+ assert!((r.width() / r.height() - 2.0).abs() < 0.05, "{n}: 2:1 thumbnail, got {r:?}");
+ }
+ assert!(!h.state().ui.mask_target);
+ let p = h.get_by_label("Masked Mask").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert!(h.state().ui.mask_target, "clicking the mask row targets the mask");
+ assert_eq!(crate::canvas::paint_target(h.state()), json!("mask"));
+ h.run_steps(2);
+ let p = h.get_by_label("RGB").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert!(!h.state().ui.mask_target, "the composite targets the pixels again");
+ // A layer without a mask has no mask row.
+ h.state_mut().run("layer.layerMask.delete", json!({"layer": masked})).unwrap();
+ h.run_steps(3);
+ assert!(crate::channels_panel::recorded(&h.ctx).iter().all(|(n, _)| !n.ends_with("Mask")));
+}
+
+#[test]
+fn paths_list_the_layer_path_above_a_bottom_footer() {
+ let (s, masked, shape) = session();
+ let mut h = harness(s, 2, 1.0, 290.0);
+ let row = h.get_by_label("Masked Vector Mask").rect();
+ let footer = crate::vector_ui::paths_footer(&h.ctx).expect("footer drawn");
+ assert!(footer.top() > row.bottom(), "buttons below the rows");
+ let group = crate::dock::last_rects(&h.ctx).into_iter().find(|(g, _)| *g == crate::dock::Group::Layers).unwrap().1;
+ assert!(group.bottom() - footer.bottom() < 16.0, "footer at the panel bottom: footer {footer:?}, group {group:?}");
+ assert!(footer.bottom() - row.bottom() > 100.0, "the footer is pinned, not right below the rows");
+ h.state_mut().run("layer.select", json!({"layer": shape})).unwrap();
+ h.run_steps(3);
+ assert!(h.query_by_label("Badge Shape Path").is_some());
+ assert!(h.query_by_label("Masked Vector Mask").is_none(), "only the selected layer's path");
+ // Selecting the temporary row targets the layer's path: Load as selection uses it.
+ let p = h.get_by_label("Badge Shape Path").rect().center();
+ click_with(&mut h, p, Modifiers::NONE);
+ assert_eq!(h.state().ui.selected_path.as_deref(), Some("layer"));
+ // Footer: fill, stroke, load as selection, … (24 pt buttons, 2 pt apart).
+ let footer = crate::vector_ui::paths_footer(&h.ctx).unwrap();
+ let p = pos2(footer.left() + 2.0 * 26.0 + 12.0, footer.center().y);
+ click_with(&mut h, p, Modifiers::NONE);
+ let sel = h.state().session.active().unwrap().doc.selection.clone().expect("selection from the shape path");
+ let b = sel.content_bounds();
+ assert!(b.x0.abs_diff(140) <= 1 && b.width().abs_diff(40) <= 1, "{b:?}");
+ let _ = masked;
+}
+
+#[test]
+fn panels_never_panic_on_odd_documents() {
+ // Rows render for a 1×1 and a very wide document, and the fitted thumbnails stay finite.
+ for (w, hgt) in [(1, 1), (2000, 3)] {
+ for tab in 0..3 {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": w, "height": hgt})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("layer.layerMask.hideAll", json!({})).unwrap();
+ s.execute("layer.vectorMask.revealAll", json!({})).unwrap();
+ let _ = harness(s, tab, 1.0, 250.0);
+ }
+ }
+ let (r, uv) = crate::channels_panel::fit_thumb(Rect::from_min_size(pos2(0.0, 0.0), vec2(28.0, 28.0)), 0, 0);
+ assert!(r.is_finite() && uv.is_finite() && r.width() > 0.0);
+}
diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs
index 8c28c5641..6e95a1fad 100644
--- a/crates/ui-egui/src/panels.rs
+++ b/crates/ui-egui/src/panels.rs
@@ -1356,14 +1356,15 @@ fn layer_row(
if eye_resp.clicked() {
actions.push(("layer.setProps".into(), json!({"layer": l.id.0, "visible": !l.visible})));
}
- let ts = if t.pro { 24.0 } else { 34.0 };
- // Everything but the indentation and the name, so a narrow panel squeezes the indentation first.
- let fixed = 6.0
+ // Everything but the thumbnails, the indentation and the name, so a narrow panel squeezes
+ // the indentation first, then the thumbnails (a layer with two masks has three).
+ let others = 6.0
+ 28.0
+ if l.is_group() { crate::layer_tree_ui::TRIANGLE_W } else { 0.0 }
+ if l.clipped { 12.0 } else { 0.0 }
- + (ts + 6.0) * if l.mask.is_some() { 2.0 } else { 1.0 }
+ crate::layer_row_ui::reserved_width(l);
+ let ts = crate::mask_thumbs_ui::thumb_size(l, if t.pro { 24.0 } else { 34.0 }, rect.width() - others);
+ let fixed = others + ts + 6.0 + crate::mask_thumbs_ui::width(l, ts);
x += 28.0 + crate::layer_row_ui::indent(depth, rect.width(), fixed);
let toggled = crate::layer_tree_ui::disclosure(ui, rect, &mut x, l, actions);
if l.clipped {
@@ -1373,22 +1374,9 @@ fn layer_row(
let thumb = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts));
draw_layer_thumb(app, ctx, ui, doc, l, thumb, row.primary);
x += ts + 6.0;
- let mut mask_rect = None;
- if let Some(m) = &l.mask {
- let mr = Rect::from_min_size(pos2(x, rect.center().y - ts / 2.0), vec2(ts, ts));
- if ui.is_rect_visible(mr) {
- let tex = app.mask_thumb(ctx, doc, l.id, m);
- painter.image(tex, mr, Rect::from_min_max(egui::Pos2::ZERO, pos2(1.0, 1.0)), Color32::WHITE);
- }
- painter.rect_stroke(
- mr,
- if t.pro { 0.0 } else { 4.0 },
- Stroke::new(1.0, if t.pro { Color32::from_gray(20) } else { t.field_border }),
- StrokeKind::Outside,
- );
- mask_rect = Some(mr);
- x += ts + 6.0;
- }
+ // Link chains and pixel / vector mask thumbnails (#153).
+ let masks = crate::mask_thumbs_ui::paint(app, ctx, ui, &painter, doc, l, &mut x, rect.center().y, ts, actions);
+ let mask_rect = masks.thumb(crate::mask_thumbs_ui::MaskKind::Pixel);
// Photoshop frames the targeted thumbnail (pixels or mask) of the active layer with corner brackets.
if row.primary {
let target = if app.ui.mask_target { mask_rect } else { Some(thumb) };
@@ -1434,15 +1422,26 @@ fn layer_row(
(on_mask || thumb.expand(2.0).contains(p))
.then(|| json!({"channel": if on_mask { "mask" } else { "transparency" }, "layer": l.id.0, "operation": crate::channels_panel::load_operation(m)}))
});
+ // ⇧-click a mask thumbnail: disable / enable that mask.
+ let mask_toggle = resp.clicked().then(|| (ui.input(|i| i.modifiers), resp.interact_pointer_pos())).and_then(|(m, pos)| {
+ let kind = masks.hit(pos?)?;
+ crate::mask_thumbs_ui::click_command(l, kind, m)
+ });
if let Some(p) = thumb_load {
actions.push(("select.loadSelection".into(), p));
- } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled {
+ } else if let Some(cmd) = mask_toggle {
+ actions.push(cmd);
+ } else if resp.clicked() && !eye_resp.clicked() && !toggled && !fx_toggled && !masks.clicked {
let mode = select_mode(ui.input(|i| i.modifiers));
actions.push(("layer.select".into(), json!({"layer": l.id.0, "mode": mode})));
// Clicking a thumbnail picks what painting targets; adjustment/fill layers target their mask.
let pos = resp.interact_pointer_pos();
let on_mask = mask_rect.zip(pos).is_some_and(|(r, p)| r.expand(2.0).contains(p));
let on_thumb = pos.is_some_and(|p| thumb.expand(2.0).contains(p));
+ // The vector mask thumbnail picks the layer's path in the Paths panel.
+ if pos.and_then(|p| masks.hit(p)) == Some(crate::mask_thumbs_ui::MaskKind::Vector) {
+ app.ui.selected_path = Some("layer".into());
+ }
let content_less = matches!(l.content, LayerContent::Adjustment(_) | LayerContent::Fill(_));
if on_mask || (content_less && l.mask.is_some()) {
actions.push(("ui.maskTarget".into(), json!(true)));
diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs
index 4d84c3519..60af5fb20 100644
--- a/crates/ui-egui/src/vector_ui.rs
+++ b/crates/ui-egui/src/vector_ui.rs
@@ -540,6 +540,8 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra
fn thumb(ui: &egui::Ui, r: Rect, path: &Path, doc: &Document) {
let t = Tokens::get(ui.ctx());
+ // At the document's aspect ratio, like the Channels thumbnails.
+ let r = crate::channels_panel::fit_thumb(r, doc.size.width, doc.size.height).0;
ui.painter().rect_filled(r, 0.0, Color32::from_gray(if t.pro { 222 } else { 240 }));
let (w, h) = (doc.size.width.max(1) as f64, doc.size.height.max(1) as f64);
let s = (r.width() as f64 / w).min(r.height() as f64 / h);
@@ -554,6 +556,55 @@ fn thumb(ui: &egui::Ui, r: Rect, path: &Path, doc: &Document) {
}
}
+/// What a Paths panel row is.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PathRow {
+ Saved,
+ Work,
+ /// The selected layer's shape path or vector mask (temporary, italic).
+ Layer,
+}
+
+/// A Paths panel row.
+#[derive(Clone, Debug)]
+pub struct PathEntry {
+ pub name: String,
+ pub path: Path,
+ pub kind: PathRow,
+}
+
+/// The Paths panel's rows, top to bottom: saved paths, the work path, then the selected layer's
+/// shape path ("<Layer> Shape Path") or vector mask ("<Layer> Vector Mask"), like Photoshop.
+pub fn path_rows(doc: &Document, active: Option<photocraft_doc::LayerId>) -> Vec<PathEntry> {
+ let mut rows: Vec<_> = doc.paths.iter().map(|p| PathEntry { name: p.name.clone(), path: p.path.clone(), kind: PathRow::Saved }).collect();
+ if let Some(wp) = &doc.work_path {
+ rows.push(PathEntry { name: "Work Path".into(), path: wp.clone(), kind: PathRow::Work });
+ }
+ if let Some(l) = active.and_then(|id| doc.layer(id)) {
+ let layer_path = match &l.content {
+ LayerContent::Shape(sh) => Some((format!("{} Shape Path", l.name), sh.path.clone())),
+ _ => l.vector_mask.as_ref().map(|v| (format!("{} Vector Mask", l.name), v.path.clone())),
+ };
+ if let Some((name, path)) = layer_path {
+ rows.push(PathEntry { name, path, kind: PathRow::Layer });
+ }
+ }
+ rows
+}
+
+fn footer_id() -> egui::Id {
+ egui::Id::new("paths-footer")
+}
+
+fn ctx_data_footer(ctx: &egui::Context, r: Rect) {
+ ctx.data_mut(|d| d.insert_temp(footer_id(), r));
+}
+
+/// Where the Paths panel's button footer was drawn last frame.
+pub fn paths_footer(ctx: &egui::Context) -> Option<Rect> {
+ ctx.data(|d| d.get_temp(footer_id()))
+}
+
pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
let t = Tokens::get(ui.ctx());
let Some(st) = app.session.active() else {
@@ -561,51 +612,79 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
return;
};
let doc = st.doc.clone();
- let mut rows: Vec<(String, Path, bool)> = doc.paths.iter().map(|p| (p.name.clone(), p.path.clone(), false)).collect();
- if let Some(wp) = &doc.work_path {
- rows.push(("Work Path".into(), wp.clone(), true));
- }
- if rows.is_empty() {
- ui.label(egui::RichText::new("Draw with the Pen tool (P) or make a work path from a selection.").color(t.text_faint).size(11.5));
- }
+ let rows = path_rows(&doc, st.active_layer);
+ let has_layer_path = rows.iter().any(|r| r.kind == PathRow::Layer);
let mut action: Option<(&str, Value)> = None;
- for (name, path, work) in &rows {
- let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
- let key = if *work { "work".to_string() } else { name.clone() };
- let sel = app.ui.selected_path.as_deref() == Some(key.as_str());
- if sel {
- ui.painter().rect_filled(r, 0.0, t.row_selected);
- } else if resp.hovered() {
- ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
- }
- thumb(ui, Rect::from_min_size(pos2(r.left() + 8.0, r.top() + 4.0), vec2(28.0, 28.0)), path, &doc);
- let mut job = egui::text::LayoutJob::default();
- job.append(name, 0.0, egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text, italics: *work, ..Default::default() });
- let g = ui.painter().layout_job(job);
- ui.painter().galley(pos2(r.left() + 46.0, r.center().y - g.size().y / 2.0), g, t.text);
- if resp.clicked() {
- app.ui.selected_path = Some(key.clone());
- }
- // Double-clicking the Work Path saves it (Photoshop's "Save Path").
- if resp.double_clicked() && *work {
- let n = doc.paths.len() + 1;
- action = Some(("path.rename", json!({"name": "work", "to": format!("Path {n}")})));
- }
- ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));
- }
+ // The buttons sit in a footer at the panel's bottom, like Photoshop's.
+ let footer = 34.0;
+ let fill = ui.available_height() > footer + 60.0;
+ let rows_h = if fill { ui.available_height() - footer } else { f32::INFINITY };
+ egui::ScrollArea::vertical().id_salt("path-rows").max_height(rows_h).min_scrolled_height(if fill { rows_h } else { 0.0 }).auto_shrink([false, !fill]).show(
+ ui,
+ |ui| {
+ if rows.is_empty() {
+ ui.label(egui::RichText::new("Draw with the Pen tool (P) or make a work path from a selection.").color(t.text_faint).size(11.5));
+ }
+ for PathEntry { name, path, kind } in &rows {
+ let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 36.0), Sense::click());
+ let key = match kind {
+ PathRow::Work => "work".to_string(),
+ PathRow::Layer => "layer".to_string(),
+ PathRow::Saved => name.clone(),
+ };
+ // Rows are painted: name them for screen readers and UI tests.
+ resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::SelectableLabel, true, name));
+ let sel = app.ui.selected_path.as_deref() == Some(key.as_str());
+ if sel {
+ ui.painter().rect_filled(r, 0.0, t.row_selected);
+ } else if resp.hovered() {
+ ui.painter().rect_filled(r, 0.0, t.hover.gamma_multiply(0.5));
+ }
+ thumb(ui, Rect::from_min_size(pos2(r.left() + 8.0, r.top() + 4.0), vec2(28.0, 28.0)), path, &doc);
+ let mut job = egui::text::LayoutJob::default();
+ // Temporary paths (the work path, the selected layer's shape path or vector mask) are italic.
+ let italics = *kind != PathRow::Saved;
+ job.append(name, 0.0, egui::TextFormat { font_id: egui::FontId::proportional(12.0), color: t.text, italics, ..Default::default() });
+ let g = ui.painter().layout_job(job);
+ ui.painter().galley(pos2(r.left() + 46.0, r.center().y - g.size().y / 2.0), g, t.text);
+ if resp.clicked() {
+ app.ui.selected_path = Some(key.clone());
+ }
+ // Double-clicking the Work Path saves it (Photoshop's "Save Path").
+ if resp.double_clicked() && *kind == PathRow::Work {
+ let n = doc.paths.len() + 1;
+ action = Some(("path.rename", json!({"name": "work", "to": format!("Path {n}")})));
+ }
+ ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));
+ }
+ },
+ );
ui.add_space(4.0);
- let sel = app.ui.selected_path.clone().unwrap_or_else(|| "work".into());
- ui.horizontal(|ui| {
+ crate::widgets::hairline(ui);
+ ui.add_space(2.0);
+ let sel = app.ui.selected_path.clone().filter(|s| s != "layer" || has_layer_path).unwrap_or_else(|| "work".into());
+ let footer_rect = ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = 2.0;
let fg = hex(app.session.tools.foreground);
- let items: [(&str, &str, &str, Value); 6] = [
+ let mut n = doc.paths.len() + 1;
+ while doc.paths.iter().any(|p| p.name == format!("Path {n}")) {
+ n += 1;
+ }
+ let items: [(&str, &str, &str, Value); 7] = [
("paint-bucket", "Fill path with foreground color", "path.fill", json!({"name": sel, "color": fg})),
("circle", "Stroke path with brush", "path.stroke", json!({"name": sel, "tool": "brush"})),
("square-dashed", "Load path as a selection", "path.toSelection", json!({"name": sel})),
("spline", "Make work path from selection", "select.toWorkPath", json!({"tolerance": 2.0})),
("square", "Add vector mask", "layer.vectorMask.fromPath", json!({"name": sel})),
+ ("square-plus", "Create new path", "path.set", json!({"name": format!("Path {n}"), "path": {"subpaths": []}})),
("trash", "Delete path", "path.delete", json!({"name": sel})),
];
+ // The layer's own path: deleting it deletes the vector mask (a shape keeps its path).
+ let shape = rows.iter().any(|r| r.kind == PathRow::Layer && r.name.ends_with(" Shape Path"));
+ let delete_layer_path = sel == "layer" && !shape;
+ let items = items.map(|(icon, tip, cmd, p)| {
+ if cmd == "path.delete" && delete_layer_path { (icon, "Delete vector mask", "layer.vectorMask.delete", json!({})) } else { (icon, tip, cmd, p) }
+ });
for (icon, tip, cmd, p) in items {
let icon = if crate::icons::exists(icon) { icon } else { "square" };
if crate::icons::button(ui, icon, 24.0, false, tip).clicked() {
@@ -613,6 +692,7 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
}
}
});
+ ctx_data_footer(ui.ctx(), footer_rect.response.rect);
if let Some((cmd, p)) = action
&& let Err(e) = app.run(cmd, p)
{