appearance-w9: net change of 2 commits

- appearance-w9: written from its sheet
- appearance-w9: repair 1
This commit is contained in:
bflatastic
2026-11-21 23:31:00 +07:00
parent 33eb7d96f7
commit f5ef149deb
2 changed files with 527 additions and 439 deletions
+93 -86
View File
@@ -2,25 +2,36 @@
//! mask (and edits it), Alt-click again shows the artwork. In isolation mode neither a click nor an
//! Alt-click edits the mask.
use craft_ui::ThumbTarget;
use egui::Modifiers;
use serde_json::json;
use vectorcraft_engine::Session;
use super::*;
// PLAN: assumed path of op.A15's `Panel` harness.
use crate::panels::tests_panel::Panel;
/// One frame of the Transparency panel with `events`, `modifiers` held.
fn frame(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>, modifiers: egui::Modifiers) {
let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect();
let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| transparency::show(app, ui));
out.textures_delta.clear();
/// The name of the mask row, which holds the two thumbnails.
const ROW: &str = "Opacity Mask";
fn run(app: &mut VectorcraftApp, id: &str, p: serde_json::Value) -> serde_json::Value {
app.session.execute(id, &p).unwrap()
}
/// Click the mask thumbnail with `modifiers` held.
fn click_mask(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui::Modifiers) {
frame(ctx, app, vec![], egui::Modifiers::NONE);
let at = ctx.read_response(egui::Id::unique(transparency::MASK_THUMB)).expect("the mask thumbnail is drawn").rect.center();
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers };
frame(ctx, app, vec![egui::Event::PointerMoved(at), button(true), button(false)], modifiers);
frame(ctx, app, vec![], egui::Modifiers::NONE);
/// A 100 × 100 document with two rectangles, the second the mask of the first (both selected for Make Mask).
fn masked() -> (VectorcraftApp, u64) {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "transparency.makeOpacityMask", json!({}));
(app, a)
}
/// Click the mask thumbnail with `mods` held.
fn click_mask(panel: &mut Panel, mods: Modifiers) {
panel.click_part(ROW, ThumbTarget::Extra(0).part(), mods);
}
/// In pattern editing mode a click or an Alt-click on the mask thumbnail of a masked object in the
@@ -29,66 +40,66 @@ fn click_mask(ctx: &egui::Context, app: &mut VectorcraftApp, modifiers: egui::Mo
/// mask.
#[test]
fn the_mask_thumbnail_does_not_edit_the_mask_in_pattern_editing_mode() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "transparency.makeOpacityMask", json!({}));
let (mut app, a) = masked();
run(&mut app, "select.set", json!({"ids": [a]}));
run(&mut app, "object.pattern.make", json!({"name": "P"}));
let tile = app.session.active().unwrap().isolation;
let ctx = egui::Context::default();
for modifiers in [egui::Modifiers::NONE, egui::Modifiers::ALT] {
app.ui.status.clear();
click_mask(&ctx, &mut app, modifiers);
let mut panel = Panel::new(app, transparency::show);
for mods in [Modifiers::NONE, Modifiers::ALT] {
panel.app().ui.status.clear();
click_mask(&mut panel, mods);
let app = panel.app();
let st = app.session.active().unwrap();
assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "{modifiers:?}");
assert!(st.doc.pattern_edit.is_some() && st.isolation == tile, "{modifiers:?}");
assert!(app.ui.status.ends_with("finish editing the pattern first"), "{modifiers:?}: {}", app.ui.status);
assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "{mods:?}");
assert!(st.doc.pattern_edit.is_some() && st.isolation == tile, "{mods:?}");
assert!(app.ui.status.ends_with("finish editing the pattern first"), "{mods:?}: {}", app.ui.status);
}
run(&mut app, "shape.rectangle", json!({"x": 60, "y": 0, "width": 30, "height": 30}));
assert!(!crate::menus::enabled(&app, "transparency.makeOpacityMask"), "Make Mask is off for one object");
run(&mut app, "object.pattern.done", json!({}));
run(&mut app, "select.set", json!({"ids": [a]}));
click_mask(&ctx, &mut app, egui::Modifiers::NONE);
assert_eq!(app.session.active().unwrap().doc.mask_edit.map(|e| e.object.0), Some(a));
run(&mut panel.app(), "shape.rectangle", json!({"x": 60, "y": 0, "width": 30, "height": 30}));
assert!(!crate::menus::enabled(&panel.app(), "transparency.makeOpacityMask"), "Make Mask is off for one object");
run(&mut panel.app(), "object.pattern.done", json!({}));
run(&mut panel.app(), "select.set", json!({"ids": [a]}));
click_mask(&mut panel, Modifiers::NONE);
assert_eq!(panel.app().session.active().unwrap().doc.mask_edit.map(|e| e.object.0), Some(a));
}
/// What a click on the mask thumbnail with each modifier does, outside and inside mask editing.
#[test]
fn alt_clicking_the_mask_thumbnail_views_only_the_mask() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "transparency.makeOpacityMask", json!({}));
let ctx = egui::Context::default();
let viewed = |app: &VectorcraftApp| app.session.active().unwrap().shown_mask().map(|n| n.0);
click_mask(&ctx, &mut app, egui::Modifiers::ALT);
assert_eq!(viewed(&app), Some(a));
assert!(app.session.active().unwrap().doc.mask_edit.is_some(), "viewing the mask edits it");
click_mask(&ctx, &mut app, egui::Modifiers::ALT);
assert_eq!(viewed(&app), None);
assert!(app.session.active().unwrap().doc.mask_edit.is_some(), "still editing");
// A plain click while editing does nothing; Alt views again.
click_mask(&ctx, &mut app, egui::Modifiers::NONE);
assert_eq!(viewed(&app), None);
click_mask(&ctx, &mut app, egui::Modifiers::ALT);
assert_eq!(viewed(&app), Some(a));
}
/// Where the panel painted `label`, in a frame of it.
fn label_at(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) -> egui::Pos2 {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| transparency::show(app, ui));
out.textures_delta.clear();
let at = out.shapes.iter().find_map(|c| match &c.shape {
egui::Shape::Text(t) if t.galley.text() == label => Some(t.visual_bounding_rect().center()),
_ => None,
});
at.unwrap_or_else(|| panic!("the panel draws {label:?}"))
// (modifiers, editing before, viewed after, editing after, disabled after)
let table = [
(Modifiers::NONE, false, None, true, false),
(Modifiers::NONE, true, None, true, false),
(Modifiers::SHIFT, false, None, false, true),
(Modifiers::ALT, false, Some(true), true, false),
(Modifiers::ALT, true, Some(true), true, false),
];
for (mods, editing, viewed, edits, disabled) in table {
let (mut app, a) = masked();
if editing {
run(&mut app, "transparency.editOpacityMask", json!({"id": a}));
}
let mut panel = Panel::new(app, transparency::show);
click_mask(&mut panel, mods);
let app = panel.app();
let st = app.session.active().unwrap();
let shown = st.shown_mask().map(|n| n.0);
assert_eq!(shown, viewed.map(|_| a), "{mods:?} editing={editing}");
assert_eq!(st.doc.mask_edit.is_some(), edits, "{mods:?} editing={editing}");
drop(app);
let info = panel.app().session.execute("transparency.opacityMaskInfo", &json!({})).unwrap();
assert_eq!(info[0]["disabled"] == true, disabled, "{mods:?} editing={editing}");
}
// Alt again shows the artwork, still editing.
let (mut app, a) = masked();
run(&mut app, "transparency.editOpacityMask", json!({"id": a}));
let mut panel = Panel::new(app, transparency::show);
for want in [Some(a), None] {
click_mask(&mut panel, Modifiers::ALT);
let app = panel.app();
let st = app.session.active().unwrap();
assert_eq!(st.shown_mask().map(|n| n.0), want);
assert!(st.doc.mask_edit.is_some(), "still editing");
}
}
/// In isolation mode a click or an Alt-click on the mask thumbnail does not edit the mask, and the
@@ -96,40 +107,36 @@ fn label_at(ctx: &egui::Context, app: &mut VectorcraftApp, label: &str) -> egui:
/// take into mask editing. After Exit Isolation Mode a click edits the mask.
#[test]
fn the_mask_thumbnail_does_not_edit_the_mask_in_isolation_mode() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
let b = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "transparency.makeOpacityMask", json!({}));
let (mut app, a) = masked();
let c = run(&mut app, "shape.rectangle", json!({"x": 60, "y": 0, "width": 30, "height": 30}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, c]}));
let g = run(&mut app, "object.group", json!({}))["id"].as_u64().unwrap();
run(&mut app, "object.isolate", json!({"id": g}));
run(&mut app, "select.set", json!({"ids": [a]}));
let ctx = egui::Context::default();
for modifiers in [egui::Modifiers::NONE, egui::Modifiers::ALT] {
app.ui.status.clear();
click_mask(&ctx, &mut app, modifiers);
let mut panel = Panel::new(app, transparency::show);
for mods in [Modifiers::NONE, Modifiers::ALT] {
panel.app().ui.status.clear();
click_mask(&mut panel, mods);
let app = panel.app();
let st = app.session.active().unwrap();
assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "{modifiers:?}");
assert!(st.doc.mask_edit.is_none() && st.shown_mask().is_none(), "{mods:?}");
assert_eq!(st.isolation.map(|i| i.0), Some(g));
assert!(app.ui.status.ends_with("exit isolation mode first"), "{modifiers:?}: {}", app.ui.status);
assert!(app.ui.status.ends_with("exit isolation mode first"), "{mods:?}: {}", app.ui.status);
}
// One object without a mask: Make Mask is off, and a click on it does nothing.
run(&mut app, "select.set", json!({"ids": [c]}));
app.ui.status.clear();
frame(&ctx, &mut app, vec![], egui::Modifiers::NONE);
let at = label_at(&ctx, &mut app, "Make Mask");
let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE };
frame(&ctx, &mut app, vec![egui::Event::PointerMoved(at), button(true), button(false)], egui::Modifiers::NONE);
run(&mut panel.app(), "select.set", json!({"ids": [c]}));
panel.app().ui.status.clear();
panel.frame();
assert!(!panel.enabled("Make Mask"), "the button is off");
panel.click("Make Mask");
let app = panel.app();
let st = app.session.active().unwrap();
let id = vectorcraft_doc::NodeId(c.as_u64().unwrap());
assert!(st.doc.node(id).unwrap().extras().mask.is_none() && st.doc.mask_edit.is_none());
assert_eq!(app.ui.status, "", "the button is off");
run(&mut app, "object.exitIsolation", json!({}));
run(&mut app, "select.set", json!({"ids": [a]}));
click_mask(&ctx, &mut app, egui::Modifiers::NONE);
assert_eq!(app.session.active().unwrap().doc.mask_edit.map(|e| e.object.0), Some(a));
drop(app);
run(&mut panel.app(), "object.exitIsolation", json!({}));
run(&mut panel.app(), "select.set", json!({"ids": [a]}));
click_mask(&mut panel, Modifiers::NONE);
assert_eq!(panel.app().session.active().unwrap().doc.mask_edit.map(|e| e.object.0), Some(a));
}
+434 -353
View File
@@ -4,233 +4,329 @@
//! neutral → off) and Opacity & Mask Define Knockout Shape; the menu's Page Isolated Blending and
//! Page Knockout Group.
// PLAN: assumed `craft_ui` re-exports every framework item imported here; adjust the paths to the facade's modules.
use std::cell::RefCell;
use std::sync::Arc;
use egui::{Sense, Stroke, StrokeKind, Ui, vec2};
use serde_json::json;
use vectorcraft_color::{BlendMode, Paint};
use vectorcraft_doc::{Knockout, Node, NodeId, OpacityMask};
use craft::behavior::Mixed;
use craft::behavior::item_source::keyed;
use craft_ui::menu::PanelRow;
use craft_ui::{
Bind, Button, Checkbox, CollectionEvent, Column, CommandRef, CommandState, CommandStates, ContentPainterCx, ContentPainterCx as _, Divider,
IconId, IconSpec, List, ListRow, LoadFailure, LoadedPicture, NumberField, Priority, Revision, Row, RowEvent, Select, SelectMode, Shade,
Text, ThumbJob, ThumbPaint, ThumbRender, ThumbRequest, ThumbSize, ThumbSource, ThumbTarget, Thumbnails, ThumbnailOptions, UnitKind,
};
use egui::{Color32, Stroke, Ui};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Knockout, Node, NodeId, OpacityMask};
use vectorcraft_engine::cmd::TransparencyInfo;
use super::{current_paints, current_transparency, live_run, pstate, selection_len, set_pstate};
use crate::theme::Tokens;
use crate::widgets::{self, TransparencyEdit, menu_item};
use crate::{VectorcraftApp, icons};
use super::edits::{EditPath, apply_edits};
use super::{current_paints, current_transparency, live_run, selection_len};
use crate::VectorcraftApp;
use crate::widgets::fields::blend_entries; // PLAN: assumed path of wg.S8's `blend_entries`
/// Interaction id of the mask thumbnail.
pub(super) const MASK_THUMB: &str = "tr-mask-thumb";
/// The side of the mask row's thumbnails, in points.
// PLAN: should come from the `size.thumb.lg` token; the row's `ThumbSize::Large` gives the rect, this only sizes the render.
const THUMB_POINTS: f32 = 48.0;
/// The command ids of the menu's own rows.
const THUMBNAILS: &str = "ui.transparency.thumbnails";
const OPTIONS: &str = "ui.transparency.options";
/// What the panel remembers between passes: which blocks the menu hid.
#[derive(Clone, Debug, Default)]
pub(crate) struct TransparencyPanel {
/// The thumbnails and the opacity-mask controls are hidden.
pub(crate) hide_thumbs: bool,
/// The Isolate Blending and knockout options are hidden.
pub(crate) hide_options: bool,
}
/// The cache key of [`state`]: document, revision, selection size and ends, and the picked mesh points.
pub(crate) type StateKey = (u64, u64, usize, Option<NodeId>, Option<NodeId>, Option<Vec<(NodeId, Vec<usize>)>>);
/// The first target of `info` as the document holds it.
fn first_node(app: &VectorcraftApp, info: &TransparencyInfo) -> Option<Arc<Node>> {
let st = app.session.active()?;
info.ids.first().and_then(|id| super::layers::node_arc(&st.doc, *id))
}
/// The panel's values ([`vectorcraft_engine::Session::transparency_info`]) and its first target
/// (the selection, or the object whose mask is being edited), recomputed only when the document
/// or the selection changes, or other gradient mesh points are picked. The target is the `Arc` the
/// document holds.
fn state(app: &VectorcraftApp, ctx: &egui::Context) -> (TransparencyInfo, Option<Arc<Node>>) {
type Key = (u64, u64, usize, Option<NodeId>, Option<NodeId>, Option<Vec<(NodeId, Vec<usize>)>>);
pub(crate) fn state(app: &mut VectorcraftApp) -> (TransparencyInfo, Option<Arc<Node>>) {
let Some(st) = app.session.active() else { return Default::default() };
let sel = &st.selection.objects;
let key: Key = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied(), app.session.mesh_points_picked());
let id = egui::Id::unique("tr-state");
if let Some((k, v)) = ctx.data(|d| d.get_temp::<(Key, (TransparencyInfo, Option<Arc<Node>>))>(id))
&& k == key
let key: StateKey = (st.uid, st.revision, sel.len(), sel.first().copied(), sel.last().copied(), app.session.mesh_points_picked());
// PLAN: assumed `app.caches.transparency_state: Option<(StateKey, TransparencyInfo, Option<Arc<Node>>)>` (hub-w1, `CanvasCache`).
if let Some((k, info, n)) = &app.caches.transparency_state
&& *k == key
{
return v;
return (info.clone(), n.clone());
}
let info = app.session.transparency_info();
let first = info.ids.first().and_then(|id| super::layers::node_arc(&st.doc, *id));
let v = (info, first);
ctx.data_mut(|d| d.insert_temp(id, (key, v.clone())));
v
let first = first_node(app, &info);
app.caches.transparency_state = Some((key, info.clone(), first.clone()));
(info, first)
}
/// Whether the object-only controls apply: while a mask is edited, or when the Appearance panel's
/// active row is the object itself (a fill or stroke has no mask, isolation or knockout).
fn object_controls(app: &VectorcraftApp, editing: bool) -> bool {
editing || app.session.appearance_item().is_none()
}
/// The key of one mask-row thumbnail: the masked object, the background it sits on and which picture it is.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) struct MaskKey {
uid: u64,
/// The object that carries the mask.
node: NodeId,
bg: Option<[u8; 4]>,
/// True: the mask's art. False: the object drawn without its mask.
own_mask: bool,
}
/// The mask row's pictures, rendered as jobs so a drag never waits for them.
pub(crate) struct MaskThumbs<'a> {
doc: &'a Arc<Document>,
revision: u64,
}
thread_local! {
static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new());
}
/// The picture of `obj` (without its mask) or of its mask's art, `px` on a side; `None` when there is nothing to draw.
fn thumb_image(doc: &Arc<Document>, obj: &Node, own_mask: bool, px: u32, bg: Option<[u8; 4]>) -> Option<egui::ColorImage> {
let bare;
let n: &Node = if own_mask {
&obj.extras().mask.as_deref()?.art
} else if obj.extras().mask.is_some() {
bare = {
let mut bare = obj.clone();
bare.extras_mut().mask = None;
bare
};
&bare
} else {
obj
};
let img = RENDERER.with(|r| r.borrow_mut().render_node_thumbnail_with(doc, n, px.max(8), bg, &super::layers::thumb_options()))?;
Some(crate::canvas::color_image(&img))
}
impl ThumbSource<MaskKey> for MaskThumbs<'_> {
fn revision(&self, key: &MaskKey, _: &ThumbRequest) -> Revision {
Revision::of(&(self.revision, key.node, key.bg, key.own_mask))
}
fn render(&self, key: &MaskKey, request: &ThumbRequest) -> ThumbRender {
let Some(obj) = super::layers::node_arc(self.doc, key.node) else { return ThumbRender::Blank };
let (doc, px, bg, own_mask) = (self.doc.clone(), request.side, key.bg, key.own_mask);
let job: ThumbJob = Box::new(move |_| {
Ok(thumb_image(&doc, &obj, own_mask, px, bg).map_or(LoadedPicture::Blank, LoadedPicture::Image))
});
let _: Option<LoadFailure> = None;
ThumbRender::Later(job)
}
}
/// The command a click on the mask thumbnail runs: Shift disables or enables the mask, Alt views only
/// the mask, a plain click edits it (none while it is being edited).
fn mask_click(m: &OpacityMask, id: NodeId, mods: craft_keymap::Mods, editing: bool) -> Option<(&'static str, Value)> {
if mods.shift {
Some((if m.disabled { "transparency.enableOpacityMask" } else { "transparency.disableOpacityMask" }, json!({})))
} else if mods.alt {
Some(("transparency.viewOpacityMask", json!({"id": id.0})))
} else if !editing {
Some(("transparency.editOpacityMask", json!({"id": id.0})))
} else {
None
}
}
/// The one-row list of the object's and the mask's thumbnails with the mask's link; the events it reported.
fn mask_row(
app: &VectorcraftApp,
ui: &mut Ui,
n: Option<&Arc<Node>>,
mask: Option<&OpacityMask>,
editing: bool,
object: bool,
) -> Vec<CollectionEvent<(), RowEvent>> {
let Some(st) = app.session.active() else { return vec![] };
let source = MaskThumbs { doc: &st.doc, revision: st.revision };
let store = Thumbnails::<MaskKey>::in_context(ui.ctx(), "vc-mask-thumbs", ThumbnailOptions::new());
let request = ThumbRequest::for_cell(THUMB_POINTS, ui.ctx().pixels_per_point());
// PLAN: assumed `Priority::Visible`.
let state_of = |ui: &Ui, node: NodeId, bg, own_mask| {
store.state(ui.ctx(), &source, &MaskKey { uid: st.uid, node, bg, own_mask }, &request, Priority::Visible)
};
let bg = mask.map(|m| if m.clip != m.invert { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
let object_state = n.map(|n| state_of(ui, n.id, None, false));
let mask_state = n.zip(mask).map(|(n, _)| state_of(ui, n.id, bg, true));
let fill = n.and_then(|_| current_paints(app).0.color()).map(|c| super::c32(&c));
let paper = ThumbPaint::default().paper(craft_ui::DataColor::new(if bg == Some([0, 0, 0, 255]) { Color32::BLACK } else { Color32::WHITE }));
let plain = ThumbPaint::default();
let (has_mask, disabled) = (mask.is_some(), mask.is_some_and(|m| m.disabled));
let (store, object_state, mask_state) = (&store, &object_state, &mask_state);
let paint_object = move |cx: &ContentPainterCx, rect: egui::Rect| {
if !object_state.as_ref().is_some_and(|s| store.paint(cx, rect, s, &plain))
&& let Some(c) = fill
{
// PLAN: a colour from data should go through the content painter's data path, not the raw painter.
cx.painter.rect_filled(rect.shrink(rect.width() * 0.2), 0.0, c);
}
};
let paint_mask = move |cx: &ContentPainterCx, rect: egui::Rect| {
if has_mask {
if let Some(s) = mask_state {
store.paint(cx, rect, s, &paper);
}
if disabled {
let red = Stroke::new(2.0, Color32::from_rgb(220, 40, 40));
cx.painter.line_segment([rect.left_top(), rect.right_bottom()], red);
cx.painter.line_segment([rect.right_top(), rect.left_bottom()], red);
}
} else {
cx.icon(rect, &IconSpec::svg(IconId::new("dc-mask-none")));
}
};
let mut row = ListRow::new(tl!("Opacity Mask")).thumbnails_only().thumb(ThumbSize::Large, paint_object).extra_thumb(paint_mask);
if let Some(m) = mask {
row = row.thumb_link(m.linked, if m.linked { tl!("Unlink the mask") } else { tl!("Link the mask") });
}
let mut row = Some(row.thumb_target(if editing { ThumbTarget::Extra(0) } else { ThumbTarget::First }));
let keys = [()];
List::<()>::new(tl!("Opacity mask thumbnails"))
.select(SelectMode::None)
.enabled(object)
.show_items(ui, &keyed(&keys, |_| ()), &mut |_, _| row.take().unwrap_or_else(|| ListRow::new("")))
.events
}
/// The Transparency panel: blend mode and opacity of the selection, or of the Appearance panel's active fill/stroke (whose object-only controls are greyed out), the opacity mask and the knockout options.
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
let t = Tokens::get(ui.ctx());
// While editing a mask the panel shows the masked object (the selection is its mask art).
let editing = app.session.active().and_then(|d| d.doc.mask_edit);
let (info, n) = state(app, ui.ctx());
let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some());
let (info, n) = state(app);
let has = n.is_some();
let (isolate, knockout_shape) = (info.isolate.unwrap_or(false), info.knockout_shape.unwrap_or(false));
// Opacity and blend of the Appearance panel's active item (not while a mask is edited: the
// panel then shows the masked object), else of the targets, blank where they differ; with no
// target, the defaults for new art.
let item = editing.is_none().then(|| app.session.appearance_item()).flatten().and_then(|_| current_transparency(app));
// A fill/stroke's transparency is only its opacity and blend: what applies to whole objects
// (the opacity mask, isolation, knockout) is greyed out meanwhile.
let object = editing.is_some() || app.session.appearance_item().is_none();
let item = (!editing).then(|| app.session.appearance_item()).flatten().and_then(|_| current_transparency(app));
let object = object_controls(app, editing);
let (op, blend) = match item {
Some((o, b)) => (Some(o), Some(b)),
None if has => (info.opacity.map(|o| (o / 100.0) as f32), info.blend),
None => (Some(1.0), Some(BlendMode::Normal)),
None => (Some(1.0), Some(vectorcraft_color::BlendMode::Normal)),
};
match widgets::opacity_blend(ui, "tr", op, blend, has) {
Some(TransparencyEdit::Blend(b)) => {
app.run("transparency.set", json!({"blend": b.label()})).ok();
}
Some(TransparencyEdit::Opacity(o, phase)) => live_run(app, "Opacity", "transparency.set", json!({ "opacity": o }), phase),
None => {}
}
widgets::divider(ui);
// Thumbnails and the opacity-mask controls.
let hide_thumbs: bool = pstate(ui.ctx(), "tr-hide-thumbs");
let mask = n.as_ref().and_then(|n| n.extras().mask.as_deref());
let (new_clip, new_invert) = app.session.new_mask_defaults();
ui.add_enabled_ui(object, |ui| {
ui.horizontal(|ui| {
if !hide_thumbs {
let (r, oresp) = ui.allocate_exact_size(vec2(60.0, 50.0), Sense::click());
ui.painter().rect_filled(r, 0.0, egui::Color32::WHITE);
// The thumbnail being edited is outlined (object normally, the mask while editing it).
let (obj_w, mask_w) = if editing.is_some() { (0.5, 1.5) } else { (1.5, 1.0) };
ui.painter().rect_stroke(r, 0.0, Stroke::new(obj_w, t.border), StrokeKind::Outside);
if editing.is_some() && oresp.on_hover_text(tl!("Stop editing the opacity mask")).clicked() {
app.run("transparency.stopEditingOpacityMask", json!({})).ok();
}
if let Some(n) = &n
&& !node_thumb(app, ui, "tr-obj", n, r.shrink(3.0), None, false)
{
let (f, s) = current_paints(app);
let inner = r.shrink2(vec2(6.0, 10.0));
widgets::paint_chip(ui, inner, &f);
if let Some(c) = s.color()
&& !matches!(s, Paint::None)
{
ui.painter().rect_stroke(inner, 0.0, Stroke::new(1.0, super::c32(&c)), StrokeKind::Middle);
}
}
match (mask, n.as_ref().map(|n| n.id)) {
(Some(m), Some(id)) => {
// Link toggle between the object and its mask.
let (lr, lresp) = ui.allocate_exact_size(vec2(14.0, 50.0), Sense::click());
icons::paint(
ui,
if m.linked { "link" } else { "link-2-off" },
egui::Rect::from_center_size(lr.center(), vec2(12.0, 12.0)),
t.icon,
);
if lresp.on_hover_text(if m.linked { tl!("Unlink the mask") } else { tl!("Link the mask") }).clicked() {
app.run("transparency.setOpacityMask", json!({"linked": !m.linked})).ok();
}
let (mr, _) = ui.allocate_exact_size(vec2(50.0, 50.0), Sense::hover());
let mresp = ui.interact(mr, egui::Id::unique(MASK_THUMB), Sense::click());
let bg = if m.clip != m.invert { [0, 0, 0, 255] } else { [255, 255, 255, 255] };
ui.painter().rect_filled(mr, 0.0, egui::Color32::from_rgb(bg[0], bg[1], bg[2]));
node_thumb(app, ui, "tr-mask", &m.art, mr.shrink(2.0), Some(bg), true);
// Viewing the mask alone (Alt-click) highlights its thumbnail.
let viewing = app.session.active().is_some_and(|d| d.shown_mask().is_some());
let border = match (viewing, editing.is_some()) {
(true, _) => Stroke::new(2.0, t.accent),
(false, true) => Stroke::new(mask_w, t.border),
(false, false) => Stroke::new(mask_w, t.input_border),
};
ui.painter().rect_stroke(mr, 0.0, border, StrokeKind::Inside);
if m.disabled {
let red = Stroke::new(2.0, egui::Color32::from_rgb(220, 40, 40));
ui.painter().line_segment([mr.left_top(), mr.right_bottom()], red);
ui.painter().line_segment([mr.right_top(), mr.left_bottom()], red);
}
let (shift, alt) = ui.input(|i| (i.modifiers.shift, i.modifiers.alt));
let tip = tl!("Click to edit the mask; Alt-click to view only the mask; Shift-click to disable or enable it");
if mresp.on_hover_text(tip).clicked() {
if shift {
app.run(if m.disabled { "transparency.enableOpacityMask" } else { "transparency.disableOpacityMask" }, json!({}))
.ok();
} else if alt {
app.run("transparency.viewOpacityMask", json!({"id": id.0})).ok();
} else if editing.is_none() {
app.run("transparency.editOpacityMask", json!({"id": id.0})).ok();
}
}
}
_ => {
let (m, _) = ui.allocate_exact_size(vec2(50.0, 50.0), Sense::hover());
ui.painter().rect_stroke(m, 0.0, Stroke::new(1.0, t.input_border), StrokeKind::Inside);
icons::paint(ui, "dc-mask-none", m.shrink(12.0), t.text_disabled);
}
}
}
ui.vertical(|ui| {
let label = if mask.is_some() { tl!("Release") } else { tl!("Make Mask") };
// Make Mask is off in isolation mode and pattern editing mode for one object, which it would take into mask editing.
let enabled = mask.is_some() || (has && editing.is_none() && crate::menus::enabled(app, "transparency.makeOpacityMask"));
let r = ui.add_enabled_ui(enabled, |ui| widgets::flat_button(ui, label, 96.0)).inner;
if r.on_disabled_hover_text(tl!("Select the art (and, on top of it, the mask object)")).clicked() {
let id = if mask.is_some() { "transparency.releaseOpacityMask" } else { "transparency.makeOpacityMask" };
app.run(id, json!({})).ok();
}
let (clip, invert) = mask.map(|m| (m.clip, m.invert)).unwrap_or((new_clip, new_invert));
if widgets::check(ui, tl!("Clip"), clip, mask.is_some()) {
app.run("transparency.setOpacityMask", json!({"clip": !clip})).ok();
}
if widgets::check(ui, tl!("Invert Mask"), invert, mask.is_some()) {
app.run("transparency.setOpacityMask", json!({"invert": !invert})).ok();
}
});
})
let (mut shown_blend, blend_before) = (blend.map_or(Mixed::Mixed, Mixed::Same), blend.map_or(Mixed::Mixed, Mixed::Same));
let entries = blend_entries();
let mut opacity = None;
Row::new().show(ui, |ui, _| {
Select::new(tl!("Blend Mode"), Bind::bound_mixed(&mut shown_blend), &entries).enabled(has).show(ui);
opacity = Some(
NumberField::new(tl!("Opacity"), Bind::given(op.map(|o| f64::from(o) * 100.0)))
.unit_kind(UnitKind::Percent)
.range(0.0..=100.0)
.popup_slider(0.0..=100.0)
.enabled(has)
.show(ui)
.edit,
);
});
if !pstate::<bool>(ui.ctx(), "tr-hide-options") {
widgets::divider(ui);
let has = has && object;
if widgets::check(ui, tl!("Isolate Blending"), isolate, has) {
app.run("transparency.set", json!({"isolate": !isolate})).ok();
}
// Neutral (and mixed) show a dash; a click moves on → neutral → off → on (mixed → on).
let shown = match info.knockout {
Some(Knockout::On) => Some(true),
Some(Knockout::Off) => Some(false),
_ => None,
};
if widgets::check3(ui, tl!("Knockout Group"), shown, has) {
let next = info.knockout.map_or(Knockout::On, Knockout::cycle);
app.run("transparency.set", json!({"knockout": next.label()})).ok();
}
if widgets::check(ui, tl!("Opacity & Mask Define Knockout Shape"), knockout_shape, has) {
app.run("transparency.set", json!({"knockoutShape": !knockout_shape})).ok();
}
if let (Mixed::Same(b), true) = (&shown_blend, shown_blend != blend_before) {
app.run("transparency.set", json!({"blend": b.label()})).ok();
}
if !has {
widgets::dim_label(ui, if selection_len(app) == 0 { tl!("No Selection") } else { "" });
if let Some(opacity) = opacity {
apply_edits(app, &opacity, EditPath::Preview, |app, v: &Option<f64>, phase| {
if let Some(percent) = v {
live_run(app, "Opacity", "transparency.set", json!({ "opacity": percent }), phase);
}
});
}
}
Divider::new().show(ui);
/// The Transparency panel's menu: showing thumbnails and options, and the opacity mask items (whole objects only).
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
let hide_thumbs: bool = pstate(ui.ctx(), "tr-hide-thumbs");
let hide_opts: bool = pstate(ui.ctx(), "tr-hide-options");
if menu_item(ui, if hide_thumbs { tl!("Show Thumbnails") } else { tl!("Hide Thumbnails") }, true, false) {
set_pstate(ui.ctx(), "tr-hide-thumbs", !hide_thumbs);
let mask = n.as_deref().and_then(|n| n.extras().mask.as_deref());
let (new_clip, new_invert) = app.session.new_mask_defaults();
let (mut clip, mut invert) = mask.map_or((new_clip, new_invert), |m| (m.clip, m.invert));
let (clip_before, invert_before) = (clip, invert);
// Make Mask is off in isolation mode and pattern editing mode for one object, which it would take into mask editing.
let can_make = has && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask");
let (hide_thumbs, hide_options) = (app.ui.transparency_panel.hide_thumbs, app.ui.transparency_panel.hide_options);
let mut cmds: Vec<(&'static str, Value)> = vec![];
let mut events = vec![];
Row::new().show(ui, |ui, _| {
if !hide_thumbs {
events = mask_row(app, ui, n.as_ref(), mask, editing, object);
}
Column::new().show(ui, |ui, _| {
let label = if mask.is_some() { tl!("Release") } else { tl!("Make Mask") };
let enabled = object && (mask.is_some() || can_make);
let button = Button::new(label).enabled(enabled).tooltip(tl!("Select the art (and, on top of it, the mask object)")).show(ui);
if button.clicked() {
cmds.push((if mask.is_some() { "transparency.releaseOpacityMask" } else { "transparency.makeOpacityMask" }, json!({})));
}
let with_mask = object && mask.is_some();
Checkbox::new(Bind::bound(&mut clip)).label(tl!("Clip")).enabled(with_mask).show(ui);
Checkbox::new(Bind::bound(&mut invert)).label(tl!("Invert Mask")).enabled(with_mask).show(ui);
});
});
if clip != clip_before {
cmds.push(("transparency.setOpacityMask", json!({"clip": clip})));
}
if menu_item(ui, if hide_opts { tl!("Show Options") } else { tl!("Hide Options") }, true, false) {
set_pstate(ui.ctx(), "tr-hide-options", !hide_opts);
if invert != invert_before {
cmds.push(("transparency.setOpacityMask", json!({"invert": invert})));
}
ui.separator();
// The masked object's mask, also while editing it (the selection then is the mask art).
let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some());
let (_, n) = state(app, ui.ctx());
let mask = n.as_ref().and_then(|n| n.extras().mask.as_deref());
// Not for a fill/stroke (the Appearance panel's active row): masks belong to whole objects.
let object = editing || app.session.appearance_item().is_none();
let can_make = n.is_some() && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask");
for (label, id, enabled) in mask_items(mask, can_make) {
if menu_item(ui, tl!(label), enabled && object, false) {
app.run(id, json!({})).ok();
for event in events {
match (event, mask, &n) {
(CollectionEvent::Item(_, RowEvent::ThumbClicked { target: ThumbTarget::First, .. }), _, _) if editing => {
cmds.push(("transparency.stopEditingOpacityMask", json!({})));
}
(CollectionEvent::Item(_, RowEvent::ThumbClicked { target: ThumbTarget::Extra(_), mods, .. }), Some(m), Some(n)) => {
cmds.extend(mask_click(m, n.id, mods, editing));
}
(CollectionEvent::Item(_, RowEvent::LinkToggled { .. }), Some(m), _) => {
cmds.push(("transparency.setOpacityMask", json!({"linked": !m.linked})));
}
_ => {}
}
}
ui.separator();
let (clip, invert) = app.session.new_mask_defaults();
if menu_item(ui, tl!("New Opacity Masks Are Clipping"), true, clip) {
app.run("transparency.toggleNewMasksClipping", json!({})).ok();
if !hide_options {
Divider::new().show(ui);
let enabled = has && object;
let (mut isolated, mut shape) = (isolate, knockout_shape);
// Neutral (and mixed) show a dash; a click moves on → neutral → off → on (mixed → on).
let mut group = match info.knockout {
Some(Knockout::On) => Mixed::Same(true),
Some(Knockout::Off) => Mixed::Same(false),
_ => Mixed::Mixed,
};
let group_before = group.clone();
Checkbox::new(Bind::bound(&mut isolated)).label(tl!("Isolate Blending")).enabled(enabled).show(ui);
Checkbox::new(Bind::bound_mixed(&mut group)).label(tl!("Knockout Group")).enabled(enabled).show(ui);
Checkbox::new(Bind::bound(&mut shape)).label(tl!("Opacity & Mask Define Knockout Shape")).enabled(enabled).show(ui);
if isolated != isolate {
cmds.push(("transparency.set", json!({"isolate": isolated})));
}
if group != group_before {
cmds.push(("transparency.set", json!({"knockout": info.knockout.map_or(Knockout::On, Knockout::cycle).label()})));
}
if shape != knockout_shape {
cmds.push(("transparency.set", json!({"knockoutShape": shape})));
}
}
if menu_item(ui, tl!("New Opacity Masks Are Inverted"), true, invert) {
app.run("transparency.toggleNewMasksInverted", json!({})).ok();
if !has && selection_len(app) == 0 {
Text::new(tl!("No Selection")).shade(Shade::Muted).show(ui);
}
ui.separator();
let page = app.session.active().map(|d| (d.doc.page_isolate, d.doc.page_knockout));
let (isolate, knockout) = page.unwrap_or_default();
if menu_item(ui, tl!("Page Isolated Blending"), page.is_some(), isolate) {
app.run("transparency.togglePageIsolatedBlending", json!({})).ok();
}
if menu_item(ui, tl!("Page Knockout Group"), page.is_some(), knockout) {
app.run("transparency.togglePageKnockoutGroup", json!({})).ok();
for (id, params) in cmds {
app.run(id, params).ok();
}
}
@@ -254,111 +350,123 @@ fn mask_items(mask: Option<&OpacityMask>, can_make: bool) -> [(&'static str, &'s
],
None => [
(tl!("Make Opacity Mask"), "transparency.makeOpacityMask", can_make),
(tl!("Release Opacity Mask"), "", false),
(tl!("Disable Opacity Mask"), "", false),
(tl!("Unlink Opacity Mask"), "", false),
(tl!("Release Opacity Mask"), "transparency.releaseOpacityMask", false),
(tl!("Disable Opacity Mask"), "transparency.disableOpacityMask", false),
(tl!("Unlink Opacity Mask"), "transparency.unlinkOpacityMask", false),
],
}
}
/// A rendered thumbnail of `n` (which may live outside the tree, like mask art). One texture per
/// slot, re-rendered only when the document revision, object or size changes, and not during a
/// drag (every pointer move is a new revision): the last one stays until it ends. With `own_mask`
/// false, `n` is drawn without its opacity mask.
fn node_thumb(app: &VectorcraftApp, ui: &Ui, slot: &str, n: &vectorcraft_doc::Node, r: egui::Rect, bg: Option<[u8; 4]>, own_mask: bool) -> bool {
use std::cell::RefCell;
thread_local! {
static RENDERER: RefCell<vectorcraft_render::Renderer> = RefCell::new(vectorcraft_render::Renderer::new());
/// The masked object's mask, also while editing it (the selection then is the mask art), whether the
/// object controls apply, and whether Make is possible.
fn menu_context(app: &VectorcraftApp) -> (Option<Arc<Node>>, bool, bool) {
let editing = app.session.active().is_some_and(|d| d.doc.mask_edit.is_some());
let n = first_node(app, &app.session.transparency_info());
let can_make = n.is_some() && !editing && crate::menus::enabled(app, "transparency.makeOpacityMask");
(n, object_controls(app, editing), can_make)
}
/// The panel menu's rows: the two view toggles, the opacity-mask commands, the new-mask defaults and the page options.
pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec<PanelRow> {
let command = |id: &str| PanelRow::Command(CommandRef::new(id));
let (n, _, can_make) = menu_context(app);
let items = mask_items(n.as_ref().and_then(|n| n.extras().mask.as_deref()), can_make);
let mut rows = vec![command(THUMBNAILS), command(OPTIONS), PanelRow::Separator];
rows.extend(items.iter().map(|(_, id, _)| command(id)));
rows.extend([
PanelRow::Separator,
command("transparency.toggleNewMasksClipping"),
command("transparency.toggleNewMasksInverted"),
PanelRow::Separator,
command("transparency.togglePageIsolatedBlending"),
command("transparency.togglePageKnockoutGroup"),
]);
rows
}
/// The titles, enabled and checked states of the menu's commands.
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
let panel = &app.ui.transparency_panel;
states.set(THUMBNAILS, CommandState::new().title(if panel.hide_thumbs { tl!("Show Thumbnails") } else { tl!("Hide Thumbnails") }));
states.set(OPTIONS, CommandState::new().title(if panel.hide_options { tl!("Show Options") } else { tl!("Hide Options") }));
let (n, object, can_make) = menu_context(app);
for (label, id, enabled) in mask_items(n.as_ref().and_then(|n| n.extras().mask.as_deref()), can_make) {
states.set(id, CommandState::new().title(label).enabled(enabled && object));
}
let Some(st) = app.session.active() else { return false };
let px = (r.width().min(r.height()) * ui.ctx().pixels_per_point()).round().max(8.0) as u32;
let (slot_id, key) = (egui::Id::unique(slot), egui::Id::unique((st.uid, n.id, bg, px)));
let busy = st.interaction.is_some() || app.session.tool_busy();
let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ui.ctx().data(|d| d.get_temp(slot_id));
let tex = match cached {
Some((k, rev, tex)) if k == key && (rev == st.revision || busy) => Some(tex),
_ => {
let bare = (!own_mask && n.extras().mask.is_some()).then(|| {
let mut bare = n.clone();
bare.extras_mut().mask = None;
bare
});
let n = bare.as_ref().unwrap_or(n);
RENDERER.with(|rr| rr.borrow_mut().render_node_thumbnail_with(&st.doc, n, px, bg, &super::layers::thumb_options())).map(|img| {
let color = crate::canvas::color_image(&img);
let tex = ui.ctx().load_texture(slot, color, egui::TextureOptions::LINEAR);
ui.ctx().data_mut(|d| d.insert_temp(slot_id, (key, st.revision, tex.clone())));
tex
})
}
};
let Some(tex) = tex else { return false };
let side = r.width().min(r.height());
let dst = egui::Rect::from_center_size(r.center(), vec2(side, side));
ui.painter().image(tex.id(), dst, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), egui::Color32::WHITE);
true
let (clip, invert) = app.session.new_mask_defaults();
states.set("transparency.toggleNewMasksClipping", CommandState::new().checked(clip));
states.set("transparency.toggleNewMasksInverted", CommandState::new().checked(invert));
let page = app.session.active().map(|d| (d.doc.page_isolate, d.doc.page_knockout));
let (isolate, knockout) = page.unwrap_or_default();
states.set("transparency.togglePageIsolatedBlending", CommandState::new().enabled(page.is_some()).checked(isolate));
states.set("transparency.togglePageKnockoutGroup", CommandState::new().enabled(page.is_some()).checked(knockout));
}
/// Runs the panel's own `ui.transparency.*` commands; `None` for any other id.
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, _params: &Value) -> Option<Result<Value, String>> {
let panel = &mut app.ui.transparency_panel;
match id {
THUMBNAILS => panel.hide_thumbs = !panel.hide_thumbs,
OPTIONS => panel.hide_options = !panel.hide_options,
_ => return None,
}
Some(Ok(json!({})))
}
#[cfg(test)]
mod tests {
use super::*;
// PLAN: assumed path of op.A15's `Panel` harness.
use crate::panels::tests_panel::Panel;
use vectorcraft_engine::Session;
/// Run the panel and its menu for one headless frame: the texts drawn.
fn frame(app: &mut VectorcraftApp) -> Vec<String> {
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
match s {
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
_ => {}
}
}
let ctx = egui::Context::default();
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
show(app, ui);
menu(app, ui);
});
out.textures_delta.clear();
let mut v = vec![];
out.shapes.iter().for_each(|c| texts(&c.shape, &mut v));
v
fn run_cmd(app: &mut VectorcraftApp, id: &str, p: serde_json::Value) -> serde_json::Value {
app.session.execute(id, &p).unwrap()
}
fn run(app: &mut VectorcraftApp, id: &str, p: serde_json::Value) -> serde_json::Value {
app.session.execute(id, &p).unwrap()
fn new_app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run_cmd(&mut app, "file.new", json!({"width": 100, "height": 100}));
app
}
#[test]
fn panel_in_mask_editing_mode_shows_and_edits_the_masked_object() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
run(&mut app, "transparency.set", json!({"opacity": 60}));
let mut app = new_app();
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].as_u64().unwrap();
run_cmd(&mut app, "transparency.set", json!({"opacity": 60}));
// One object: an empty mask, drawn in editing mode.
run(&mut app, "transparency.makeOpacityMask", json!({}));
run(&mut app, "shape.ellipse", json!({"x": 0, "y": 0, "width": 30, "height": 30}));
let texts = frame(&mut app);
assert!(texts.iter().any(|t| t == "60%"), "the masked object's opacity, not the mask art's: {texts:?}");
assert!(texts.iter().any(|t| t == "Release"));
let (info, n) = state(&app, &egui::Context::default());
run_cmd(&mut app, "transparency.makeOpacityMask", json!({}));
run_cmd(&mut app, "shape.ellipse", json!({"x": 0, "y": 0, "width": 30, "height": 30}));
let mut panel = Panel::new(app, show);
assert_eq!(panel.value("Opacity").as_deref(), Some("60%"), "the masked object's opacity, not the mask art's");
assert!(panel.shows("Release"));
let (info, n) = state(&mut panel.app());
assert_eq!((info.ids, n.as_ref().map(|n| n.id.0)), (vec![vectorcraft_doc::NodeId(a)], Some(a)));
// The menu is enabled for the masked object while editing (Make is not).
let items = mask_items(n.as_ref().and_then(|n| n.extras().mask.as_deref()), false);
assert_eq!(items.map(|(_, _, on)| on), [false, true, true, true]);
// The panel's controls run without ids and reach the masked object.
run(&mut app, "transparency.setOpacityMask", json!({"clip": false}));
run(&mut app, "transparency.unlinkOpacityMask", json!({}));
run(&mut app, "transparency.set", json!({"blend": "Multiply"}));
frame(&mut app);
for (id, p) in [
("transparency.setOpacityMask", json!({"clip": false})),
("transparency.unlinkOpacityMask", json!({})),
("transparency.set", json!({"blend": "Multiply"})),
] {
run_cmd(&mut panel.app(), id, p);
}
panel.frame();
let app = panel.app();
let st = app.session.active().unwrap();
let obj = st.doc.node(vectorcraft_doc::NodeId(a)).unwrap();
let m = obj.extras().mask.as_ref().unwrap();
assert!(!m.clip && !m.linked && obj.blend == BlendMode::Multiply);
assert!(!m.clip && !m.linked && obj.blend == vectorcraft_color::BlendMode::Multiply);
assert!(st.doc.mask_edit.is_some());
drop(app);
// Release leaves editing and puts the drawn mask art back.
run(&mut app, "transparency.releaseOpacityMask", json!({}));
assert!(frame(&mut app).iter().any(|t| t == "Make Mask"));
assert!(app.session.active().unwrap().doc.mask_edit.is_none());
run_cmd(&mut panel.app(), "transparency.releaseOpacityMask", json!({}));
panel.frame();
assert!(panel.shows("Make Mask"));
assert!(panel.app().session.active().unwrap().doc.mask_edit.is_none());
}
/// Picking other gradient mesh points (which gives the document no new revision) shows their
@@ -367,12 +475,11 @@ mod tests {
fn picking_mesh_points_shows_their_opacity() {
use vectorcraft_engine::ViewInfo;
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].clone();
run(&mut app, "object.mesh.create", json!({"rows": 2, "cols": 2}));
run(&mut app, "object.mesh.setPointColor", json!({"id": a, "index": 0, "opacity": 0.3}));
run(&mut app, "paint.setStroke", json!({"color": "#000000"}));
let mut app = new_app();
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50}))["id"].clone();
run_cmd(&mut app, "object.mesh.create", json!({"rows": 2, "cols": 2}));
run_cmd(&mut app, "object.mesh.setPointColor", json!({"id": a, "index": 0, "opacity": 0.3}));
run_cmd(&mut app, "paint.setStroke", json!({"color": "#000000"}));
let v = ViewInfo::default();
app.session.select_tool("mesh", v).unwrap();
let click = |app: &mut VectorcraftApp, x: f64, y: f64| {
@@ -381,14 +488,13 @@ mod tests {
}
};
let picked = |app: &VectorcraftApp| app.session.mesh_points_picked().map(|p| p.into_iter().flat_map(|(_, v)| v).collect::<Vec<_>>());
let ctx = egui::Context::default();
click(&mut app, 35.0, 10.0);
assert_ne!(picked(&app), Some(vec![0]), "the click picks the top middle point");
assert_eq!(picked(&app).map(|v| v.len()), Some(1));
assert_eq!(state(&app, &ctx).0.opacity, Some(100.0));
assert_eq!(state(&mut app).0.opacity, Some(100.0));
click(&mut app, 10.0, 10.0);
assert_eq!(picked(&app), Some(vec![0]), "the click picks the top-left point");
assert_eq!(state(&app, &ctx).0.opacity, Some(30.0), "the newly picked point's opacity");
assert_eq!(state(&mut app).0.opacity, Some(30.0), "the newly picked point's opacity");
// An active Appearance row takes the opacity, so the values are the object's again.
let rows = app
.session
@@ -399,114 +505,89 @@ mod tests {
.first()
.map(|id| app.session.active().unwrap().doc.node(*id).unwrap().appearance.items.len());
assert!(rows.is_some_and(|n| n > 0), "the mesh has its stroke row");
run(&mut app, "appearance.setActiveItem", json!({"index": 0}));
run_cmd(&mut app, "appearance.setActiveItem", json!({"index": 0}));
assert_eq!(picked(&app), None);
assert_eq!(app.session.transparency_info().opacity, Some(100.0), "the object's opacity, not the point's");
assert_eq!(run(&mut app, "transparency.info", json!({}))["opacity"], json!(100.0));
assert_eq!(run_cmd(&mut app, "transparency.info", json!({}))["opacity"], json!(100.0));
}
#[test]
fn mixed_values_show_blank() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
run(&mut app, "transparency.set", json!({"opacity": 50, "blend": "Screen"}));
let b = run(&mut app, "shape.rectangle", json!({"x": 60, "y": 0, "width": 30, "height": 30}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
let texts = frame(&mut app);
assert!(!texts.iter().any(|t| t.ends_with('%') || t == "Screen" || t == "Normal"), "{texts:?}");
run(&mut app, "select.set", json!({"ids": [a]}));
let texts = frame(&mut app);
assert!(texts.iter().any(|t| t == "50%") && texts.iter().any(|t| t == "Screen"), "{texts:?}");
let mut app = new_app();
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
run_cmd(&mut app, "transparency.set", json!({"opacity": 50, "blend": "Screen"}));
let b = run_cmd(&mut app, "shape.rectangle", json!({"x": 60, "y": 0, "width": 30, "height": 30}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a, b]}));
let mut panel = Panel::new(app, show);
let blank = |v: Option<String>| v.is_none_or(|v| v.is_empty());
assert!(blank(panel.value("Opacity")) && blank(panel.value("Blend Mode")));
run_cmd(&mut panel.app(), "select.set", json!({"ids": [a]}));
panel.frame();
assert_eq!((panel.value("Opacity").as_deref(), panel.value("Blend Mode").as_deref()), (Some("50%"), Some("Screen")));
// Nothing selected: the defaults for new art, disabled.
run(&mut app, "select.none", json!({}));
let texts = frame(&mut app);
assert!(texts.iter().any(|t| t == "100%") && texts.iter().any(|t| t == "No Selection"), "{texts:?}");
}
#[test]
fn panel_draws_with_and_without_a_mask() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
let r = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
r(&mut app, "file.new", json!({"width": 100, "height": 100}));
frame(&mut app);
let a = r(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let b = r(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
r(&mut app, "select.set", json!({"ids": [a, b]}));
frame(&mut app);
r(&mut app, "transparency.makeOpacityMask", json!({}));
frame(&mut app);
r(&mut app, "transparency.disableOpacityMask", json!({}));
r(&mut app, "transparency.unlinkOpacityMask", json!({}));
frame(&mut app);
assert_eq!(app.session.execute("transparency.opacityMaskInfo", &json!({})).unwrap()[0]["disabled"], true);
run_cmd(&mut panel.app(), "select.none", json!({}));
panel.frame();
assert_eq!(panel.value("Opacity").as_deref(), Some("100%"));
assert!(panel.shows("No Selection") && !panel.enabled("Opacity"));
}
/// Each knockout state and the state a click on the box moves it to.
#[test]
fn knockout_states_and_page_group_items() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
for k in ["on", "off", "neutral"] {
run(&mut app, "transparency.set", json!({"knockout": k, "knockoutShape": k == "on"}));
let texts = frame(&mut app);
assert!(texts.iter().any(|t| t == "Knockout Group") && texts.iter().any(|t| t == "Opacity & Mask Define Knockout Shape"));
for (start, next) in [("on", "neutral"), ("neutral", "off"), ("off", "on")] {
let mut app = new_app();
run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
run_cmd(&mut app, "transparency.set", json!({"knockout": start}));
let mut panel = Panel::new(app, show);
assert!(panel.shows("Opacity & Mask Define Knockout Shape"));
panel.click("Knockout Group");
let after = panel.app().session.transparency_info().knockout.map(|k| k.label().to_lowercase());
assert_eq!(after.as_deref(), Some(next), "from {start}");
}
assert!(frame(&mut app).iter().any(|t| t.ends_with(" Page Knockout Group") && !t.starts_with('✓')));
run(&mut app, "transparency.togglePageKnockoutGroup", json!({}));
run(&mut app, "transparency.togglePageIsolatedBlending", json!({}));
let texts = frame(&mut app);
assert!(texts.iter().any(|t| t == "✓ Page Knockout Group") && texts.iter().any(|t| t == "✓ Page Isolated Blending"), "{texts:?}");
}
/// The pixels of the thumbnail [`node_thumb`] draws of `n`, in a context of its own (so no
/// earlier texture is reused).
fn thumb_pixels(app: &VectorcraftApp, n: &Node, own_mask: bool) -> Vec<egui::Color32> {
let ctx = egui::Context::default();
let r = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(44.0, 44.0));
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
assert!(node_thumb(app, ui, "tr-test", n, r, None, own_mask), "the thumbnail draws");
});
let cached: Option<(egui::Id, u64, egui::TextureHandle)> = ctx.data(|d| d.get_temp(egui::Id::unique("tr-test")));
let id = cached.expect("the thumbnail's texture").2.id();
let pixels = out.textures_delta.set.iter().find(|e| e.0.eq(&id)).and_then(|e| e.1.last()).map(|d| {
let egui::ImageData::Color(img) = &d.image;
img.pixels.clone()
});
out.textures_delta.clear();
pixels.expect("the thumbnail uploads")
let mut app = new_app();
run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}));
let page = |app: &VectorcraftApp| {
let mut states = CommandStates::new();
menu_states(app, &mut states);
["transparency.togglePageKnockoutGroup", "transparency.togglePageIsolatedBlending"]
// PLAN: assumed `CommandState::is_checked() -> bool`.
.map(|id| states.get(&CommandRef::new(id)).is_some_and(CommandState::is_checked))
};
assert_eq!(page(&app), [false, false]);
run_cmd(&mut app, "transparency.togglePageKnockoutGroup", json!({}));
run_cmd(&mut app, "transparency.togglePageIsolatedBlending", json!({}));
assert_eq!(page(&app), [true, true]);
}
/// The panel's state holds the target as the document holds it, a new one after an edit and
/// after Undo; the object thumbnail of a masked object draws as the object without its mask.
#[test]
fn state_holds_the_documents_node_and_the_object_thumbnail_leaves_out_the_mask() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
run(&mut app, "file.new", json!({"width": 100, "height": 100}));
let a = run(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let b = run(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run(&mut app, "select.set", json!({"ids": [a, b]}));
run(&mut app, "transparency.makeOpacityMask", json!({}));
let mut app = new_app();
let a = run_cmd(&mut app, "shape.rectangle", json!({"x": 0, "y": 0, "width": 50, "height": 50}))["id"].clone();
let b = run_cmd(&mut app, "shape.ellipse", json!({"x": 10, "y": 10, "width": 20, "height": 20}))["id"].clone();
run_cmd(&mut app, "select.set", json!({"ids": [a, b]}));
run_cmd(&mut app, "transparency.makeOpacityMask", json!({}));
let held = |app: &VectorcraftApp, id: NodeId| super::super::layers::node_arc(&app.session.active().unwrap().doc, id).expect("held");
let ctx = egui::Context::default();
let n = state(&app, &ctx).1.expect("the masked object");
let n = state(&mut app).1.expect("the masked object");
assert!(n.extras().mask.is_some(), "the object has its mask");
assert!(Arc::ptr_eq(&n, &held(&app, n.id)), "the node the document holds");
assert!(Arc::ptr_eq(&state(&app, &ctx).1.expect("cached"), &n), "the cached state gives the same node");
assert!(Arc::ptr_eq(&state(&mut app).1.expect("cached"), &n), "the cached state gives the same node");
// The object thumbnail: as a copy with the mask removed draws, not as the masked object.
let mut bare = (*n).clone();
bare.extras_mut().mask = None;
let without = thumb_pixels(&app, &n, false);
assert!(without == thumb_pixels(&app, &bare, true), "the object without its mask");
assert!(without != thumb_pixels(&app, &n, true), "the mask changes the drawing");
let doc = app.session.active().unwrap().doc.clone();
let without = thumb_image(&doc, &n, false, 44, None).expect("the object draws");
assert!(without == thumb_image(&doc, &bare, false, 44, None).expect("the bare object draws"), "the object without its mask");
assert!(without != thumb_image(&doc, &n, true, 44, None).expect("the mask draws"), "the mask changes the drawing");
// An edit and its Undo: the state follows the document.
run(&mut app, "transparency.set", json!({"opacity": 40}));
let (info, edited) = state(&app, &ctx);
run_cmd(&mut app, "transparency.set", json!({"opacity": 40}));
let (info, edited) = state(&mut app);
let edited = edited.expect("the edited object");
assert_eq!((info.opacity, edited.opacity), (Some(40.0), 0.4));
assert!(Arc::ptr_eq(&edited, &held(&app, n.id)) && !Arc::ptr_eq(&edited, &n), "the edited node");
run(&mut app, "edit.undo", json!({}));
let (info, undone) = state(&app, &ctx);
run_cmd(&mut app, "edit.undo", json!({}));
let (info, undone) = state(&mut app);
let undone = undone.expect("the object after Undo");
assert_eq!((info.opacity, undone.opacity), (Some(100.0), 1.0));
assert!(Arc::ptr_eq(&undone, &held(&app, n.id)), "the node Undo put back");