mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
document-panels-w8: net change of 2 commits
- document-panels-w8: written from its sheet - document-panels-w8: repair 1
This commit is contained in:
@@ -447,7 +447,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?;
|
||||
st.layer_rows = vec![row];
|
||||
st.locate_reveal = Some(row);
|
||||
st.layers_reveal = Some(crate::LayersReveal::Row(row));
|
||||
st.revision += 1;
|
||||
let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect();
|
||||
Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) })
|
||||
|
||||
@@ -25,10 +25,11 @@ pub struct DocState {
|
||||
/// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`,
|
||||
/// `layer.highlight`).
|
||||
pub layer_rows: Vec<NodeId>,
|
||||
/// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the
|
||||
/// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also
|
||||
/// when the row was already highlighted. Panel state: not saved, not undoable.
|
||||
pub locate_reveal: Option<NodeId>,
|
||||
/// What the Layers panel reveals at its next pass, until the panel takes it: the panel opens
|
||||
/// the layers around the row and scrolls to it, also when the row was already highlighted.
|
||||
/// Set by `layer.locate` and, for what a top-level command, an interaction's commit or a
|
||||
/// selection changed, by [`DocState::request_reveal`]. Panel state: not saved, not undoable.
|
||||
pub layers_reveal: Option<LayersReveal>,
|
||||
/// The variable highlighted in the Variables panel: what its Delete, Options… and Select
|
||||
/// Bound Object act on. Panel state, not art selection: not saved, not undoable
|
||||
/// (`variable.highlight`). A name, so renaming a variable moves the highlight with it.
|
||||
@@ -179,6 +180,30 @@ thread_local! {
|
||||
|
||||
static NEXT_DOC_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
||||
|
||||
/// What the Layers panel is asked to reveal ([`DocState::layers_reveal`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayersReveal {
|
||||
/// Open the layers around this row and scroll to it: it was highlighted, located or isolated.
|
||||
Row(NodeId),
|
||||
/// The current layer changed with no row highlighted: reveal that layer.
|
||||
Current(NodeId),
|
||||
/// The last selected object changed: reveal its row when Panel Options › Locate Selected
|
||||
/// Objects is on.
|
||||
Selected(NodeId),
|
||||
}
|
||||
|
||||
/// What decides a [`LayersReveal`], as of one moment: the isolation, the highlighted rows, the
|
||||
/// current layer and the last selected object of one document, with the request pending then.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(crate) struct LayersView {
|
||||
uid: u64,
|
||||
isolation: Option<NodeId>,
|
||||
rows: Vec<NodeId>,
|
||||
active_layer: Option<NodeId>,
|
||||
last_selected: Option<NodeId>,
|
||||
reveal: Option<LayersReveal>,
|
||||
}
|
||||
|
||||
/// The rows open in the Layers panel: the layers, sublayers and groups that show what they hold.
|
||||
/// A document opens with the ones it was saved with ([`Document::layers_open`]), else with only
|
||||
/// its top-level layers open (a `.ai` another app wrote opens with none open).
|
||||
@@ -326,7 +351,7 @@ impl DocState {
|
||||
revision: 1,
|
||||
active_layer,
|
||||
layer_rows: vec![],
|
||||
locate_reveal: None,
|
||||
layers_reveal: None,
|
||||
variables_highlight: None,
|
||||
variables_sort: Default::default(),
|
||||
isolation: None,
|
||||
@@ -657,6 +682,68 @@ impl DocState {
|
||||
pub fn highlighted_rows(&self) -> Vec<NodeId> {
|
||||
self.layer_rows.iter().copied().filter(|id| self.doc.node(*id).is_some()).collect()
|
||||
}
|
||||
/// What decides the Layers panel's reveal request now.
|
||||
pub(crate) fn layers_view(&self) -> LayersView {
|
||||
LayersView {
|
||||
uid: self.uid,
|
||||
isolation: self.isolation,
|
||||
rows: self.layer_rows.clone(),
|
||||
active_layer: self.active_layer,
|
||||
last_selected: self.selection.objects.last().copied(),
|
||||
reveal: self.layers_reveal,
|
||||
}
|
||||
}
|
||||
/// [`DocState::layers_view`] as it was when interaction `it` began: what a commit of the
|
||||
/// interaction changed is compared with that, since the previews changed the state meanwhile.
|
||||
pub(crate) fn layers_view_before(&self, it: &Interaction) -> LayersView {
|
||||
LayersView {
|
||||
uid: self.uid,
|
||||
isolation: it.isolation,
|
||||
rows: it.layer_rows.clone(),
|
||||
active_layer: it.active_layer,
|
||||
last_selected: it.selection.objects.last().copied(),
|
||||
reveal: self.layers_reveal,
|
||||
}
|
||||
}
|
||||
/// Ask the Layers panel to reveal what changed since `before`, in this order: isolation entered
|
||||
/// or left, the highlighted rows, the current layer, the last selected object. A request made
|
||||
/// meanwhile (`layer.locate`) stands, and nothing is asked while an interaction is open, so a
|
||||
/// drag's previews reveal nothing and its commit does.
|
||||
pub(crate) fn request_reveal(&mut self, before: &LayersView) {
|
||||
if self.uid != before.uid || self.layers_reveal != before.reveal || self.interaction.is_some() {
|
||||
return;
|
||||
}
|
||||
let now = self.layers_view();
|
||||
let mut request = None;
|
||||
if now.isolation != before.isolation {
|
||||
request = self.reveal_isolation(now.isolation, before.isolation);
|
||||
}
|
||||
if request.is_none() && now.rows != before.rows {
|
||||
request = self.highlighted_rows().first().copied().map(LayersReveal::Row);
|
||||
}
|
||||
if request.is_none() && now.active_layer != before.active_layer {
|
||||
request = self.current_layer().map(LayersReveal::Current);
|
||||
}
|
||||
if request.is_none() && now.last_selected != before.last_selected {
|
||||
request = now.last_selected.map(LayersReveal::Selected);
|
||||
}
|
||||
if request.is_some() {
|
||||
self.layers_reveal = request;
|
||||
}
|
||||
}
|
||||
/// The request for isolation moving from `before` to `now`: entering opens the isolated row,
|
||||
/// leaving opens the layers around the row that was isolated.
|
||||
fn reveal_isolation(&mut self, now: Option<NodeId>, before: Option<NodeId>) -> Option<LayersReveal> {
|
||||
if let Some(root) = now.filter(|r| self.doc.node(*r).is_some()) {
|
||||
self.layers_open.set(root, true);
|
||||
return Some(LayersReveal::Row(root));
|
||||
}
|
||||
let former = before?;
|
||||
for around in self.doc.ancestry(former)?.into_iter().filter(|a| *a != former) {
|
||||
self.layers_open.set(around, true);
|
||||
}
|
||||
Some(LayersReveal::Row(former))
|
||||
}
|
||||
/// The object whose opacity mask View Opacity Mask shows ([`DocState::mask_view`]): only while
|
||||
/// its mask is being edited, so leaving editing by any route (undo, deleting the object) ends it.
|
||||
pub fn shown_mask(&self) -> Option<NodeId> {
|
||||
|
||||
@@ -432,7 +432,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, OpenRows, RecalledSelection};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
|
||||
@@ -7,6 +7,10 @@ impl Session {
|
||||
/// Run `f` on a mutable copy of the active document. Outside an interaction this records one
|
||||
/// undo step labelled `label`; inside one it just mutates (the interaction commits later).
|
||||
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
|
||||
self.revealing(|s| s.edit_unwatched(label, f))
|
||||
}
|
||||
|
||||
fn edit_unwatched<T>(&mut self, label: &str, f: impl FnOnce(&mut Document, &mut Selection) -> Result<T>) -> Result<T> {
|
||||
if self.script_running() {
|
||||
return Err(EngineError::Busy);
|
||||
}
|
||||
@@ -197,6 +201,10 @@ impl Session {
|
||||
|
||||
/// Change only the selection (not an undo step).
|
||||
pub fn select(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
self.revealing(|s| s.select_unwatched(f))
|
||||
}
|
||||
|
||||
fn select_unwatched(&mut self, f: impl FnOnce(&Document, &mut Selection)) -> Result<()> {
|
||||
self.active_appearance_item = None;
|
||||
let menu = self.menu.clone();
|
||||
let st = self.doc_mut()?;
|
||||
@@ -390,6 +398,17 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn commit_interaction(&mut self) -> Result<()> {
|
||||
// The interaction is taken below, so its starting state is read first: the commit is what
|
||||
// the previews that came before it changed.
|
||||
let before = (self.depth == 0).then(|| self.active().and_then(|st| st.interaction.as_ref().map(|it| st.layers_view_before(it)))).flatten();
|
||||
let r = self.commit_interaction_unwatched();
|
||||
if let Some(before) = before {
|
||||
self.reveal_since(&before);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn commit_interaction_unwatched(&mut self) -> Result<()> {
|
||||
self.clear_deferred_overlay_cache();
|
||||
self.decoded_images.empty();
|
||||
if let Some(paint) = self.active().and_then(|st| st.interaction.as_ref()).and_then(|it| it.preview_paint.clone()) {
|
||||
|
||||
@@ -59,6 +59,30 @@ impl Session {
|
||||
|
||||
/// Execute a command by id. This is THE entry point for every frontend.
|
||||
pub fn execute(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
self.revealing(|s| s.execute_unwatched(id, params))
|
||||
}
|
||||
|
||||
/// Run `f`, a top-level entry that changes the active document's rows, current layer or
|
||||
/// selection, then ask the Layers panel to reveal what it changed ([`DocState::request_reveal`]).
|
||||
/// Nothing is asked inside a command, while an interaction is open or while a tool is busy: the
|
||||
/// entry that ends them asks.
|
||||
pub(super) fn revealing<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
|
||||
let before = (self.depth == 0 && !self.tool_busy()).then(|| self.active().map(crate::DocState::layers_view)).flatten();
|
||||
let r = f(self);
|
||||
if let Some(before) = before {
|
||||
self.reveal_since(&before);
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
/// Ask the Layers panel of the active document to reveal what changed since `before`.
|
||||
pub(super) fn reveal_since(&mut self, before: &crate::doc_state::LayersView) {
|
||||
if let Some(st) = self.active_mut() {
|
||||
st.request_reveal(before);
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_unwatched(&mut self, id: &str, params: &Value) -> Result<Value> {
|
||||
let spec = find_command(id).ok_or_else(|| cmd::params::unknown_command(id))?;
|
||||
// A clipboard import is a query that replaces the clipboard, which the end of a run sets too.
|
||||
if self.depth == 0 && self.script_key.is_some() && (waits_for_tool_edit(id) || id.starts_with("clipboard.import")) {
|
||||
|
||||
@@ -1326,11 +1326,11 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
|
||||
let r = run(&mut s, "layer.locate", json!({"layersOnly": true}));
|
||||
assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer");
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]);
|
||||
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row");
|
||||
s.doc_mut().unwrap().locate_reveal = None;
|
||||
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "the Layers panel reveals the located row");
|
||||
s.doc_mut().unwrap().layers_reveal = None;
|
||||
let undo = s.doc().unwrap().history.undo.len();
|
||||
run(&mut s, "layer.locate", json!({"layersOnly": true}));
|
||||
assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted");
|
||||
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(sub)), "again for a row already highlighted");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step");
|
||||
assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer");
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]);
|
||||
@@ -1342,12 +1342,53 @@ fn locate_layer_highlights_the_layer_holding_the_object() {
|
||||
for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] {
|
||||
assert!(s.execute("layer.locate", &p).is_err(), "{p}");
|
||||
assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}");
|
||||
assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}");
|
||||
assert_eq!(s.doc().unwrap().layers_reveal, Some(crate::LayersReveal::Row(g)), "{p}");
|
||||
}
|
||||
run(&mut s, "select.none", json!({}));
|
||||
assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected");
|
||||
}
|
||||
|
||||
/// The session asks the Layers panel to reveal what a top-level command changed: isolation, then
|
||||
/// the highlighted rows, the current layer and the last selected object. An open interaction asks
|
||||
/// for nothing, and a failed command changes nothing.
|
||||
#[test]
|
||||
fn the_layers_panel_is_asked_to_reveal_what_a_command_changed() {
|
||||
use crate::LayersReveal::{Current, Row, Selected};
|
||||
let mut s = session();
|
||||
let (layer, sub, _, g, b, c) = tree(&mut s);
|
||||
let take = |s: &mut Session| s.doc_mut().unwrap().layers_reveal.take();
|
||||
take(&mut s);
|
||||
run(&mut s, "layer.highlight", highlight_params([c], "set"));
|
||||
take(&mut s);
|
||||
run(&mut s, "layer.highlight", highlight_params([g], "set"));
|
||||
assert_eq!(take(&mut s), Some(Row(g)), "a highlighted row");
|
||||
// The current layer changes with the selection of art in another layer.
|
||||
s.doc_mut().unwrap().active_layer = Some(sub);
|
||||
run(&mut s, "select.set", json!({"ids": [c.0]}));
|
||||
assert_eq!(take(&mut s), Some(Current(layer)), "a new current layer wins over the selected object");
|
||||
// Within the current layer only the last selected object changes.
|
||||
s.doc_mut().unwrap().active_layer = Some(sub);
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
take(&mut s);
|
||||
run(&mut s, "select.set", json!({"ids": [g.0]}));
|
||||
assert_eq!(take(&mut s), Some(Selected(g)), "the last selected object");
|
||||
// Isolation entered and left reveals the isolated row.
|
||||
run(&mut s, "object.isolate", json!({"id": g.0}));
|
||||
assert_eq!(take(&mut s), Some(Row(g)), "isolation entered");
|
||||
run(&mut s, "object.exitIsolation", json!({}));
|
||||
assert_eq!(take(&mut s), Some(Row(g)), "isolation left");
|
||||
// A failed command asks for nothing.
|
||||
assert!(s.execute("layer.locate", &json!({"id": 999_999})).is_err());
|
||||
assert_eq!(take(&mut s), None);
|
||||
// A command inside an open interaction asks for nothing either.
|
||||
run(&mut s, "select.set", json!({"ids": [g.0]}));
|
||||
take(&mut s);
|
||||
s.begin_interaction("Drag").unwrap();
|
||||
run(&mut s, "select.set", json!({"ids": [b.0]}));
|
||||
assert_eq!(take(&mut s), None, "a preview");
|
||||
s.cancel_interaction().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_clipping_mask_button_acts_on_the_highlighted_group() {
|
||||
let mut s = session();
|
||||
|
||||
@@ -1,150 +1,78 @@
|
||||
use super::model::{ObjectKind, RowState, names, parse_names, toggled};
|
||||
use super::{
|
||||
Arc, Document, HashSet, LayersDrag, Node, NodeId, NodeKind, PanelDrag, Sense, Stroke, Ui, Value, VectorcraftApp, View, json, last_selected,
|
||||
see_selection, vec2, widgets,
|
||||
};
|
||||
use craft::behavior::IconId;
|
||||
use craft_keymap::Mods;
|
||||
use craft::layers::ui::{LayerRowKey, MenuTarget}; // PLAN: assumed path of craft-layers' panel types
|
||||
use craft_ui::contract::{Entry, ListDrag};
|
||||
use craft_ui::menu::{MenuRow, PanelRow};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::commands::{CommandRef, CommandState, CommandStates};
|
||||
use craft_ui::sections::{FooterAction, FooterBar};
|
||||
use vectorcraft_engine::LayersReveal;
|
||||
|
||||
/// The Filter button, lit while a filter is on, and its popup: Clear All, the object kinds under
|
||||
/// By Object and the row states under By Layer, each ticked or not. A tick, or Clear All, runs
|
||||
/// `ui.layersFilter`; the popup stays open until a click outside it or Escape.
|
||||
pub(super) fn filter_button(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let f = app.ui.layers_filter.clone();
|
||||
let button = widgets::icon_button(ui, "dc-filter", tl!("Filter"), f.is_on(), 24.0);
|
||||
let mut set = None;
|
||||
egui::Popup::menu(&button).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
widgets::subheader(ui, tl!("Filter"));
|
||||
ui.add_space(12.0);
|
||||
if ui.add_enabled(f.is_on(), egui::Button::new(egui::RichText::new(tl!("Clear All")).size(12.5)).frame(false)).clicked() {
|
||||
set = Some(json!({"objects": [], "layers": []}));
|
||||
}
|
||||
});
|
||||
widgets::subheader(ui, tl!("By Object"));
|
||||
for (k, _) in ObjectKind::ALL {
|
||||
if widgets::check(ui, k.label(), f.objects.contains(&k), true) {
|
||||
set = Some(json!({"objects": toggled(&ObjectKind::ALL, &f.objects, k)}));
|
||||
}
|
||||
}
|
||||
widgets::subheader(ui, tl!("By Layer"));
|
||||
for (s, _) in RowState::ALL {
|
||||
if widgets::check(ui, s.label(), f.layers.contains(&s), true) {
|
||||
set = Some(json!({"layers": toggled(&RowState::ALL, &f.layers, s)}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(p) = set {
|
||||
app.run("ui.layersFilter", p).ok();
|
||||
// PLAN: assumed document-panels-w7's `model` exports `DocLayers` (accessors used here: `doc() -> &Arc<Document>`,
|
||||
// `state() -> &DocState`, `root() -> Option<NodeId>`, `layers_only() -> bool`, `guides() -> &[usize]`,
|
||||
// `targets(&MenuTarget<RowId>) -> Vec<u64>`: the ids a menu command acts on) and `RowId::{Node(NodeId), Guide(usize), Spine(NodeId)}`.
|
||||
use super::model::{DocLayers, FilterObject, FilterState, RowId, names, painted_name, parse_names};
|
||||
use super::{Arc, HashSet, Node, NodeId, NodeKind, Ui, Value, VectorcraftApp, json};
|
||||
use crate::panel_drag::PanelDrag;
|
||||
|
||||
/// The command of a Save Selection row that recalls one of the document's saved selections.
|
||||
const RECALL: &str = "ui.layers.recall";
|
||||
|
||||
// The footer's actions, in the order given to the bar.
|
||||
const DELETE: usize = 0;
|
||||
const NEW_LAYER: usize = 1;
|
||||
const NEW_SUBLAYER: usize = 2;
|
||||
const MASK: usize = 3;
|
||||
const LOCATE: usize = 4;
|
||||
|
||||
/// One row of the panel menu with the state its command has.
|
||||
enum Item {
|
||||
Separator,
|
||||
Command(CommandRef, CommandState),
|
||||
Submenu(String, Vec<Item>),
|
||||
}
|
||||
|
||||
impl Item {
|
||||
/// The row the dock's panel menu shows for it.
|
||||
fn row(&self) -> PanelRow {
|
||||
match self {
|
||||
Item::Separator => PanelRow::Separator,
|
||||
Item::Command(command, _) => PanelRow::Command(command.clone()),
|
||||
Item::Submenu(label, items) => PanelRow::Submenu(label.clone().into(), items.iter().map(Item::row).collect()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Give each command of it and of its submenus its state.
|
||||
fn set_states(&self, states: &mut CommandStates) {
|
||||
match self {
|
||||
Item::Separator => {}
|
||||
Item::Command(command, state) => states.set(command.clone(), state.clone()),
|
||||
Item::Submenu(_, items) => items.iter().for_each(|item| item.set_states(states)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bottom bar: the layer count and the panel's buttons.
|
||||
pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc: &Document, actions: &mut Vec<(String, Value)>) {
|
||||
let t = &view.t;
|
||||
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), 30.0), Sense::hover());
|
||||
ui.painter().line_segment([bar.left_top(), bar.right_top()], Stroke::new(1.0, t.divider));
|
||||
let n = doc.layers.len();
|
||||
ui.painter().text(
|
||||
bar.left_center() + vec2(4.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
crate::i18n::tn(n as u64, "{n} Layer", "{n} Layers"),
|
||||
egui::FontId::proportional(11.5),
|
||||
t.text_dim,
|
||||
);
|
||||
let m = ui.input(|i| i.modifiers);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(bar).layout(egui::Layout::right_to_left(egui::Align::Center)));
|
||||
let trash = widgets::icon_button(&mut child, "trash-2", tl!("Delete Selection"), false, 24.0);
|
||||
// A target circle dropped on the trash reduces that appearance to one fill and one stroke
|
||||
// (dragged rows: below). Peek at the payload's type before taking it: egui's take drops a
|
||||
// payload of another type.
|
||||
if trash.dnd_hover_payload::<PanelDrag>().is_some()
|
||||
&& let Some(d) = trash.dnd_release_payload::<PanelDrag>()
|
||||
&& let PanelDrag::Appearance(id) = *d
|
||||
{
|
||||
actions.push(("appearance.reduceToBasic".into(), json!({"ids": [id.0]})));
|
||||
} else if trash.clicked() {
|
||||
// With no row highlighted, the selected art and ruler guides go.
|
||||
if view.rows.is_empty() && app.session.active().is_some_and(|d| d.selection.has_objects_or_guides()) {
|
||||
actions.push(("edit.clear".into(), json!({})));
|
||||
} else {
|
||||
actions.push(("ui.layerDelete".into(), json!({})));
|
||||
}
|
||||
}
|
||||
// In isolation mode New Layer and New Sublayer are off while the layer they make would be
|
||||
// outside the isolated art, where the panel does not list it.
|
||||
let unlisted = |sublayer: bool, top: bool| app.session.active().is_some_and(|st| new_layer_unlisted(st, sublayer, top));
|
||||
let new_layer_ok = !unlisted(false, m.command && !m.alt);
|
||||
let new_sublayer_ok = !unlisted(true, false);
|
||||
// Create New Layer: Alt asks for its options first, Ctrl/Cmd puts it on top of every layer,
|
||||
// and Ctrl/Cmd+Alt puts it directly below the current layer.
|
||||
let new_layer = widgets::icon_button_enabled(&mut child, "file-plus", tl!("Create New Layer"), false, new_layer_ok, 24.0);
|
||||
if new_layer.clicked() {
|
||||
if m.alt && m.command {
|
||||
actions.push(("layer.new".into(), json!({"below": true})));
|
||||
} else if m.alt {
|
||||
actions.push(("ui.newLayer".into(), json!({})));
|
||||
} else {
|
||||
actions.push(("layer.new".into(), json!({"top": m.command})));
|
||||
}
|
||||
}
|
||||
// Rows dropped on the trash are deleted, on New Layer duplicated. Both are
|
||||
// outlined while rows (or, on the trash, a target circle) hang over them. Guide rows dropped on
|
||||
// the trash delete their guides (`guide.remove`); New Layer does not take them.
|
||||
for (button, cmd) in [(&trash, "ui.layerDelete"), (&new_layer, "layer.duplicate")] {
|
||||
let deletes = cmd == "ui.layerDelete";
|
||||
if let Some(d) = button.dnd_release_payload::<LayersDrag>() {
|
||||
match &*d {
|
||||
// A copy of the isolated node would go beside it, outside the isolated art.
|
||||
LayersDrag::Rows(ids) if !deletes && view.root.is_some_and(|r| ids.contains(&r)) => {}
|
||||
LayersDrag::Rows(ids) => actions.push((cmd.into(), json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()}))),
|
||||
LayersDrag::Guides(guides) if deletes => actions.push(("guide.remove".into(), json!({"indexes": guides}))),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let over = button.dnd_hover_payload::<LayersDrag>().is_some_and(|d| match &*d {
|
||||
LayersDrag::Rows(ids) => deletes || !view.root.is_some_and(|r| ids.contains(&r)),
|
||||
LayersDrag::Guides(_) => deletes,
|
||||
LayersDrag::Art => false,
|
||||
}) || (deletes && button.dnd_hover_payload::<PanelDrag>().is_some_and(|d| matches!(*d, PanelDrag::Appearance(_))));
|
||||
if over {
|
||||
widgets::drop_target_outline(&child, button.rect);
|
||||
}
|
||||
}
|
||||
// Create New Sublayer: Alt asks for its options first, and Ctrl/Cmd+Alt puts it under the
|
||||
// layer's contents.
|
||||
if widgets::icon_button_enabled(&mut child, "plus", tl!("Create New Sublayer"), false, new_sublayer_ok, 24.0).clicked() {
|
||||
actions.push(match (m.alt, m.command) {
|
||||
(true, true) => ("layer.newSublayer".into(), json!({"bottom": true})),
|
||||
(true, false) => ("ui.newLayer".into(), json!({"sublayer": true})),
|
||||
_ => ("layer.newSublayer".into(), json!({})),
|
||||
});
|
||||
}
|
||||
if widgets::icon_button(&mut child, "frame", tl!("Make/Release Clipping Mask"), false, 24.0).clicked() {
|
||||
actions.push(("layer.clippingMask.toggle".into(), json!({})));
|
||||
}
|
||||
// With Show Layers Only on, Locate Object becomes Locate Layer: it highlights the layer row.
|
||||
let layers_only = view.opts.layers_only;
|
||||
let locate = if layers_only { tl!("Locate Layer") } else { tl!("Locate Object") };
|
||||
let locate_ok = !layers_only || super::rows::locate_layer_listed(doc, view.root);
|
||||
if widgets::icon_button_enabled(&mut child, "search", locate, false, locate_ok, 24.0).clicked() {
|
||||
actions.push(("layer.locate".into(), json!({ "layersOnly": layers_only })));
|
||||
}
|
||||
/// A row running `id` with `params`, shown as `title`.
|
||||
fn command(id: &str, params: Value, title: &str, enabled: bool) -> Item {
|
||||
Item::Command(CommandRef::with_params(id, params), CommandState::new().title(title).enabled(enabled))
|
||||
}
|
||||
|
||||
/// A panel menu item: label, command, params, enabled, checked.
|
||||
type MenuItem<'a> = (&'a str, &'a str, Value, bool, bool);
|
||||
/// A row running `id` with `params`, shown as `title` and checked when `checked`.
|
||||
fn toggle(id: &str, params: Value, title: &str, checked: bool) -> Item {
|
||||
Item::Command(CommandRef::with_params(id, params), CommandState::new().title(title).checked(checked))
|
||||
}
|
||||
|
||||
/// The Layers panel's (≡) menu.
|
||||
pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
let Some(st) = app.session.active() else { return };
|
||||
let doc = st.doc.clone();
|
||||
/// The rows of the Layers panel menu with their states: what `menu_rows` shows and `menu_states` answers.
|
||||
fn items(app: &VectorcraftApp) -> Vec<Item> {
|
||||
let Some(st) = app.session.active() else { return vec![] };
|
||||
let doc = &st.doc;
|
||||
let rows = listed_highlighted_rows(st);
|
||||
let current = st.current_layer();
|
||||
let has_sel = !st.selection.is_empty();
|
||||
let isolated = st.isolation.is_some();
|
||||
let layers_only = app.ui.layers_panel.layers_only;
|
||||
let targets: Vec<NodeId> = if rows.is_empty() { listed_current_layer(st).into_iter().collect() } else { rows.clone() };
|
||||
let ids: Vec<u64> = targets.iter().map(|i| i.0).collect();
|
||||
let (new_layer_ok, new_sublayer_ok) = (!new_layer_unlisted(st, false, false), !new_layer_unlisted(st, true, false));
|
||||
// A copy of the isolated node goes beside it, outside the isolated art.
|
||||
let duplicate_ok = !targets.is_empty() && !st.isolation.is_some_and(|r| targets.contains(&r));
|
||||
@@ -163,143 +91,390 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
all_layers.push(n);
|
||||
}
|
||||
});
|
||||
let mut items: Vec<Option<MenuItem>> = vec![
|
||||
Some(("New Layer…", "ui.newLayer", json!({}), new_layer_ok, false)),
|
||||
Some(("New Sublayer…", "ui.newLayer", json!({"sublayer": true}), current.is_some() && new_sublayer_ok, false)),
|
||||
let export = |multiple: bool| {
|
||||
let mut p = json!({ "multiple": multiple });
|
||||
if !ids.is_empty() {
|
||||
p["ids"] = json!(ids);
|
||||
}
|
||||
p
|
||||
};
|
||||
let export_ok = !targets.is_empty() || has_sel;
|
||||
let mut items = vec![
|
||||
command("ui.newLayer", json!({}), &tl!("New Layer…"), new_layer_ok),
|
||||
command("ui.newLayer", json!({"sublayer": true}), &tl!("New Sublayer…"), current.is_some() && new_sublayer_ok),
|
||||
// The rows listed, so no highlighted row outside the isolated art is copied.
|
||||
Some(("Duplicate Selection", "layer.duplicate", json!({"ids": targets.iter().map(|i| i.0).collect::<Vec<_>>()}), duplicate_ok, false)),
|
||||
Some(("Delete Selection", "ui.layerDelete", json!({}), !targets.is_empty(), false)),
|
||||
Some(("Options for Selection…", "ui.layerOptions", json!({}), !targets.is_empty(), false)),
|
||||
None,
|
||||
Some(("Make/Release Clipping Mask", "layer.clippingMask.toggle", json!({}), true, false)),
|
||||
None,
|
||||
];
|
||||
items.push(if isolated {
|
||||
Some(("Exit Isolation Mode", "object.exitIsolation", json!({}), true, false))
|
||||
} else {
|
||||
let id = targets.first().map(|i| i.0);
|
||||
Some(("Enter Isolation Mode", "object.isolate", json!({ "id": id }), one_container, false))
|
||||
});
|
||||
items.extend([
|
||||
None,
|
||||
Some(if layers_only {
|
||||
("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel && super::rows::locate_layer_listed(&doc, st.isolation), false)
|
||||
command("layer.duplicate", json!({ "ids": ids }), &tl!("Duplicate Selection"), duplicate_ok),
|
||||
command("ui.layerDelete", json!({}), &tl!("Delete Selection"), !targets.is_empty()),
|
||||
command("ui.layerOptions", json!({}), &tl!("Options for Selection…"), !targets.is_empty()),
|
||||
Item::Separator,
|
||||
command("layer.clippingMask.toggle", json!({}), &tl!("Make/Release Clipping Mask"), true),
|
||||
Item::Separator,
|
||||
if isolated {
|
||||
command("object.exitIsolation", json!({}), &tl!("Exit Isolation Mode"), true)
|
||||
} else {
|
||||
("Locate Object", "layer.locate", json!({}), has_sel, false)
|
||||
}),
|
||||
// Sentinel: rendered as the Save Selection submenu (the Select menu's saved-selection items).
|
||||
Some(("Save Selection", "", json!({}), true, false)),
|
||||
None,
|
||||
Some(("Merge Selected", "layer.merge", json!({}), rows.len() >= 2, false)),
|
||||
Some(("Flatten Artwork", "layer.flatten", json!({}), true, false)),
|
||||
Some(("Collect in New Layer", "layer.collectInNew", json!({}), !rows.is_empty() || has_sel, false)),
|
||||
// Sentinel: rendered as Collect for Export › As Single / As Multiple (assets.add).
|
||||
Some(("Collect for Export", "", json!({}), !targets.is_empty() || has_sel, false)),
|
||||
Some(("Release to Layers (Sequence)", "layer.releaseToLayers", json!({}), one_container, false)),
|
||||
Some(("Release to Layers (Build)", "layer.releaseToLayersBuild", json!({}), one_container, false)),
|
||||
Some(("Reverse Order", "layer.reverse", json!({}), rows.len() >= 2, false)),
|
||||
None,
|
||||
Some(("Template", "layer.template", json!({}), !layers_in.is_empty(), template)),
|
||||
]);
|
||||
command("object.isolate", json!({ "id": targets.first().map(|i| i.0) }), &tl!("Enter Isolation Mode"), one_container)
|
||||
},
|
||||
Item::Separator,
|
||||
if layers_only {
|
||||
command("layer.locate", json!({"layersOnly": true}), &tl!("Locate Layer"), has_sel && super::rows::locate_layer_listed(doc, st.isolation))
|
||||
} else {
|
||||
command("layer.locate", json!({}), &tl!("Locate Object"), has_sel)
|
||||
},
|
||||
save_selection(app),
|
||||
Item::Separator,
|
||||
command("layer.merge", json!({}), &tl!("Merge Selected"), rows.len() >= 2),
|
||||
command("layer.flatten", json!({}), &tl!("Flatten Artwork"), true),
|
||||
command("layer.collectInNew", json!({}), &tl!("Collect in New Layer"), !rows.is_empty() || has_sel),
|
||||
Item::Submenu(
|
||||
tl!("Collect for Export").to_string(),
|
||||
vec![
|
||||
command("assets.add", export(false), "As Single Asset", export_ok),
|
||||
command("assets.add", export(true), "As Multiple Assets", export_ok),
|
||||
],
|
||||
),
|
||||
command("layer.releaseToLayers", json!({}), &tl!("Release to Layers (Sequence)"), one_container),
|
||||
command("layer.releaseToLayersBuild", json!({}), &tl!("Release to Layers (Build)"), one_container),
|
||||
command("layer.reverse", json!({}), &tl!("Reverse Order"), rows.len() >= 2),
|
||||
Item::Separator,
|
||||
toggle_or_enabled_template(!layers_in.is_empty(), template),
|
||||
];
|
||||
// Each pair reads by state: Hide Others while another layer shows, else Show All Layers. In
|
||||
// isolation mode the other layers are outside the isolated art, so the pairs are off.
|
||||
let any_other = |f: &dyn Fn(&Node) -> bool| others.iter().any(|l| f(l));
|
||||
items.push(Some(if any_other(&|l| l.visible) {
|
||||
("Hide Others", "layer.hideOthers", json!({}), !isolated, false)
|
||||
let outlined = |l: &Node| matches!(l.kind, NodeKind::Layer { preview: false, .. });
|
||||
items.push(if any_other(&|l| l.visible) {
|
||||
command("layer.hideOthers", json!({}), &tl!("Hide Others"), !isolated)
|
||||
} else {
|
||||
("Show All Layers", "layer.showAll", json!({}), !isolated && all_layers.iter().any(|l| !l.visible), false)
|
||||
}));
|
||||
items.push(Some(if any_other(&|l| !matches!(l.kind, NodeKind::Layer { preview: false, .. })) {
|
||||
("Outline Others", "layer.outlineOthers", json!({}), !isolated, false)
|
||||
command("layer.showAll", json!({}), &tl!("Show All Layers"), !isolated && all_layers.iter().any(|l| !l.visible))
|
||||
});
|
||||
items.push(if any_other(&|l| !outlined(l)) {
|
||||
command("layer.outlineOthers", json!({}), &tl!("Outline Others"), !isolated)
|
||||
} else {
|
||||
(
|
||||
"Preview All Layers",
|
||||
"layer.previewAll",
|
||||
json!({}),
|
||||
!isolated && all_layers.iter().any(|l| matches!(l.kind, NodeKind::Layer { preview: false, .. })),
|
||||
false,
|
||||
)
|
||||
}));
|
||||
items.push(Some(if any_other(&|l| !l.locked) {
|
||||
("Lock Others", "layer.lockOthers", json!({}), !isolated, false)
|
||||
command("layer.previewAll", json!({}), &tl!("Preview All Layers"), !isolated && all_layers.iter().any(|l| outlined(l)))
|
||||
});
|
||||
items.push(if any_other(&|l| !l.locked) {
|
||||
command("layer.lockOthers", json!({}), &tl!("Lock Others"), !isolated)
|
||||
} else {
|
||||
("Unlock All Layers", "layer.unlockAll", json!({}), !isolated && all_layers.iter().any(|l| l.locked), false)
|
||||
}));
|
||||
items.push(None);
|
||||
command("layer.unlockAll", json!({}), &tl!("Unlock All Layers"), !isolated && all_layers.iter().any(|l| l.locked))
|
||||
});
|
||||
let remembers = doc.paste_remembers_layers;
|
||||
items.push(Some(("Paste Remembers Layers", "layer.pasteRemembersLayers", json!({"on": !remembers}), true, remembers)));
|
||||
items.push(None);
|
||||
items.push(Some(("Panel Options…", "ui.layersPanelOptions", json!({}), true, false)));
|
||||
for item in items {
|
||||
match item {
|
||||
None => {
|
||||
ui.separator();
|
||||
}
|
||||
Some(("Collect for Export", _, _, enabled, _)) => {
|
||||
collect_for_export_menu(ui, enabled, |multiple| {
|
||||
let mut p = json!({ "multiple": multiple });
|
||||
if !targets.is_empty() {
|
||||
p["ids"] = json!(targets.iter().map(|id| id.0).collect::<Vec<_>>());
|
||||
}
|
||||
app.run("assets.add", p).ok();
|
||||
});
|
||||
}
|
||||
Some(("Save Selection", "", ..)) => save_selection_menu(app, ui),
|
||||
Some((label, cmd, p, enabled, checked)) => {
|
||||
if widgets::menu_item(ui, label, enabled, checked) {
|
||||
let selected = last_selected(app);
|
||||
app.run(cmd, p).ok();
|
||||
see_selection(app, ui, selected);
|
||||
}
|
||||
}
|
||||
}
|
||||
items.extend([
|
||||
Item::Separator,
|
||||
toggle("layer.pasteRemembersLayers", json!({"on": !remembers}), &tl!("Paste Remembers Layers"), remembers),
|
||||
Item::Separator,
|
||||
command("ui.layersPanelOptions", json!({}), &tl!("Panel Options…"), true),
|
||||
]);
|
||||
items
|
||||
}
|
||||
|
||||
/// The Template row: enabled with a layer among the targets, checked while the first one is one.
|
||||
fn toggle_or_enabled_template(enabled: bool, checked: bool) -> Item {
|
||||
let state = CommandState::new().title(&*tl!("Template")).enabled(enabled).checked(checked);
|
||||
Item::Command(CommandRef::with_params("layer.template", json!({})), state)
|
||||
}
|
||||
|
||||
/// Save Selection › Save Selection…, Update Selection and Edit Selection…, enabled as in the Select
|
||||
/// menu, then the active document's saved selections: choosing one recalls it.
|
||||
fn save_selection(app: &VectorcraftApp) -> Item {
|
||||
let mut rows: Vec<Item> = [("Save Selection…", "select.save"), ("Update Selection", "select.update"), ("Edit Selection…", "select.editSaved")]
|
||||
.into_iter()
|
||||
.map(|(label, id)| command(id, json!({}), label, crate::menus::enabled(app, id)))
|
||||
.collect();
|
||||
let names: Vec<String> = app.session.active().map(|d| d.doc.saved_selections.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
|
||||
if !names.is_empty() {
|
||||
rows.push(Item::Separator);
|
||||
}
|
||||
rows.extend(names.into_iter().map(|name| command(RECALL, json!({ "name": name }), &name, true)));
|
||||
Item::Submenu(tl!("Save Selection").to_string(), rows)
|
||||
}
|
||||
|
||||
/// The rows of the Layers panel's (≡) menu.
|
||||
pub(crate) fn menu_rows(app: &VectorcraftApp) -> Vec<PanelRow> {
|
||||
items(app).iter().map(Item::row).collect()
|
||||
}
|
||||
|
||||
/// The states of the menu's commands (enabled, checked and the titles that follow the state), for
|
||||
/// the frame's one set of command states.
|
||||
pub(crate) fn menu_states(app: &VectorcraftApp, states: &mut CommandStates) {
|
||||
items(app).iter().for_each(|item| item.set_states(states));
|
||||
}
|
||||
|
||||
/// Run this panel's own menu command: `ui.layers.recall {name}` recalls a saved selection and
|
||||
/// answers `None` for any other id. The panel's own command reveals nothing for the selection it
|
||||
/// makes (the request `select.recall` raised for the last selected object is dropped).
|
||||
pub(crate) fn run(app: &mut VectorcraftApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
if id != RECALL {
|
||||
return None;
|
||||
}
|
||||
let Some(name) = params.get("name").and_then(Value::as_str) else { return Some(Err("`name` must be a name".into())) };
|
||||
let r = app.run("select.recall", json!({ "name": name }));
|
||||
if let Some(st) = app.session.active_mut()
|
||||
&& matches!(st.layers_reveal, Some(LayersReveal::Selected(_)))
|
||||
{
|
||||
st.layers_reveal = None;
|
||||
}
|
||||
Some(r)
|
||||
}
|
||||
|
||||
/// An entry of a row menu whose pick is the command `id` with `params`.
|
||||
fn entry(id: &str, params: Value, label: impl Into<String>, enabled: bool) -> MenuRow<String> {
|
||||
Entry::new(CommandRef::with_params(id, params).key(), label.into()).enabled(enabled).into()
|
||||
}
|
||||
|
||||
/// A separator of a row menu.
|
||||
fn separator() -> MenuRow<String> {
|
||||
Entry::<String>::separator().into()
|
||||
}
|
||||
|
||||
/// A row's name cut to 20 characters, as the Duplicate and Delete entries show it.
|
||||
fn short_name(n: &Node) -> String {
|
||||
let raw = painted_name(n, &n.display_name(), crate::i18n::current());
|
||||
if raw.chars().count() > 20 { format!("{}…", raw.chars().take(20).collect::<String>()) } else { raw }
|
||||
}
|
||||
|
||||
/// The entries of the menu on a row, with each pick's command as its value. It acts on the
|
||||
/// highlighted rows when the row is one of them. The panel adds its own Label Color submenu.
|
||||
pub(crate) fn row_menu(tree: &DocLayers, target: &MenuTarget<RowId>) -> Vec<MenuRow<String>> {
|
||||
let Some(LayerRowKey::Layer(row)) = &target.row else { return vec![] };
|
||||
match row {
|
||||
RowId::Guide(i) => guide_menu(tree, *i),
|
||||
RowId::Spine(blend) => spine_menu(tree, *blend),
|
||||
RowId::Node(id) => object_menu(tree, *id, &tree.targets(target)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Collect for Export › As Single Asset / As Multiple Assets (`assets.add`).
|
||||
pub(super) fn collect_for_export_menu(ui: &mut Ui, enabled: bool, mut run: impl FnMut(bool)) {
|
||||
ui.add_enabled_ui(enabled, |ui| {
|
||||
// English labels match the rest of this panel menu (and Object › Collect for Export).
|
||||
ui.menu_button("Collect for Export", |ui| {
|
||||
if widgets::menu_item(ui, "As Single Asset", true, false) {
|
||||
run(false);
|
||||
ui.close();
|
||||
}
|
||||
if widgets::menu_item(ui, "As Multiple Assets", true, false) {
|
||||
run(true);
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
/// The entries of a layer, sublayer, group or object row `id`; `ids` are the rows they act on.
|
||||
fn object_menu(tree: &DocLayers, id: NodeId, ids: &[u64]) -> Vec<MenuRow<String>> {
|
||||
let doc = tree.doc();
|
||||
let Some(n) = doc.node(id) else { return vec![] };
|
||||
let multi = ids.len() > 1;
|
||||
if n.is_guide() {
|
||||
let any = |f: fn(&Node) -> bool| ids.iter().filter_map(|&id| doc.node(NodeId(id))).any(f);
|
||||
let (unlocked, visible) = (any(|n| !n.locked), any(|n| n.visible));
|
||||
return vec![
|
||||
entry("view.guides.release", json!({ "ids": ids }), if multi { "Release Guides" } else { "Release Guide" }, true),
|
||||
entry("layer.duplicate", json!({ "ids": ids }), if multi { "Duplicate Selection" } else { "Duplicate" }, true),
|
||||
entry("layer.delete", json!({ "ids": ids }), if multi { "Delete Guides" } else { "Delete Guide" }, true),
|
||||
separator(),
|
||||
entry("layer.setProps", json!({ "ids": ids, "locked": unlocked }), if unlocked { "Lock" } else { "Unlock" }, true),
|
||||
entry("layer.setProps", json!({ "ids": ids, "visible": !visible }), if visible { "Hide" } else { "Show" }, true),
|
||||
];
|
||||
}
|
||||
let options = if multi {
|
||||
"Options for Selection…"
|
||||
} else if n.is_layer() {
|
||||
"Layer Options…"
|
||||
} else {
|
||||
"Options…"
|
||||
};
|
||||
let name = short_name(n);
|
||||
let duplicate = if multi { tl!("Duplicate Selection").to_string() } else { format!("{} \"{name}\"", tl!("Duplicate")) };
|
||||
let delete = if multi { tl!("Delete Selection").to_string() } else { format!("{} \"{name}\"", tl!("Delete")) };
|
||||
let listed: HashSet<NodeId> = ids.iter().map(|&id| NodeId(id)).collect();
|
||||
// A copy of the isolated node goes beside it, outside the isolated art.
|
||||
let duplicate_ok = !tree.root().is_some_and(|r| ids.contains(&r.0));
|
||||
let delete_ok = !doc.layers.iter().all(|l| listed.contains(&l.id));
|
||||
// In isolation mode the other layers are outside the isolated art, so these pairs are off.
|
||||
let others_ok = tree.root().is_none();
|
||||
let (lock, lock_params, lock_ok) = super::rows::multi_others_action(doc, ids, false);
|
||||
let (hide, hide_params, hide_ok) = super::rows::multi_others_action(doc, ids, true);
|
||||
let lock_label = if lock == "layer.lockOthers" { "Lock Others" } else { "Unlock All Layers" };
|
||||
let hide_label = if hide == "layer.hideOthers" { "Hide Others" } else { "Show All Layers" };
|
||||
let layers_only = tree.layers_only();
|
||||
let export = |multiple: bool| json!({ "ids": ids, "multiple": multiple });
|
||||
vec![
|
||||
entry("ui.layerOptions", json!({ "ids": ids }), options, true),
|
||||
entry("layer.duplicate", json!({ "ids": ids }), duplicate, duplicate_ok),
|
||||
entry("layer.delete", json!({ "ids": ids }), delete, delete_ok),
|
||||
separator(),
|
||||
entry(&lock, lock_params, lock_label, lock_ok && others_ok),
|
||||
entry(&hide, hide_params, hide_label, hide_ok && others_ok),
|
||||
separator(),
|
||||
locate_entry(tree, id.0),
|
||||
separator(),
|
||||
MenuRow::Submenu(
|
||||
tl!("Collect for Export").to_string().into(),
|
||||
vec![entry("assets.add", export(false), "As Single Asset", true), entry("assets.add", export(true), "As Multiple Assets", true)],
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Save Selection › Save Selection…, Update Selection and Edit Selection…, enabled and run as in
|
||||
/// the Select menu, then the active document's saved selections: choosing one recalls it.
|
||||
fn save_selection_menu(app: &mut VectorcraftApp, ui: &mut Ui) {
|
||||
ui.menu_button(format!(" {}", tl!("Save Selection")), |ui| {
|
||||
widgets::menu_scroll(ui, |ui| {
|
||||
for (label, id) in [("Save Selection…", "select.save"), ("Update Selection", "select.update"), ("Edit Selection…", "select.editSaved")]
|
||||
{
|
||||
if widgets::menu_item(ui, label, crate::menus::enabled(app, id), false) {
|
||||
crate::menus::invoke(app, id, json!({}));
|
||||
ui.close();
|
||||
}
|
||||
/// Locate Object, or Locate Layer with Show Layers Only on, for row `id`.
|
||||
fn locate_entry(tree: &DocLayers, id: Option<u64>) -> MenuRow<String> {
|
||||
let layers_only = tree.layers_only();
|
||||
let ok = !layers_only || super::rows::locate_layer_listed(tree.doc(), tree.root());
|
||||
entry("layer.locate", json!({ "id": id, "layersOnly": layers_only }), if layers_only { "Locate Layer" } else { "Locate Object" }, ok)
|
||||
}
|
||||
|
||||
/// The entries of ruler guide row `i`: they act on the selected guides when it is one of them.
|
||||
fn guide_menu(tree: &DocLayers, i: usize) -> Vec<MenuRow<String>> {
|
||||
let doc = tree.doc();
|
||||
let guides = doc.ruler_guides();
|
||||
let Some(g) = guides.get(i) else { return vec![] };
|
||||
let selected = tree.guides().contains(&i);
|
||||
let editable = doc.guide_editable(g);
|
||||
let acts: Vec<usize> = if selected { tree.guides().to_vec() } else { vec![i] };
|
||||
let nodes: Vec<u64> = acts.iter().filter_map(|&idx| guides.get(idx)?.id.map(|id| id.0)).collect();
|
||||
let node = g.id.and_then(|id| doc.node(id));
|
||||
let (visible, locked) = (node.is_none_or(|n| n.visible), node.is_some_and(|n| n.locked));
|
||||
let release = if acts.len() > 1 { json!({}) } else { json!({ "index": i }) };
|
||||
vec![
|
||||
entry("layer.setProps", json!({ "ids": nodes, "visible": !visible }), if visible { "Hide" } else { "Show" }, !nodes.is_empty()),
|
||||
entry("layer.setProps", json!({ "ids": nodes, "locked": !locked }), if locked { "Unlock" } else { "Lock" }, !nodes.is_empty()),
|
||||
separator(),
|
||||
entry("view.guides.release", release, "Release Guides", editable),
|
||||
entry("guide.remove", json!({ "indexes": acts }), "Delete", editable),
|
||||
separator(),
|
||||
locate_entry(tree, g.id.map(|id| id.0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// The entries of the spine row of blend `blend`. They act on the selection, which the row's press
|
||||
/// makes the blend (a click selects it), as the Object menu's blend commands do.
|
||||
// PLAN: assumed document-panels-w7 selects the blend on the row's secondary press: a menu pick is one command, so it cannot select first.
|
||||
fn spine_menu(tree: &DocLayers, blend: NodeId) -> Vec<MenuRow<String>> {
|
||||
let doc = tree.doc();
|
||||
let editable = (doc.editable())(blend);
|
||||
let has_spine = !matches!(doc.node(blend).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine);
|
||||
vec![
|
||||
entry("select.set", json!({ "ids": [blend.0] }), "Select", editable),
|
||||
entry("ui.blendOptions", json!({}), "Blend Options…", editable),
|
||||
separator(),
|
||||
entry("object.blend.reverseSpine", json!({}), "Reverse Spine", editable && has_spine),
|
||||
entry("object.blend.reverseFrontToBack", json!({}), "Reverse Front to Back", editable),
|
||||
entry("object.blend.expand", json!({}), "Expand", editable),
|
||||
entry("object.blend.release", json!({}), "Release", editable),
|
||||
separator(),
|
||||
locate_entry(tree, Some(blend.0)),
|
||||
]
|
||||
}
|
||||
|
||||
/// What was dropped on a footer action.
|
||||
pub(super) enum FooterPayload<'a> {
|
||||
/// Rows of the panel.
|
||||
Rows(&'a [LayerRowKey<RowId>]),
|
||||
/// The target circle of an appearance (its node id).
|
||||
Appearance(u64),
|
||||
}
|
||||
|
||||
/// The node ids and the ruler guide indexes among `keys`.
|
||||
fn row_ids(keys: &[LayerRowKey<RowId>]) -> (Vec<u64>, Vec<usize>) {
|
||||
let (mut nodes, mut guides) = (vec![], vec![]);
|
||||
for key in keys {
|
||||
match key {
|
||||
LayerRowKey::Layer(RowId::Node(id) | RowId::Spine(id)) => nodes.push(id.0),
|
||||
LayerRowKey::Layer(RowId::Guide(i)) => guides.push(*i),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
(nodes, guides)
|
||||
}
|
||||
|
||||
/// The command a press of footer action `index` runs, with the modifiers held at the press. Delete
|
||||
/// with no row highlighted deletes the selected art and ruler guides. New Layer: Alt asks for its
|
||||
/// options first, Ctrl/Cmd puts it on top of every layer, Ctrl/Cmd+Alt directly below the current
|
||||
/// layer. New Sublayer: Alt asks for its options first, Ctrl/Cmd+Alt puts it under the layer's contents.
|
||||
pub(super) fn footer_pick(tree: &DocLayers, index: usize, mods: Mods) -> Option<(String, Value)> {
|
||||
let (id, params) = match index {
|
||||
DELETE => {
|
||||
let st = tree.state();
|
||||
if listed_highlighted_rows(st).is_empty() && st.selection.has_objects_or_guides() {
|
||||
("edit.clear", json!({}))
|
||||
} else {
|
||||
("ui.layerDelete", json!({}))
|
||||
}
|
||||
let names: Vec<String> =
|
||||
app.session.active().map(|d| d.doc.saved_selections.iter().map(|s| s.name.clone()).collect()).unwrap_or_default();
|
||||
if !names.is_empty() {
|
||||
ui.separator();
|
||||
}
|
||||
NEW_LAYER => match (mods.alt, mods.cmd) {
|
||||
(true, true) => ("layer.new", json!({"below": true})),
|
||||
(true, false) => ("ui.newLayer", json!({})),
|
||||
_ => ("layer.new", json!({"top": mods.cmd})),
|
||||
},
|
||||
NEW_SUBLAYER => match (mods.alt, mods.cmd) {
|
||||
(true, true) => ("layer.newSublayer", json!({"bottom": true})),
|
||||
(true, false) => ("ui.newLayer", json!({"sublayer": true})),
|
||||
_ => ("layer.newSublayer", json!({})),
|
||||
},
|
||||
MASK => ("layer.clippingMask.toggle", json!({})),
|
||||
LOCATE => ("layer.locate", json!({ "layersOnly": tree.layers_only() })),
|
||||
_ => return None,
|
||||
};
|
||||
Some((id.into(), params))
|
||||
}
|
||||
|
||||
/// The command for `drop` dropped on footer action `index`: rows on Delete delete them (the node
|
||||
/// rows, else the ruler guides), rows on New Layer duplicate them (not the isolated node, not
|
||||
/// guides), an appearance's target circle on Delete reduces it to one fill and one stroke.
|
||||
pub(super) fn footer_drop(tree: &DocLayers, index: usize, drop: FooterPayload<'_>) -> Option<(String, Value)> {
|
||||
match (index, drop) {
|
||||
(DELETE, FooterPayload::Rows(keys)) => {
|
||||
let (nodes, guides) = row_ids(keys);
|
||||
if !nodes.is_empty() {
|
||||
Some(("ui.layerDelete".into(), json!({ "ids": nodes })))
|
||||
} else if !guides.is_empty() {
|
||||
Some(("guide.remove".into(), json!({ "indexes": guides })))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
for name in names {
|
||||
if widgets::menu_item_name(ui, &name, true, false) {
|
||||
let selected = last_selected(app);
|
||||
app.run("select.recall", json!({ "name": name })).ok();
|
||||
see_selection(app, ui, selected);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
(NEW_LAYER, FooterPayload::Rows(keys)) => {
|
||||
let (nodes, _) = row_ids(keys);
|
||||
let isolated = tree.root().is_some_and(|r| nodes.contains(&r.0));
|
||||
(!nodes.is_empty() && !isolated).then(|| ("layer.duplicate".into(), json!({ "ids": nodes })))
|
||||
}
|
||||
(DELETE, FooterPayload::Appearance(id)) => Some(("appearance.reduceToBasic".into(), json!({ "ids": [id] }))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The panel's footer: the layer count and the buttons. A press or a drop adds its command to `out`.
|
||||
pub(crate) fn footer(tree: &DocLayers, ui: &mut Ui, out: &mut Vec<(String, Value)>) {
|
||||
let st = tree.state();
|
||||
let mods = ui.input(|i| i.modifiers);
|
||||
// In isolation mode New Layer and New Sublayer are off while the layer they make would be
|
||||
// outside the isolated art, where the panel does not list it.
|
||||
let new_layer_ok = !new_layer_unlisted(st, false, mods.command && !mods.alt);
|
||||
let new_sublayer_ok = !new_layer_unlisted(st, true, false);
|
||||
let layers_only = tree.layers_only();
|
||||
let locate_ok = !layers_only || super::rows::locate_layer_listed(tree.doc(), tree.root());
|
||||
let root = tree.root();
|
||||
let icon = |name: &'static str| IconSpec::svg(IconId::new(name));
|
||||
let layer_rows = |keys: &[LayerRowKey<RowId>]| keys.iter().all(|key| matches!(key, LayerRowKey::Layer(_)));
|
||||
let actions = [
|
||||
// PLAN: the framework's `accepts_drops` takes one payload type, so Delete cannot also take
|
||||
// `PanelDrag` (the appearance drop `footer_drop` maps); it needs a second payload there.
|
||||
FooterAction::new(icon("trash-2"), tl!("Delete Selection").to_string())
|
||||
.takes_drops_disabled(true)
|
||||
.accepts_drops(move |d: &ListDrag<LayerRowKey<RowId>>| layer_rows(&d.keys)),
|
||||
FooterAction::new(icon("file-plus"), tl!("Create New Layer").to_string()).enabled(new_layer_ok).accepts_drops(
|
||||
move |d: &ListDrag<LayerRowKey<RowId>>| {
|
||||
let (nodes, guides) = row_ids(&d.keys);
|
||||
layer_rows(&d.keys) && guides.is_empty() && !root.is_some_and(|r| nodes.contains(&r.0))
|
||||
},
|
||||
),
|
||||
FooterAction::new(icon("plus"), tl!("Create New Sublayer").to_string()).enabled(new_sublayer_ok),
|
||||
FooterAction::new(icon("frame"), tl!("Make/Release Clipping Mask").to_string()),
|
||||
FooterAction::new(icon("search"), if layers_only { tl!("Locate Layer").to_string() } else { tl!("Locate Object").to_string() })
|
||||
.enabled(locate_ok),
|
||||
];
|
||||
let count = crate::i18n::tn(tree.doc().layers.len() as u64, "{n} Layer", "{n} Layers").to_string();
|
||||
let (output, _) = FooterBar::actions(actions).at_start(0).show_footer_leading(ui, |ui, _| {
|
||||
ui.weak(&count);
|
||||
});
|
||||
// The footer runs twice per pass: the sizing pass measures it and must report nothing.
|
||||
if ui.is_sizing_pass() {
|
||||
return;
|
||||
}
|
||||
out.extend(output.picked.and_then(|index| footer_pick(tree, index, output.mods)));
|
||||
if let Some(drop) = &output.dropped {
|
||||
let run = if let Some(d) = drop.payload::<ListDrag<LayerRowKey<RowId>>>() {
|
||||
footer_drop(tree, drop.index, FooterPayload::Rows(&d.keys))
|
||||
} else if let Some(PanelDrag::Appearance(id)) = drop.payload::<PanelDrag>() {
|
||||
footer_drop(tree, drop.index, FooterPayload::Appearance(id.0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
out.extend(run);
|
||||
}
|
||||
}
|
||||
|
||||
/// `ui.layerDelete {ids?|id?, doc?, confirmed?}`: Delete Selection as the Layers panel runs it (the
|
||||
@@ -440,18 +615,19 @@ pub fn expand(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
|
||||
/// `ui.layersFilter {objects?, layers?}`: set the Layers panel's Filter, `objects` to the object
|
||||
/// kinds ticked under By Object and `layers` to the row states ticked under By Layer, by parameter
|
||||
/// name ([`ObjectKind::ALL`], [`RowState::ALL`]). A key left out or set to null keeps its list; any
|
||||
/// other value that is not an array of those names is an error, and then nothing changes.
|
||||
/// name ([`FilterObject::ALL`], [`FilterState::ALL`]). A key left out or set to null keeps its list; any
|
||||
/// other value that is not an array of those names is an error, and then nothing changes. The
|
||||
/// panel deselects nothing.
|
||||
/// → {objects, layers}
|
||||
pub fn set_filter(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
|
||||
let objects = parse_names(p, "objects", &ObjectKind::ALL)?;
|
||||
let layers = parse_names(p, "layers", &RowState::ALL)?;
|
||||
let f = &mut app.ui.layers_filter;
|
||||
let objects = parse_names(p, "objects", &FilterObject::ALL)?;
|
||||
let layers = parse_names(p, "layers", &FilterState::ALL)?;
|
||||
let f = &mut app.ui.layers_ui.filter;
|
||||
if let Some(objects) = objects {
|
||||
f.objects = objects;
|
||||
}
|
||||
if let Some(layers) = layers {
|
||||
f.layers = layers;
|
||||
f.states = layers;
|
||||
}
|
||||
Ok(json!({"objects": names(&ObjectKind::ALL, &f.objects), "layers": names(&RowState::ALL, &f.layers)}))
|
||||
Ok(json!({"objects": names(&FilterObject::ALL, &f.objects), "layers": names(&FilterState::ALL, &f.states)}))
|
||||
}
|
||||
|
||||
@@ -1,25 +1,10 @@
|
||||
use std::collections::HashSet;
|
||||
use craft::layers::ui::{LayerThumb, LayerThumbKind}; // PLAN: assumed path of craft-layers' thumbnail key
|
||||
use craft_ui::primitives::textures::{LoadFailure, LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource, ThumbnailOptions, Thumbnails};
|
||||
use vectorcraft_doc::{NodeKind, TextKind};
|
||||
use vectorcraft_geom::PathData;
|
||||
|
||||
use super::{Arc, Color32, Document, HashMap, Node, NodeId, Settle, ThumbWorker, Ui, VectorcraftApp, Weak, vec2};
|
||||
use crate::thumb_worker::Done;
|
||||
|
||||
/// Where row thumbnails come from: document `uid` at `revision`, and whether a drag is in
|
||||
/// progress (the thumbnails shown then stay until it ends).
|
||||
pub(crate) struct ThumbSource<'a> {
|
||||
pub uid: u64,
|
||||
pub revision: u64,
|
||||
pub doc: &'a Arc<Document>,
|
||||
pub busy: bool,
|
||||
}
|
||||
|
||||
impl<'a> ThumbSource<'a> {
|
||||
/// The thumbnails of the document `st` holds (`doc`, its document).
|
||||
pub(crate) fn of(app: &VectorcraftApp, st: &vectorcraft_engine::DocState, doc: &'a Arc<Document>) -> Self {
|
||||
Self { uid: st.uid, revision: st.revision, doc, busy: st.interaction.is_some() || app.session.tool_busy() }
|
||||
}
|
||||
}
|
||||
use super::model::RowId; // PLAN: assumed document-panels-w7's `RowId::{Node(NodeId), Guide(usize), Spine(NodeId)}`
|
||||
use super::{Arc, Document, Node, NodeId};
|
||||
|
||||
/// Node `id` of `doc`, as the `Arc` its parent holds.
|
||||
pub(crate) fn node_arc(doc: &Document, id: NodeId) -> Option<Arc<Node>> {
|
||||
@@ -32,60 +17,139 @@ pub(crate) fn node_arc(doc: &Document, id: NodeId) -> Option<Arc<Node>> {
|
||||
Some(cur.clone())
|
||||
}
|
||||
|
||||
/// A row thumbnail's image.
|
||||
struct ThumbEntry {
|
||||
/// The node it shows. Weak, so the cache doesn't keep old art alive, but its allocation stays
|
||||
/// and no other node can come to have its address.
|
||||
node: Weak<Node>,
|
||||
px: u32,
|
||||
/// None: the node draws nothing.
|
||||
tex: Option<egui::TextureHandle>,
|
||||
/// How long it took to render (ms).
|
||||
ms: f64,
|
||||
/// The pass it was last drawn in.
|
||||
used: u64,
|
||||
/// A node of the Links panel's rows: the document and the node, nested ones included.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct NodeThumb {
|
||||
/// The document's uid.
|
||||
pub uid: u64,
|
||||
/// The node the row shows.
|
||||
pub node: NodeId,
|
||||
}
|
||||
|
||||
/// A row thumbnail job: the row (document uid, node), the node and the size rendered.
|
||||
type ThumbJob = ((u64, NodeId), Weak<Node>, u32);
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Thumbs {
|
||||
entries: HashMap<(u64, NodeId), ThumbEntry>,
|
||||
/// Documents still open. None until the app first synchronizes its documents.
|
||||
open_docs: Option<HashSet<u64>>,
|
||||
/// What the worker is rendering, by row.
|
||||
pending: HashMap<(u64, NodeId), (Weak<Node>, u32)>,
|
||||
worker: Option<ThumbWorker<(u64, NodeId), ThumbJob>>,
|
||||
worker_started: bool,
|
||||
/// The uid of the document whose rows were last drawn: the worker holds jobs for it alone.
|
||||
pub(super) showing: Option<u64>,
|
||||
settle: Settle,
|
||||
/// (pass, ms, count) rendered on the UI thread in that pass.
|
||||
spent: (u64, f64, u32),
|
||||
/// Thumbnails rendered on the UI thread (tests count them).
|
||||
pub(super) renders: u64,
|
||||
/// A test's clock (ms) for the render budget, replacing [`crate::now_ms`] so a test decides how
|
||||
/// long each render takes (production always leaves this `None`).
|
||||
#[cfg(test)]
|
||||
pub(super) clock: Option<Box<dyn FnMut() -> f64>>,
|
||||
/// The thumbnails of one document's Layers panel, one store for each document: node ids repeat across
|
||||
/// documents, and a key shared by two would show one document's picture for the other's row.
|
||||
pub(crate) fn layer_thumbnails(ctx: &egui::Context, uid: u64) -> Thumbnails<LayerThumb<RowId>> {
|
||||
Thumbnails::in_context(ctx, ("vc-layer-thumbs", uid), ThumbnailOptions::new())
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
pub(super) static THUMBS: crate::graphics::TexCache<Thumbs> = crate::graphics::TexCache::default();
|
||||
/// The thumbnails of the Links panel's rows, for every document.
|
||||
pub(crate) fn link_thumbnails(ctx: &egui::Context) -> Thumbnails<NodeThumb> {
|
||||
Thumbnails::in_context(ctx, "vc-link-thumbs", ThumbnailOptions::new())
|
||||
}
|
||||
|
||||
/// The most row thumbnails kept: past it the ones drawn longest ago go.
|
||||
const MAX_THUMBS: usize = 512;
|
||||
/// Forget every thumbnail of document `uid`'s Layers panel, when it closes.
|
||||
pub(crate) fn forget(ctx: &egui::Context, uid: u64) {
|
||||
layer_thumbnails(ctx, uid).retain(ctx, |_| false);
|
||||
}
|
||||
|
||||
/// Rendering a thumbnail that took longer than this (ms) again goes to the worker.
|
||||
const LIGHT_THUMB_MS: f64 = 4.0;
|
||||
/// Keep the Links panel's thumbnails of the documents in `uids`, the open ones.
|
||||
pub(crate) fn retain_open(ctx: &egui::Context, uids: &[u64]) {
|
||||
link_thumbnails(ctx).retain(ctx, |key| uids.contains(&key.uid));
|
||||
}
|
||||
|
||||
/// A node with more objects than this inside has its first thumbnail made on the worker.
|
||||
/// The version of `node`'s picture: the node's identity, since an unchanged node keeps its `Arc`
|
||||
/// allocation and an edited one gets another.
|
||||
fn node_revision(node: &Arc<Node>, request: &ThumbRequest) -> Revision {
|
||||
Revision::of(&(Arc::as_ptr(node) as usize, request.side))
|
||||
}
|
||||
|
||||
/// Where the Layers panel's thumbnails come from: the rows of document `doc`.
|
||||
pub(crate) struct LayerThumbs<'a> {
|
||||
/// The document the rows are of.
|
||||
pub doc: &'a Arc<Document>,
|
||||
}
|
||||
|
||||
// PLAN: the sheet's `tree` field is left out: `RowId` already says which rows have no picture (guides and spines).
|
||||
impl LayerThumbs<'_> {
|
||||
/// The node of the row `key` names, when it has a picture of its own to show.
|
||||
fn node(&self, key: &LayerThumb<RowId>) -> Option<Arc<Node>> {
|
||||
if key.kind != LayerThumbKind::Pixels {
|
||||
return None;
|
||||
}
|
||||
match &key.layer {
|
||||
RowId::Node(id) => node_arc(self.doc, *id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ThumbSource<LayerThumb<RowId>> for LayerThumbs<'_> {
|
||||
fn revision(&self, key: &LayerThumb<RowId>, request: &ThumbRequest) -> Revision {
|
||||
self.node(key).map_or_else(Revision::default, |n| node_revision(&n, request))
|
||||
}
|
||||
|
||||
fn render(&self, key: &LayerThumb<RowId>, request: &ThumbRequest) -> ThumbRender {
|
||||
match self.node(key) {
|
||||
Some(n) => {
|
||||
let light = light_row(&n, None, self.doc);
|
||||
render(n, self.doc.clone(), request, light)
|
||||
}
|
||||
None => ThumbRender::Blank,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the Links panel's thumbnails come from: the nodes of document `doc`, found by `lookup`
|
||||
/// (nested nodes are not in the document's own tree).
|
||||
pub(crate) struct NodeThumbs<'a, F: Fn(NodeId) -> Option<Arc<Node>>> {
|
||||
doc: &'a Arc<Document>,
|
||||
lookup: F,
|
||||
}
|
||||
|
||||
impl<'a, F: Fn(NodeId) -> Option<Arc<Node>>> NodeThumbs<'a, F> {
|
||||
/// The source of the rows of `doc`.
|
||||
pub(crate) fn new(doc: &'a Arc<Document>, lookup: F) -> Self {
|
||||
Self { doc, lookup }
|
||||
}
|
||||
}
|
||||
|
||||
impl<F: Fn(NodeId) -> Option<Arc<Node>>> ThumbSource<NodeThumb> for NodeThumbs<'_, F> {
|
||||
fn revision(&self, key: &NodeThumb, request: &ThumbRequest) -> Revision {
|
||||
(self.lookup)(key.node).map_or_else(Revision::default, |n| node_revision(&n, request))
|
||||
}
|
||||
|
||||
fn render(&self, key: &NodeThumb, request: &ThumbRequest) -> ThumbRender {
|
||||
match (self.lookup)(key.node) {
|
||||
Some(n) => {
|
||||
let light = light_row(&n, None, self.doc);
|
||||
render(n, self.doc.clone(), request, light)
|
||||
}
|
||||
None => ThumbRender::Blank,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The thumbnail of `node` (of `doc`) for `request`: made here and now when `light`, else as a job
|
||||
/// for a lane that stops when cancelled. A node that draws nothing is `Blank`.
|
||||
pub(crate) fn render(node: Arc<Node>, doc: Arc<Document>, request: &ThumbRequest, light: bool) -> ThumbRender {
|
||||
let side = request.side;
|
||||
if light {
|
||||
thread_local! {
|
||||
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
return match RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), &doc, &node, side)) {
|
||||
Some(img) => ThumbRender::Ready(crate::canvas::color_image(&img)),
|
||||
None => ThumbRender::Blank,
|
||||
};
|
||||
}
|
||||
ThumbRender::Later(Box::new(move |cancel| {
|
||||
let cancelled = || LoadFailure::Message("cancelled".to_owned());
|
||||
if cancel.is_cancelled() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
let img = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &node, side);
|
||||
if cancel.is_cancelled() {
|
||||
return Err(cancelled());
|
||||
}
|
||||
Ok(img.map_or(LoadedPicture::Blank, |img| LoadedPicture::Image(crate::canvas::color_image(&img))))
|
||||
}))
|
||||
}
|
||||
|
||||
/// A node with more objects than this inside has its first thumbnail made on a lane.
|
||||
const LIGHT_THUMB_NODES: usize = 200;
|
||||
|
||||
/// A node whose paths have more anchors than this in all has its first thumbnail made on the
|
||||
/// worker. Type's glyphs, mesh points and image pixels count against it too, each as the anchors
|
||||
/// A node whose paths have more anchors than this in all has its first thumbnail made on a lane.
|
||||
/// Type's glyphs, mesh points and image pixels count against it too, each as the anchors
|
||||
/// that take about as long to render: [`GLYPH_ANCHORS`], [`MESH_POINT_ANCHORS`] and
|
||||
/// [`IMAGE_PIXELS_PER_ANCHOR`].
|
||||
const LIGHT_THUMB_ANCHORS: usize = 2_000;
|
||||
@@ -100,22 +164,15 @@ const MESH_POINT_ANCHORS: usize = 1;
|
||||
const IMAGE_PIXELS_PER_ANCHOR: usize = 100;
|
||||
|
||||
/// The most symbols and placed documents counted inside one another: a node holding them deeper
|
||||
/// (a symbol whose art holds an instance of itself, for one) has its first thumbnail made on the
|
||||
/// worker.
|
||||
/// (a symbol whose art holds an instance of itself, for one) has its first thumbnail made on a
|
||||
/// lane.
|
||||
const MAX_THUMB_NESTING: usize = 8;
|
||||
|
||||
/// The most steps counting a node takes: each object, subpath, text run and symbol looked at is
|
||||
/// one step, and so is every 64 bytes of a symbol or placed file name looked up. A node that
|
||||
/// needs more has its thumbnail made on the worker, and the painted thumbnail draws nothing for
|
||||
/// it. A row drawn before counts at most this many objects too.
|
||||
/// needs more has its thumbnail made on a lane.
|
||||
const THUMB_COUNT_STEPS: usize = 20_000;
|
||||
|
||||
/// At most this long (ms) and this many thumbnails are rendered on the UI thread in a pass; the
|
||||
/// rest go to the worker, or wait for the next pass where there is none.
|
||||
const THUMB_BUDGET_MS: f64 = 8.0;
|
||||
|
||||
const THUMB_BUDGET_COUNT: u32 = 16;
|
||||
|
||||
/// How row thumbnails render: images far smaller than they are sample their mip levels.
|
||||
pub(crate) fn thumb_options() -> vectorcraft_render::RenderOptions {
|
||||
vectorcraft_render::RenderOptions { image_mips: true, ..Default::default() }
|
||||
@@ -251,335 +308,20 @@ fn light_row(n: &Node, quick: Option<bool>, doc: &Document) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or the worker.
|
||||
/// The thumbnail of `n` (`px` pixels square) as `r` renders it, on the UI thread or a lane.
|
||||
fn render_thumb(r: &mut vectorcraft_render::Renderer, doc: &Document, n: &Node, px: u32) -> Option<vectorcraft_render::Rendered> {
|
||||
r.render_node_thumbnail_with(doc, n, px, None, &thumb_options())
|
||||
}
|
||||
|
||||
impl Thumbs {
|
||||
#[cfg(test)]
|
||||
pub(super) fn cached(&self, uid: u64) -> bool {
|
||||
self.entries.keys().any(|key| key.0 == uid)
|
||||
}
|
||||
|
||||
/// The time (ms) a render on the UI thread is measured by: [`crate::now_ms`], or a test's clock.
|
||||
fn now_ms(&mut self) -> f64 {
|
||||
#[cfg(test)]
|
||||
if let Some(clock) = self.clock.as_mut() {
|
||||
return clock();
|
||||
}
|
||||
crate::now_ms()
|
||||
}
|
||||
|
||||
/// Release thumbnails and queued jobs for documents that have closed, keeping the cache for
|
||||
/// other open documents even when the panels are hidden or another document is active. When a
|
||||
/// document closes, the worker drops its jobs, the one running included, and the images it
|
||||
/// finished that the panels have not collected yet.
|
||||
fn retain_open(&mut self, uids: &[u64]) {
|
||||
if self.open_docs.as_ref().is_some_and(|open| open.len() == uids.len() && uids.iter().all(|uid| open.contains(uid))) {
|
||||
return;
|
||||
}
|
||||
let open: HashSet<u64> = uids.iter().copied().collect();
|
||||
let closed: HashSet<u64> = self.open_docs.as_ref().map(|before| before.difference(&open).copied().collect()).unwrap_or_default();
|
||||
let stale =
|
||||
self.entries.keys().chain(self.pending.keys()).any(|key| !open.contains(&key.0)) || self.showing.is_some_and(|uid| !open.contains(&uid));
|
||||
self.entries.retain(|key, _| open.contains(&key.0));
|
||||
self.pending.retain(|key, _| open.contains(&key.0));
|
||||
self.showing = self.showing.filter(|uid| open.contains(uid));
|
||||
if !closed.is_empty() {
|
||||
// Images finished before now are dropped with the rest of the queue: the open
|
||||
// documents' rows are asked for again. Documents opened later keep their jobs.
|
||||
if let Some(w) = &self.worker {
|
||||
w.forget(move |key| closed.contains(&key.0));
|
||||
if w.poll().is_none() {
|
||||
self.worker = None;
|
||||
}
|
||||
}
|
||||
self.pending.clear();
|
||||
} else if stale
|
||||
&& let Some(w) = &self.worker
|
||||
&& !w.discard({
|
||||
let open = open.clone();
|
||||
move |key| !open.contains(&key.0)
|
||||
})
|
||||
{
|
||||
self.worker = None;
|
||||
self.pending.clear();
|
||||
}
|
||||
self.open_docs = Some(open);
|
||||
}
|
||||
|
||||
/// Keep `img` (None: nothing drawn) as the thumbnail of row `key` showing `node`.
|
||||
fn upload(&mut self, ctx: &egui::Context, key: (u64, NodeId), node: Weak<Node>, px: u32, img: Option<&vectorcraft_render::Rendered>, ms: f64) {
|
||||
let color = img.map(crate::canvas::color_image);
|
||||
let used = ctx.cumulative_pass_nr();
|
||||
let name = format!("layer-thumb-{}", key.1.0);
|
||||
match self.entries.get_mut(&key) {
|
||||
Some(e) => {
|
||||
match (color, &mut e.tex) {
|
||||
(Some(color), Some(tex)) => tex.set(color, egui::TextureOptions::LINEAR),
|
||||
(Some(color), tex) => *tex = Some(ctx.load_texture(name, color, egui::TextureOptions::LINEAR)),
|
||||
(None, tex) => *tex = None,
|
||||
}
|
||||
(e.node, e.px, e.ms, e.used) = (node, px, ms, used);
|
||||
}
|
||||
None => {
|
||||
let tex = color.map(|color| ctx.load_texture(name, color, egui::TextureOptions::LINEAR));
|
||||
self.entries.insert(key, ThumbEntry { node, px, tex, ms, used });
|
||||
if self.entries.len() > MAX_THUMBS {
|
||||
// Keep the three quarters drawn last.
|
||||
let mut by_use: Vec<u64> = self.entries.values().map(|e| e.used).collect();
|
||||
by_use.sort_unstable();
|
||||
let cut = by_use.get(by_use.len() - MAX_THUMBS * 3 / 4).copied().unwrap_or(0);
|
||||
self.entries.retain(|_, e| e.used >= cut);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The panels draw the rows of document `uid` (None: no document). When that is another
|
||||
/// document than before, the worker drops the jobs it has not started for every other
|
||||
/// document, so they don't hold up this one's thumbnails, and those rows are asked for again
|
||||
/// when their document shows again. The thumbnails of still-open documents stay.
|
||||
pub(super) fn show(&mut self, uid: Option<u64>) {
|
||||
if self.showing == uid {
|
||||
return;
|
||||
}
|
||||
self.showing = uid;
|
||||
self.pending.retain(|key, _| Some(key.0) == uid);
|
||||
if let Some(w) = &self.worker
|
||||
&& !w.discard(move |key| Some(key.0) != uid)
|
||||
{
|
||||
self.worker = None;
|
||||
self.pending.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the thumbnail `d` the worker finished.
|
||||
fn receive(&mut self, ctx: &egui::Context, d: Done<ThumbJob>) {
|
||||
let (key, node, px) = d.key;
|
||||
if self.open_docs.as_ref().is_some_and(|open| !open.contains(&key.0)) {
|
||||
return;
|
||||
}
|
||||
if self.pending.get(&key).is_some_and(|(p, ppx)| p.ptr_eq(&node) && *ppx == px) {
|
||||
self.pending.remove(&key);
|
||||
}
|
||||
self.upload(ctx, key, node, px, d.img.as_ref(), d.ms);
|
||||
}
|
||||
|
||||
/// The texture of row `n` (`px` pixels square) to draw: made or updated now, or on the
|
||||
/// worker (the old one is drawn meanwhile). Thumbnails shown stay during a drag and until
|
||||
/// the document settles.
|
||||
fn texture(&mut self, ctx: &egui::Context, src: &ThumbSource, n: &Arc<Node>, px: u32) -> Option<egui::TextureHandle> {
|
||||
if !self.worker_started {
|
||||
self.worker_started = true;
|
||||
self.worker = ThumbWorker::spawn(ctx, "thumbnails");
|
||||
}
|
||||
let done = match self.worker.as_ref().map(ThumbWorker::poll) {
|
||||
Some(Some(done)) => done,
|
||||
Some(None) => {
|
||||
// The thread is gone: render here from now on.
|
||||
self.worker = None;
|
||||
self.pending.clear();
|
||||
vec![]
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
for d in done {
|
||||
self.receive(ctx, d);
|
||||
}
|
||||
self.show(Some(src.uid));
|
||||
let key = (src.uid, n.id);
|
||||
let pass = ctx.cumulative_pass_nr();
|
||||
let (fresh, light) = match self.entries.get_mut(&key) {
|
||||
Some(e) => {
|
||||
e.used = pass;
|
||||
(std::ptr::eq(e.node.as_ptr(), Arc::as_ptr(n)) && e.px == px, Some(e.ms <= LIGHT_THUMB_MS))
|
||||
}
|
||||
None => (false, None),
|
||||
};
|
||||
let shown = self.entries.get(&key).and_then(|e| e.tex.clone());
|
||||
if fresh || self.pending.get(&key).is_some_and(|(p, ppx)| std::ptr::eq(p.as_ptr(), Arc::as_ptr(n)) && *ppx == px) {
|
||||
return shown;
|
||||
}
|
||||
if light.is_some() && (src.busy || !self.settle.settled(ctx, src.uid, src.revision, ctx.input(|i| i.time))) {
|
||||
return shown;
|
||||
}
|
||||
if self.spent.0 != pass {
|
||||
self.spent = (pass, 0.0, 0);
|
||||
}
|
||||
let in_budget = self.spent.1 < THUMB_BUDGET_MS && self.spent.2 < THUMB_BUDGET_COUNT;
|
||||
// A row drawn before is light when its last thumbnail was quick to render, unless its
|
||||
// object now has more anchors than the limit.
|
||||
let light = light_row(n, light, src.doc) && in_budget;
|
||||
if !light && let Some(w) = &self.worker {
|
||||
let (doc, node) = (src.doc.clone(), n.clone());
|
||||
let job: ThumbJob = (key, Arc::downgrade(n), px);
|
||||
if w.submit(key, job, Box::new(move |r| render_thumb(r, &doc, &node, px))) {
|
||||
self.pending.insert(key, (Arc::downgrade(n), px));
|
||||
return shown;
|
||||
}
|
||||
self.worker = None;
|
||||
self.pending.clear();
|
||||
}
|
||||
if !in_budget {
|
||||
ctx.request_repaint();
|
||||
return shown;
|
||||
}
|
||||
thread_local! {
|
||||
static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new());
|
||||
}
|
||||
let t0 = self.now_ms();
|
||||
let img = RENDERER.with(|r| render_thumb(&mut r.borrow_mut(), src.doc, n, px));
|
||||
let ms = self.now_ms() - t0;
|
||||
self.spent.1 += ms;
|
||||
self.spent.2 += 1;
|
||||
self.renders += 1;
|
||||
self.upload(ctx, key, Arc::downgrade(n), px, img.as_ref(), ms);
|
||||
self.entries.get(&key).and_then(|e| e.tex.clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// The Layers or Links panel shows the rows of document `uid` in this frame (None: no document
|
||||
/// is open), whether or not a thumbnail is drawn; see [`Thumbs::show`].
|
||||
pub(crate) fn show_thumbs_of(uid: Option<u64>) {
|
||||
THUMBS.with(|c| c.borrow_mut().show(uid));
|
||||
}
|
||||
|
||||
/// Forget thumbnails of documents no longer open, even if neither thumbnail panel is shown.
|
||||
pub(crate) fn retain_open_thumbs(uids: &[u64]) {
|
||||
THUMBS.with(|c| c.borrow_mut().retain_open(uids));
|
||||
}
|
||||
|
||||
/// A real rendered thumbnail of row `n`, cached by node identity (unchanged nodes keep their `Arc`
|
||||
/// allocation, so the address is a free change detector). Only rendered for visible rows; see
|
||||
/// [`Thumbs::texture`] for when.
|
||||
pub(crate) fn real_thumb(ui: &Ui, src: &ThumbSource, n: &Arc<Node>, r: egui::Rect) -> bool {
|
||||
if !ui.is_rect_visible(r) {
|
||||
return true;
|
||||
}
|
||||
let ppp = ui.ctx().pixels_per_point();
|
||||
let px = ((r.width() * ppp).round() as u32).max(8);
|
||||
match THUMBS.with(|c| c.borrow_mut().texture(ui.ctx(), src, n, px)) {
|
||||
Some(t) => {
|
||||
ui.painter().image(t.id(), r, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiny vector thumbnail painted with egui (fallback when rendering isn't possible). A node with
|
||||
/// more than [`LIGHT_THUMB_ANCHORS`] anchors, or that takes more than [`THUMB_COUNT_STEPS`] steps
|
||||
/// to count, paints nothing, since this runs on every frame and
|
||||
/// measuring its bounds takes time in proportion to its anchor count.
|
||||
pub(super) fn thumb(ui: &Ui, n: &Node, r: egui::Rect) {
|
||||
if !small_node(n, usize::MAX, LIGHT_THUMB_ANCHORS, false, None) {
|
||||
return;
|
||||
}
|
||||
let Some(b) = n.visual_bounds() else { return };
|
||||
let s = ((r.width() - 3.0) as f64 / b.width().max(b.height()).max(1e-6)) as f32;
|
||||
let off = r.center() - vec2(b.center().x as f32 * s, b.center().y as f32 * s);
|
||||
let p = ui.painter().with_clip_rect(r);
|
||||
let mut count = 0;
|
||||
n.walk(&mut |c| {
|
||||
if count > 40 {
|
||||
return;
|
||||
}
|
||||
if let Some(pd) = c.path_data() {
|
||||
count += 1;
|
||||
let col = c.appearance.fill_paint().color().or(c.appearance.stroke_paint().color()).map(|cc| {
|
||||
let [a, b2, d, _] = cc.to_rgba8(1.0);
|
||||
Color32::from_rgb(a, b2, d)
|
||||
});
|
||||
if let Some(bb) = pd.bounds() {
|
||||
let rr = egui::Rect::from_min_max(off + vec2(bb.x0 as f32 * s, bb.y0 as f32 * s), off + vec2(bb.x1 as f32 * s, bb.y1 as f32 * s));
|
||||
p.rect_filled(rr, 0.0, col.unwrap_or(Color32::from_gray(120)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use craft::host::queue::Cancel; // PLAN: assumed path of craft-host's `Cancel`
|
||||
use vectorcraft_color::{Color, Paint};
|
||||
use vectorcraft_doc::{Appearance, CharStyle, LayerColor, NodeKind, OpacityMask, TextKind, TextObject};
|
||||
use vectorcraft_geom::{Affine, Point, SubPath};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_finished_job_cannot_restore_a_closed_documents_thumbnail() {
|
||||
let mut thumbs = Thumbs::default();
|
||||
let ctx = egui::Context::default();
|
||||
thumbs.retain_open(&[2]);
|
||||
thumbs.receive(&ctx, Done { key: ((1, NodeId(1)), Weak::new(), 16), img: None, ms: 0.0 });
|
||||
assert!(thumbs.entries.is_empty(), "a closed document's late result is discarded");
|
||||
thumbs.receive(&ctx, Done { key: ((2, NodeId(2)), Weak::new(), 16), img: None, ms: 0.0 });
|
||||
assert!(thumbs.entries.contains_key(&(2, NodeId(2))), "an open document's result is kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closing_a_document_drops_the_image_its_running_job_finishes_while_the_panels_are_hidden() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
thumbs.retain_open(&[1, 2]);
|
||||
// A job of document 1 is running, so discarding the queue cannot drop it.
|
||||
let (started, running) = std::sync::mpsc::channel::<()>();
|
||||
let (release, held) = std::sync::mpsc::channel::<()>();
|
||||
let key = (1, NodeId(1));
|
||||
let job: crate::thumb_worker::JobFn = Box::new(move |_| {
|
||||
started.send(()).ok();
|
||||
held.recv().ok();
|
||||
None
|
||||
});
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job)));
|
||||
running.recv().expect("the job starts");
|
||||
// Another row of document 1 waits behind it.
|
||||
let queued = (1, NodeId(3));
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(queued, (queued, Weak::new(), 1), Box::new(|_| None))));
|
||||
// Document 1 closes while no panel collects results, then its running job finishes.
|
||||
thumbs.retain_open(&[2]);
|
||||
release.send(()).ok();
|
||||
// A job of document 2 queued after them comes back first: document 1's images were dropped.
|
||||
let next = (2, NodeId(2));
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(next, (next, Weak::new(), 1), Box::new(|_| None))));
|
||||
let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the same worker finishes document 2's job");
|
||||
assert_eq!(done.key.0, next, "no worker keeps the closed document's image");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_document_opened_while_a_job_runs_after_a_close_gets_its_thumbnails() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
thumbs.retain_open(&[1, 2]);
|
||||
// A job of document 2 is running.
|
||||
let (started, running) = std::sync::mpsc::channel::<()>();
|
||||
let (release, held) = std::sync::mpsc::channel::<()>();
|
||||
let blocker = (2, NodeId(1));
|
||||
let job: crate::thumb_worker::JobFn = Box::new(move |_| {
|
||||
started.send(()).ok();
|
||||
held.recv().ok();
|
||||
None
|
||||
});
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(blocker, (blocker, Weak::new(), 1), job)));
|
||||
running.recv().expect("the job starts");
|
||||
// Document 1 closes, then document 3 opens and one of its rows is queued.
|
||||
thumbs.retain_open(&[2]);
|
||||
thumbs.retain_open(&[2, 3]);
|
||||
let opened = (3, NodeId(2));
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(opened, (opened, Weak::new(), 1), Box::new(|_| None))));
|
||||
// A job of document 2 queued after it marks the end of the queue.
|
||||
let last = (2, NodeId(3));
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(last, (last, Weak::new(), 1), Box::new(|_| None))));
|
||||
release.send(()).ok();
|
||||
let worker = thumbs.worker.as_ref().expect("the worker is kept");
|
||||
let order: Vec<(u64, NodeId)> = (0..3).map_while(|_| worker.wait().map(|d| d.key.0)).take_while(|key| *key != last).collect();
|
||||
assert_eq!(order, [blocker, opened], "document 3's job comes back before the last one");
|
||||
}
|
||||
|
||||
/// An open zigzag of `anchors` anchors.
|
||||
fn line(anchors: usize) -> PathData {
|
||||
let pts: Vec<Point> = (0..anchors).map(|i| Point::new(i as f64 * 0.01, (i % 2) as f64 * 50.0)).collect();
|
||||
@@ -734,7 +476,7 @@ mod tests {
|
||||
assert!(small_in(&doc, &image(1, px / 100, 100)), "an image of as many pixels as the limit");
|
||||
assert!(!small_in(&doc, &image(1, px / 100, 101)), "a larger image");
|
||||
assert!(!small_in(&doc, &image(1, 4_000, 3_000)), "a photo");
|
||||
// Without the document only paths and frames count, as the painted thumbnail needs.
|
||||
// Without the document only paths and frames count.
|
||||
assert!(small(&glyphs(1, 5_000)) && small(&mesh(1, 100)) && small(&image(1, 4_000, 3_000)));
|
||||
}
|
||||
|
||||
@@ -834,29 +576,6 @@ mod tests {
|
||||
assert!(!small_in(&doc, &instance(1, &format!("Other {}", THUMB_COUNT_STEPS - 1))), "the last of many symbols");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_painted_thumbnail_leaves_out_a_long_path() {
|
||||
let ctx = egui::Context::default();
|
||||
let painted = |n: &Node| {
|
||||
let r = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), vec2(24.0, 24.0));
|
||||
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| thumb(ui, n, r));
|
||||
out.textures_delta.clear();
|
||||
out.shapes.len()
|
||||
};
|
||||
let none = painted(&Node::layer(NodeId(1), "Layer 1", LayerColor::Preset(0)));
|
||||
assert_eq!(painted(&rect(1)), none + 1, "a small path is painted");
|
||||
assert_eq!(painted(&path(1, LIGHT_THUMB_ANCHORS)), none + 1, "a path of as many anchors as the limit");
|
||||
assert_eq!(painted(&path(1, LIGHT_THUMB_ANCHORS + 1)), none, "a long path is not");
|
||||
// Type is not painted, so each holds a small path beside it: the group is painted only
|
||||
// while the type's frame or path keeps the anchors in all within the limit.
|
||||
let left = LIGHT_THUMB_ANCHORS - rect(2).path_data().map_or(0, PathData::anchor_count);
|
||||
let beside = |typ: Node| Node::group(NodeId(1), vec![Arc::new(rect(2)), Arc::new(typ)]);
|
||||
assert_eq!(painted(&beside(area_type(3, left))), none + 1, "area type whose frame keeps the group at the limit");
|
||||
assert_eq!(painted(&beside(area_type(3, left + 1))), none, "area type with a long frame");
|
||||
assert_eq!(painted(&beside(path_type(3, left))), none + 1, "type on a path that keeps the group at the limit");
|
||||
assert_eq!(painted(&beside(path_type(3, left + 1))), none, "type on a long path");
|
||||
}
|
||||
|
||||
/// A document with `n` on its layer, and `n` as the layer holds it.
|
||||
fn doc_with(n: impl FnOnce(NodeId) -> Node) -> (Arc<Document>, Arc<Node>) {
|
||||
let mut doc = Document::new(200.0, 200.0);
|
||||
@@ -868,196 +587,59 @@ mod tests {
|
||||
(doc, node)
|
||||
}
|
||||
|
||||
/// `n` of `doc` as `render` answers for a 24-point cell, weighed as a row not drawn before.
|
||||
fn rendered(doc: &Arc<Document>, n: &Arc<Node>, request: &ThumbRequest) -> ThumbRender {
|
||||
render(n.clone(), doc.clone(), request, light_row(n, None, doc))
|
||||
}
|
||||
|
||||
/// `render` gives a heavy node as a job, whose pixels are those `render_thumb` makes here.
|
||||
fn assert_job_matches_a_render_made_here(doc: &Arc<Document>, n: &Arc<Node>) {
|
||||
let request = ThumbRequest::for_cell(24.0, 1.0);
|
||||
let ThumbRender::Later(job) = rendered(doc, n, &request) else { panic!("a heavy node is made on a lane") };
|
||||
let Ok(LoadedPicture::Image(there)) = job(&Cancel::new()) else { panic!("the job draws the node") };
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, request.side).expect("this thread draws the node");
|
||||
let here = crate::canvas::color_image(&here);
|
||||
assert!(here.pixels.iter().any(|p| p.a() > 0), "the thumbnail shows the art");
|
||||
assert_eq!((there.size, &there.pixels), (here.size, &here.pixels), "the same pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_paths_thumbnail_is_made_on_the_worker_and_matches_one_made_here() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
let (doc, n) = doc_with(|id| path(id.0, 50_000));
|
||||
let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false };
|
||||
assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made");
|
||||
assert_eq!(thumbs.renders, 0, "not made on this thread");
|
||||
assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker");
|
||||
let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it");
|
||||
let there = done.img.as_ref().expect("the worker draws the path");
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the path");
|
||||
assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path");
|
||||
assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels");
|
||||
thumbs.receive(&ctx, done);
|
||||
assert!(thumbs.pending.is_empty());
|
||||
assert!(thumbs.texture(&ctx, &src, &n, 24).is_some(), "the worker's thumbnail is shown");
|
||||
assert_eq!(thumbs.renders, 0, "and not made again here");
|
||||
|
||||
// A small object's thumbnail is still made on this thread, at once.
|
||||
assert_job_matches_a_render_made_here(&doc, &n);
|
||||
// A small object's thumbnail is made on this thread, at once.
|
||||
let (doc, n) = doc_with(|id| rect(id.0));
|
||||
let src = ThumbSource { uid: 2, revision: 1, doc: &doc, busy: false };
|
||||
assert!(thumbs.texture(&ctx, &src, &n, 24).is_some());
|
||||
assert_eq!(thumbs.renders, 1);
|
||||
assert!(thumbs.pending.is_empty());
|
||||
}
|
||||
|
||||
/// A document of `rows` paths of 5,000 anchors on its layer, and the paths as the layer holds
|
||||
/// them.
|
||||
fn long_paths(rows: usize) -> (Arc<Document>, Vec<Arc<Node>>) {
|
||||
let mut doc = Document::new(200.0, 200.0);
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let ids: Vec<NodeId> = (0..rows)
|
||||
.map(|_| {
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(layer, usize::MAX, path(id.0, 5_000)).unwrap();
|
||||
id
|
||||
})
|
||||
.collect();
|
||||
let doc = Arc::new(doc);
|
||||
let nodes = ids.iter().filter_map(|id| node_arc(&doc, *id)).collect();
|
||||
(doc, nodes)
|
||||
}
|
||||
|
||||
/// Keep the worker of `thumbs` busy with a job of row (0, 0) until the sender returned sends,
|
||||
/// so the jobs submitted meanwhile wait in its queue.
|
||||
fn hold(thumbs: &Thumbs) -> std::sync::mpsc::Sender<()> {
|
||||
let (started, running) = std::sync::mpsc::channel::<()>();
|
||||
let (release, held) = std::sync::mpsc::channel::<()>();
|
||||
let key = (0, NodeId(0));
|
||||
let job: crate::thumb_worker::JobFn = Box::new(move |_| {
|
||||
started.send(()).ok();
|
||||
held.recv().ok();
|
||||
None
|
||||
});
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Weak::new(), 1), job)));
|
||||
running.recv().expect("the job starts");
|
||||
release
|
||||
}
|
||||
|
||||
/// The next job `thumbs`'s worker finishes, checked against the thumbnail of the same node in
|
||||
/// `rows` of `doc` made on this thread, then kept.
|
||||
fn receive_checked(ctx: &egui::Context, thumbs: &mut Thumbs, uid: u64, doc: &Document, rows: &[Arc<Node>]) {
|
||||
let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes a job");
|
||||
assert_eq!(done.key.0.0, uid, "a job of document {uid} is done next");
|
||||
let n = rows.iter().find(|n| n.id == done.key.0.1).expect("one of its rows");
|
||||
let there = done.img.as_ref().expect("the worker draws the path");
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), doc, n, 24).expect("this thread draws the path");
|
||||
assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the path");
|
||||
assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels");
|
||||
thumbs.receive(ctx, done);
|
||||
}
|
||||
|
||||
/// Prioritize the shown document’s thumbnails, requeue them when revisited, and retain cached rows.
|
||||
#[test]
|
||||
fn the_shown_documents_thumbnails_are_made_before_the_queued_ones_of_another() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
let (a, a_rows) = long_paths(3);
|
||||
let (b, b_rows) = long_paths(2);
|
||||
let release = hold(&thumbs);
|
||||
let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false };
|
||||
for n in &a_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none());
|
||||
}
|
||||
assert_eq!(thumbs.pending.len(), 3, "document 1's rows wait on the worker");
|
||||
// Document 2 shows before the worker gets to them.
|
||||
let src_b = ThumbSource { uid: 2, revision: 1, doc: &b, busy: false };
|
||||
for n in &b_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_b, n, 24).is_none());
|
||||
}
|
||||
assert_eq!(thumbs.pending.keys().map(|k| k.0).collect::<Vec<_>>(), [2, 2], "only the shown document's rows are pending");
|
||||
release.send(()).expect("the held job is waiting");
|
||||
let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes");
|
||||
assert_eq!(held.key.0, (0, NodeId(0)));
|
||||
for _ in &b_rows {
|
||||
receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows);
|
||||
}
|
||||
for n in &b_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some(), "the shown document's thumbnails are shown");
|
||||
}
|
||||
// Shown again, document 1's rows are asked for again and come back.
|
||||
// Hold the worker so texture() cannot collect a completed row before the count.
|
||||
let release = hold(&thumbs);
|
||||
for n in &a_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_a, n, 24).is_none());
|
||||
}
|
||||
assert_eq!(thumbs.pending.keys().filter(|k| k.0 == 1).count(), 3);
|
||||
release.send(()).expect("the held job is waiting");
|
||||
let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes");
|
||||
assert_eq!(held.key.0, (0, NodeId(0)));
|
||||
for _ in &a_rows {
|
||||
receive_checked(&ctx, &mut thumbs, 1, &a, &a_rows);
|
||||
}
|
||||
for n in &a_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_a, n, 24).is_some());
|
||||
}
|
||||
// Document 2's thumbnails were kept: showing it again asks for nothing.
|
||||
for n in &b_rows {
|
||||
assert!(thumbs.texture(&ctx, &src_b, n, 24).is_some());
|
||||
}
|
||||
assert!(thumbs.pending.is_empty());
|
||||
assert_eq!(thumbs.renders, 0, "none was made on this thread");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_queued_thumbnails_of_a_closed_document_are_dropped() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
let (a, a_rows) = long_paths(3);
|
||||
let release = hold(&thumbs);
|
||||
let src_a = ThumbSource { uid: 1, revision: 1, doc: &a, busy: false };
|
||||
for n in &a_rows {
|
||||
thumbs.texture(&ctx, &src_a, n, 24);
|
||||
}
|
||||
// The document closes and no other shows.
|
||||
thumbs.show(None);
|
||||
assert!(thumbs.pending.is_empty());
|
||||
// A job queued after it, straight on the worker, comes back next.
|
||||
let (b, b_rows) = long_paths(1);
|
||||
let (doc, node) = (b.clone(), b_rows[0].clone());
|
||||
let key = (2, node.id);
|
||||
let job: crate::thumb_worker::JobFn = Box::new(move |r| render_thumb(r, &doc, &node, 24));
|
||||
assert!(thumbs.worker.as_ref().is_some_and(|w| w.submit(key, (key, Arc::downgrade(&b_rows[0]), 24), job)));
|
||||
release.send(()).expect("the held job is waiting");
|
||||
let held = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the held job finishes");
|
||||
assert_eq!(held.key.0, (0, NodeId(0)));
|
||||
receive_checked(&ctx, &mut thumbs, 2, &b, &b_rows);
|
||||
let request = ThumbRequest::for_cell(24.0, 1.0);
|
||||
assert!(matches!(rendered(&doc, &n, &request), ThumbRender::Ready(_)));
|
||||
// A cancelled job gives no picture.
|
||||
let (doc, n) = doc_with(|id| path(id.0, 50_000));
|
||||
let ThumbRender::Later(job) = rendered(&doc, &n, &request) else { panic!("a long path is made on a lane") };
|
||||
let cancel = Cancel::new();
|
||||
cancel.cancel();
|
||||
assert!(job(&cancel).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_of_a_long_symbols_thumbnail_is_made_on_the_worker_and_matches_one_made_here() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
let mut doc = with_symbol("Long", path(900, 50_000));
|
||||
let layer = doc.layers.first().map(|l| l.id);
|
||||
let id = doc.alloc_id();
|
||||
doc.insert(layer, usize::MAX, instance(id.0, "Long")).unwrap();
|
||||
let doc = Arc::new(doc);
|
||||
let n = node_arc(&doc, id).unwrap();
|
||||
let src = ThumbSource { uid: 1, revision: 1, doc: &doc, busy: false };
|
||||
assert!(thumbs.texture(&ctx, &src, &n, 24).is_none(), "nothing is shown until it is made");
|
||||
assert_eq!(thumbs.renders, 0, "not made on this thread");
|
||||
assert!(thumbs.pending.contains_key(&(1, n.id)), "sent to the worker");
|
||||
let done = thumbs.worker.as_ref().and_then(ThumbWorker::wait).expect("the worker finishes it");
|
||||
let there = done.img.as_ref().expect("the worker draws the symbol");
|
||||
let here = render_thumb(&mut vectorcraft_render::Renderer::new(), &doc, &n, 24).expect("this thread draws the symbol");
|
||||
assert!(here.pixels.chunks(4).any(|p| p[3] > 0), "the thumbnail shows the symbol's art");
|
||||
assert_eq!((there.width, there.height, &there.pixels), (here.width, here.height, &here.pixels), "the same pixels");
|
||||
assert_job_matches_a_render_made_here(&doc, &n);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_row_whose_object_becomes_a_long_path_is_drawn_again_on_the_worker() {
|
||||
let ctx = egui::Context::default();
|
||||
let Some(worker) = ThumbWorker::start(&ctx, "test") else { return };
|
||||
let mut thumbs = Thumbs { worker: Some(worker), worker_started: true, ..Default::default() };
|
||||
let (doc, n) = doc_with(|id| path(id.0, 50_000));
|
||||
let key = (1, n.id);
|
||||
// The row's last thumbnail showed a small object and took no time to render.
|
||||
let before = Arc::new(rect(n.id.0));
|
||||
thumbs.upload(&ctx, key, Arc::downgrade(&before), 24, None, 0.0);
|
||||
let src = ThumbSource { uid: 1, revision: 2, doc: &doc, busy: false };
|
||||
// The document reached this revision long before now, so it has settled.
|
||||
thumbs.settle.settled(&ctx, 1, 2, f64::NEG_INFINITY);
|
||||
thumbs.texture(&ctx, &src, &n, 24);
|
||||
assert_eq!(thumbs.renders, 0, "not made on this thread");
|
||||
assert!(thumbs.pending.contains_key(&key), "sent to the worker");
|
||||
let request = ThumbRequest::for_cell(24.0, 1.0);
|
||||
let (doc, small_node) = doc_with(|id| rect(id.0));
|
||||
let (long_doc, long_node) = doc_with(|id| path(id.0, 50_000));
|
||||
let key = NodeThumb { uid: 1, node: small_node.id };
|
||||
let before = NodeThumbs::new(&doc, |_| Some(small_node.clone()));
|
||||
let after = NodeThumbs::new(&long_doc, |_| Some(long_node.clone()));
|
||||
assert_ne!(before.revision(&key, &request), after.revision(&key, &request), "a changed node is a new picture");
|
||||
assert!(matches!(before.render(&key, &request), ThumbRender::Ready(_)));
|
||||
assert!(matches!(after.render(&key, &request), ThumbRender::Later(_)), "and a long path is made on a lane");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user