Skip to content

VectorCraft: An open-source, vector art tool written by scratch in pure Rust

Layers: the panel filters its rows by object kind, lock and visibility

dotCooCoo29eb4903816a
diff --git a/ASSETS.md b/ASSETS.md
index 11e5602ea..e51b5e54f 100644
--- a/ASSETS.md
+++ b/ASSETS.md
@@ -134,6 +134,7 @@ Generated-in-code art is original and has no file to list. This covers the defau
| `assets/icons/dc-draw-normal.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-ellipse.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-fill-none.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
+| `assets/icons/dc-filter.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-flare.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-folder.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
| `assets/icons/dc-free-transform.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | |
diff --git a/assets/icons/dc-filter.svg b/assets/icons/dc-filter.svg
new file mode 100644
index 000000000..b359ca9a1
--- /dev/null
+++ b/assets/icons/dc-filter.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt" stroke-linejoin="miter"><path d="M4 5H20L14 12.5V18.5L10 20V12.5Z" stroke-width="1.5" /></svg>
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv
index 5b9aa8f3f..f9923e337 100644
--- a/crates/ui-egui/src/i18n/cs.tsv
+++ b/crates/ui-egui/src/i18n/cs.tsv
@@ -1501,6 +1501,17 @@ lighting Light Světlo
Create New Layer Vytvořit novou vrstvu
Create New Sublayer Vytvořit novou podvrstvu
Search All Hledat ve všem
+ Filter Filtr
+ Clear All Smazat vše
+ By Object Podle objektu
+ By Layer Podle vrstvy
+ Images Obrazy
+ Groups Skupiny
+ Linked Files Propojené soubory
+ Locked Zamčené
+ Hidden Skryté
+ Filter Layers Panel Rows Filtrovat řádky panelu Vrstvy
+@msg `{key}` must be an array of these names: {_1} `{key}` musí být pole těchto názvů: {_1}
Graphics Grafika
Local Libraries Místní knihovny
Add Content Přidat obsah
diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv
index 8e8f3969f..1b6e23e5b 100644
--- a/crates/ui-egui/src/i18n/de.tsv
+++ b/crates/ui-egui/src/i18n/de.tsv
@@ -2558,6 +2558,17 @@
Scripts Skripte
Search Suchen
Search All Alle durchsuchen
+ Filter Filter
+ Clear All Alle aufheben
+ By Object Nach Objekt
+ By Layer Nach Ebene
+ Images Bilder
+ Groups Gruppen
+ Linked Files Verknüpfte Dateien
+ Locked Gesperrt
+ Hidden Ausgeblendet
+ Filter Layers Panel Rows Zeilen im Ebenenbedienfeld filtern
+@msg `{key}` must be an array of these names: {_1} `{key}` muss ein Array mit diesen Namen sein: {_1}
Search commands and tools Befehle und Werkzeuge suchen
Search commands and tools… Befehle und Werkzeuge suchen…
Search Commands… Befehle suchen…
diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv
index e2d2fa0c8..f02f9a599 100644
--- a/crates/ui-egui/src/i18n/es.tsv
+++ b/crates/ui-egui/src/i18n/es.tsv
@@ -2606,6 +2606,17 @@
Scripts Scripts
Search Buscar
Search All Buscar en todo
+ Filter Filtro
+ Clear All Borrar todo
+ By Object Por objeto
+ By Layer Por capa
+ Images Imágenes
+ Groups Grupos
+ Linked Files Archivos vinculados
+ Locked Bloqueados
+ Hidden Ocultos
+ Filter Layers Panel Rows Filtrar filas del panel Capas
+@msg `{key}` must be an array of these names: {_1} `{key}` debe ser una lista de estos nombres: {_1}
Search commands and tools Buscar comandos y herramientas
Search commands and tools… Buscar comandos y herramientas…
Search Commands… Buscar comandos…
diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv
index 042023805..21faea1a5 100644
--- a/crates/ui-egui/src/i18n/fr.tsv
+++ b/crates/ui-egui/src/i18n/fr.tsv
@@ -2603,6 +2603,17 @@
Scripts Scripts
Search Rechercher
Search All Rechercher partout
+ Filter Filtre
+ Clear All Tout effacer
+ By Object Par objet
+ By Layer Par calque
+ Images Images
+ Groups Groupes
+ Linked Files Fichiers liés
+ Locked Verrouillés
+ Hidden Masqués
+ Filter Layers Panel Rows Filtrer les lignes du panneau Calques
+@msg `{key}` must be an array of these names: {_1} `{key}` doit être un tableau de noms parmi {_1}
Search commands and tools Chercher commandes et outils
Search commands and tools… Chercher commandes et outils…
Search Commands… Rechercher des commandes…
diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv
index 45ed86225..16a06c84c 100644
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@ -3159,6 +3159,17 @@
Scrub Numeric Fields by Dragging Számmezők állítása húzással
Search Keresés
Search All Keresés mindenben
+ Filter Szűrő
+ Clear All Összes törlése
+ By Object Objektum szerint
+ By Layer Réteg szerint
+ Images Képek
+ Groups Csoportok
+ Linked Files Csatolt fájlok
+ Locked Zárolt
+ Hidden Rejtett
+ Filter Layers Panel Rows Rétegek panel sorainak szűrése
+@msg `{key}` must be an array of these names: {_1} `{key}`: ezen nevek tömbje kell: {_1}
Search commands and tools Parancsok és eszközök keresése
Search commands and tools… Parancsok és eszközök keresése…
Search Commands… Parancsok keresése…
diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv
index 773b2c9ee..821b85d1b 100644
--- a/crates/ui-egui/src/i18n/it.tsv
+++ b/crates/ui-egui/src/i18n/it.tsv
@@ -2609,6 +2609,17 @@
Scripts Script
Search Cerca
Search All Cerca ovunque
+ Filter Filtro
+ Clear All Cancella tutto
+ By Object Per oggetto
+ By Layer Per livello
+ Images Immagini
+ Groups Gruppi
+ Linked Files File collegati
+ Locked Bloccati
+ Hidden Nascosti
+ Filter Layers Panel Rows Filtra righe del pannello Livelli
+@msg `{key}` must be an array of these names: {_1} `{key}` deve essere un array di questi nomi: {_1}
Search commands and tools Cerca comandi e strumenti
Search commands and tools… Cerca comandi e strumenti…
Search Commands… Cerca comandi…
diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv
index 608ca5ab3..a5d460dd3 100644
--- a/crates/ui-egui/src/i18n/ja.tsv
+++ b/crates/ui-egui/src/i18n/ja.tsv
@@ -2482,6 +2482,17 @@
Screen スクリーン
Screens スクリーン
Search All すべてを検索
+ Filter フィルター
+ Clear All すべてクリア
+ By Object オブジェクト別
+ By Layer レイヤー別
+ Images 画像
+ Groups グループ
+ Linked Files リンクファイル
+ Locked ロック
+ Hidden 非表示
+ Filter Layers Panel Rows レイヤーパネルの行をフィルター
+@msg `{key}` must be an array of these names: {_1} `{key}` には {_1} の中の名前の配列を指定してください
Search commands and tools コマンドとツールを検索
Search commands and tools… コマンドとツールを検索…
Secondary セカンダリ
diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv
index 98ebee7e4..869b18dc5 100644
--- a/crates/ui-egui/src/i18n/ko.tsv
+++ b/crates/ui-egui/src/i18n/ko.tsv
@@ -2476,6 +2476,17 @@
Screen 스크린
Screens 화면
Search All 모두 검색
+ Filter 필터
+ Clear All 모두 지우기
+ By Object 개체별
+ By Layer 레이어별
+ Images 이미지
+ Groups 그룹
+ Linked Files 연결된 파일
+ Locked 잠김
+ Hidden 숨김
+ Filter Layers Panel Rows 레이어 패널 행 필터링
+@msg `{key}` must be an array of these names: {_1} `{key}`은(는) 다음 이름의 배열이어야 합니다: {_1}
Search commands and tools 명령 및 도구 검색
Search commands and tools… 명령 및 도구 검색…
Secondary 보조
diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv
index f7c59945d..a56342b50 100644
--- a/crates/ui-egui/src/i18n/pl.tsv
+++ b/crates/ui-egui/src/i18n/pl.tsv
@@ -1414,6 +1414,17 @@ lighting Light Światło
Create New Layer Utwórz nową warstwę
Create New Sublayer Utwórz nową podwarstwę
Search All Szukaj wszędzie
+ Filter Filtr
+ Clear All Wyczyść wszystko
+ By Object Według obiektu
+ By Layer Według warstwy
+ Images Obrazy
+ Groups Grupy
+ Linked Files Połączone pliki
+ Locked Zablokowane
+ Hidden Ukryte
+ Filter Layers Panel Rows Filtruj wiersze panelu Warstwy
+@msg `{key}` must be an array of these names: {_1} `{key}` musi być tablicą tych nazw: {_1}
Graphics Grafiki
Local Libraries Biblioteki lokalne
Add Content Dodaj zawartość
diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv
index d98968075..1b245d942 100644
--- a/crates/ui-egui/src/i18n/pt-br.tsv
+++ b/crates/ui-egui/src/i18n/pt-br.tsv
@@ -2139,6 +2139,17 @@
Scribble… Rabisco…
Scripts Scripts
Search All Pesquisar em Tudo
+ Filter Filtro
+ Clear All Limpar Tudo
+ By Object Por Objeto
+ By Layer Por Camada
+ Images Imagens
+ Groups Grupos
+ Linked Files Arquivos Vinculados
+ Locked Bloqueados
+ Hidden Ocultos
+ Filter Layers Panel Rows Filtrar linhas do painel Camadas
+@msg `{key}` must be an array of these names: {_1} `{key}` deve ser uma matriz destes nomes: {_1}
Search Commands… Pesquisar Comandos…
Search commands and tools Pesquisar comandos e ferramentas
Search commands and tools… Pesquisar comandos e ferramentas…
diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv
index ca113bb98..162c998e0 100644
--- a/crates/ui-egui/src/i18n/ru.tsv
+++ b/crates/ui-egui/src/i18n/ru.tsv
@@ -2605,6 +2605,17 @@
Scripts Сценарии
Search Поиск
Search All Искать везде
+ Filter Фильтр
+ Clear All Очистить всё
+ By Object По объектам
+ By Layer По слоям
+ Images Изображения
+ Groups Группы
+ Linked Files Связанные файлы
+ Locked Заблокированные
+ Hidden Скрытые
+ Filter Layers Panel Rows Фильтровать строки панели «Слои»
+@msg `{key}` must be an array of these names: {_1} `{key}` должно быть массивом из этих имён: {_1}
Search commands and tools Поиск команд и инструментов
Search commands and tools… Поиск команд и инструментов…
Search Commands… Поиск команд…
diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv
index 72a9ca3ce..76c5f5973 100644
--- a/crates/ui-egui/src/i18n/uk.tsv
+++ b/crates/ui-egui/src/i18n/uk.tsv
@@ -2601,6 +2601,17 @@
Scripts Сценарії
Search Пошук
Search All Шукати скрізь
+ Filter Фільтр
+ Clear All Очистити все
+ By Object За об’єктами
+ By Layer За шарами
+ Images Зображення
+ Groups Групи
+ Linked Files Пов’язані файли
+ Locked Заблоковані
+ Hidden Приховані
+ Filter Layers Panel Rows Фільтрувати рядки панелі «Шари»
+@msg `{key}` must be an array of these names: {_1} `{key}` має бути масивом цих назв: {_1}
Search commands and tools Пошук команд та інструментів
Search commands and tools… Пошук команд та інструментів…
Search Commands… Пошук команд…
diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv
index 3093a360c..ee105f278 100644
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@ -2892,6 +2892,17 @@
Scrub Numeric Fields by Dragging Cuộn nhanh trường số bằng cách kéo
Search Tìm kiếm
Search All Tìm kiếm tất cả
+ Filter Bộ lọc
+ Clear All Xóa tất cả
+ By Object Theo đối tượng
+ By Layer Theo lớp
+ Images Hình ảnh
+ Groups Nhóm
+ Linked Files Tệp được liên kết
+ Locked Đã khóa
+ Hidden Đã ẩn
+ Filter Layers Panel Rows Lọc hàng bảng Lớp
+@msg `{key}` must be an array of these names: {_1} `{key}` phải là một mảng gồm các tên sau: {_1}
Search commands and tools Tìm kiếm lệnh và công cụ
Search commands and tools… Tìm kiếm lệnh và công cụ…
Search Commands… Tìm kiếm lệnh…
diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv
index 137af1836..f551b280e 100644
--- a/crates/ui-egui/src/i18n/zh-hans.tsv
+++ b/crates/ui-egui/src/i18n/zh-hans.tsv
@@ -2462,6 +2462,16 @@
Scripts 脚本
Search 搜索
Search All 搜索全部
+ Filter 筛选
+ Clear All 全部清除
+ By Object 按对象
+ By Layer 按图层
+ Images 图像
+ Groups 编组
+ Linked Files 链接文件
+ Locked 已锁定
+ Hidden 已隐藏
+ Filter Layers Panel Rows 筛选图层面板行
Search commands and tools 搜索命令和工具
Search commands and tools… 搜索命令和工具…
Search Commands… 搜索命令…
diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv
index 7dd826cdc..f3616068a 100644
--- a/crates/ui-egui/src/i18n/zh-hant.tsv
+++ b/crates/ui-egui/src/i18n/zh-hant.tsv
@@ -2587,6 +2587,16 @@
Scripts 指令碼
Search 搜尋
Search All 搜尋全部
+ Filter 篩選
+ Clear All 全部清除
+ By Object 依物件
+ By Layer 依圖層
+ Images 影像
+ Groups 群組
+ Linked Files 連結檔案
+ Locked 已鎖定
+ Hidden 已隱藏
+ Filter Layers Panel Rows 篩選圖層面板列
Search commands and tools 搜尋指令與工具
Search commands and tools… 搜尋指令與工具…
Search Commands… 搜尋指令…
diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs
index 7f4022b4c..ac6274e70 100644
--- a/crates/ui-egui/src/icon_data.rs
+++ b/crates/ui-egui/src/icon_data.rs
@@ -82,6 +82,7 @@ pub static ICONS: &[(&str, &[u8])] = &[
("dc-draw-normal", include_bytes!("../../../assets/icons/dc-draw-normal.svg")),
("dc-ellipse", include_bytes!("../../../assets/icons/dc-ellipse.svg")),
("dc-fill-none", include_bytes!("../../../assets/icons/dc-fill-none.svg")),
+ ("dc-filter", include_bytes!("../../../assets/icons/dc-filter.svg")),
("dc-flare", include_bytes!("../../../assets/icons/dc-flare.svg")),
("dc-folder", include_bytes!("../../../assets/icons/dc-folder.svg")),
("dc-free-transform", include_bytes!("../../../assets/icons/dc-free-transform.svg")),
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index cc9e5b8c1..5ec65a377 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -527,6 +527,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"",
"{ids?: [id…] (default: every row that holds others), open?: bool (default true)} open or close rows of the Layers panel, as clicking their triangles does → {count}",
),
+ (
+ "ui.layersFilter",
+ "Filter Layers Panel Rows",
+ "",
+ "{objects?: [paths|shapes|text|images|effects|groups|linkedFiles|guides], layers?: [locked|hidden]} set the Layers panel's Filter (By Object, By Layer): a row stays when it is of a kind in `objects` and in a state in `layers` (its own lock or eye; an empty list takes every row), or when a row inside it stays; Search All narrows the rows further. A key left out keeps its list. The filter lasts the session and does not change the document, its open rows or the selection → {objects, layers}",
+ ),
(
"ui.tileEdgeColor",
"Tile Edge Color…",
@@ -1417,6 +1423,7 @@ pub fn run_ui_command(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<R
"ui.newLayer" => crate::dialogs::layer_options::open_new(app, p),
"ui.layersPanelOptions" => crate::dialogs::layers_panel_options::open(app),
"ui.layersExpand" => crate::panels::layers::expand(app, p),
+ "ui.layersFilter" => crate::panels::layers::set_filter(app, p),
"ui.flattenTransparencyDialog" => {
crate::dialogs::flatten::open(app);
Ok(Value::Null)
diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs
index 95d35ff5d..8f163c067 100644
--- a/crates/ui-egui/src/panels/layers.rs
+++ b/crates/ui-egui/src/panels/layers.rs
@@ -24,6 +24,11 @@
//! - A target circle targets its layer, group or object (`layer.target`); dragging it onto another
//! row's circle moves the appearance there (Alt copies it, `appearance.transfer`) and dropping it
//! on the trash clears it.
+//! - Search All and the Filter button at its right (`ui.layersFilter`, lit while a filter is on)
+//! narrow the rows, and every row that holds others shows open while they do. A row stays when
+//! its name holds the text typed, it is one of the object kinds ticked under By Object and it is
+//! in one of the states ticked under By Layer (a section with nothing ticked takes every row), or
+//! when a row inside it stays. Neither changes the document, its open rows or the selection.
//!
//! While an opacity mask is edited the panel lists only its art, under an `<Opacity Mask>` entry.
//!
@@ -38,7 +43,7 @@ use std::sync::{Arc, Weak};
use egui::{Color32, Sense, Stroke, StrokeKind, Ui, vec2};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
-use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
+use vectorcraft_doc::{Document, LiveShape, Node, NodeId, NodeKind};
use vectorcraft_engine::OpenRows;
use crate::theme::Tokens;
@@ -232,6 +237,149 @@ struct Row {
guide: Option<usize>,
}
+/// An object kind under the Filter's By Object (`ui.layersFilter`'s `objects`).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum ObjectKind {
+ Paths,
+ Shapes,
+ Text,
+ Images,
+ Effects,
+ Groups,
+ LinkedFiles,
+ Guides,
+}
+
+impl ObjectKind {
+ /// Every kind with its parameter name, in the popup's order.
+ pub const ALL: [(Self, &'static str); 8] = [
+ (Self::Paths, "paths"),
+ (Self::Shapes, "shapes"),
+ (Self::Text, "text"),
+ (Self::Images, "images"),
+ (Self::Effects, "effects"),
+ (Self::Groups, "groups"),
+ (Self::LinkedFiles, "linkedFiles"),
+ (Self::Guides, "guides"),
+ ];
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::Paths => tl!("Paths"),
+ Self::Shapes => tl!("Shapes"),
+ Self::Text => tl!("Text"),
+ Self::Images => tl!("Images"),
+ Self::Effects => tl!("Effects"),
+ Self::Groups => tl!("Groups"),
+ Self::LinkedFiles => tl!("Linked Files"),
+ Self::Guides => tl!("Guides"),
+ }
+ }
+
+ /// Whether `n`'s row is of this kind. Paths take plain paths, the paths whose corners Live
+ /// Corners cut and compound paths; Shapes take live rectangles, ellipses, polygons and lines;
+ /// Paths and Shapes leave out paths made into guides. Effects take a row with an effect, shown
+ /// or hidden, on itself or on one of its fills or strokes. Linked Files take linked images and
+ /// placed documents.
+ fn takes(self, n: &Node) -> bool {
+ match (self, &n.kind) {
+ (Self::Guides, NodeKind::Path { guide, .. }) => *guide,
+ (Self::Paths | Self::Shapes, NodeKind::Path { guide: true, .. }) => false,
+ (Self::Paths, NodeKind::Path { live, .. }) => live.as_deref().is_none_or(|l| matches!(l, LiveShape::Path { .. })),
+ (Self::Shapes, NodeKind::Path { live, .. }) => live.as_deref().is_some_and(|l| !matches!(l, LiveShape::Path { .. })),
+ (Self::Paths, NodeKind::Compound { .. })
+ | (Self::Text, NodeKind::Text(_))
+ | (Self::Images, NodeKind::Image(_))
+ | (Self::Groups, NodeKind::Group { .. })
+ | (Self::LinkedFiles, NodeKind::PlacedDocument(_)) => true,
+ (Self::LinkedFiles, NodeKind::Image(im)) => im.link.is_some(),
+ (Self::Effects, _) => !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()),
+ _ => false,
+ }
+ }
+}
+
+/// A row state under the Filter's By Layer (`ui.layersFilter`'s `layers`): the row's own lock or
+/// eye, as its lock and eye columns show them.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum RowState {
+ Locked,
+ Hidden,
+}
+
+impl RowState {
+ /// Every state with its parameter name, in the popup's order.
+ pub const ALL: [(Self, &'static str); 2] = [(Self::Locked, "locked"), (Self::Hidden, "hidden")];
+
+ fn label(self) -> &'static str {
+ match self {
+ Self::Locked => tl!("Locked"),
+ Self::Hidden => tl!("Hidden"),
+ }
+ }
+
+ fn takes(self, n: &Node) -> bool {
+ match self {
+ Self::Locked => n.locked,
+ Self::Hidden => !n.visible,
+ }
+ }
+}
+
+/// The Layers panel's Filter (`ui.layersFilter`): the object kinds ticked under By Object and the
+/// row states ticked under By Layer, each in the popup's order. A section with nothing ticked takes
+/// every row.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct Filter {
+ pub objects: Vec<ObjectKind>,
+ pub layers: Vec<RowState>,
+}
+
+impl Filter {
+ /// Whether anything is ticked.
+ pub fn is_on(&self) -> bool {
+ !self.objects.is_empty() || !self.layers.is_empty()
+ }
+
+ /// Whether `n`'s row is of a ticked kind and in a ticked state.
+ fn keeps(&self, n: &Node) -> bool {
+ (self.objects.is_empty() || self.objects.iter().any(|k| k.takes(n))) && (self.layers.is_empty() || self.layers.iter().any(|s| s.takes(n)))
+ }
+
+ /// Whether the ruler guide rows stay: with no filter on, or with Guides ticked and no row state
+ /// ticked.
+ fn keeps_guides(&self) -> bool {
+ !self.is_on() || (self.objects.contains(&ObjectKind::Guides) && self.layers.is_empty())
+ }
+}
+
+/// The parameter names of the ones of `all` in `on`, in `all`'s order.
+fn names<T: Copy + PartialEq>(all: &[(T, &'static str)], on: &[T]) -> Vec<&'static str> {
+ all.iter().filter(|(t, _)| on.contains(t)).map(|(_, name)| *name).collect()
+}
+
+/// The parameter names of `on` with `t` added, or taken out when it is in `on`.
+fn toggled<T: Copy + PartialEq>(all: &[(T, &'static str)], on: &[T], t: T) -> Vec<&'static str> {
+ all.iter().filter(|(x, _)| if *x == t { !on.contains(x) } else { on.contains(x) }).map(|(_, name)| *name).collect()
+}
+
+/// The list `key` of `p` read by the parameter names of `all`, in `all`'s order: `None` when `p`
+/// leaves it out or sets it to null, and an error when it is anything other than an array of
+/// those names.
+fn parse_names<T: Copy + PartialEq>(p: &Value, key: &str, all: &[(T, &'static str)]) -> Result<Option<Vec<T>>, String> {
+ let given = match p.get(key) {
+ None | Some(Value::Null) => return Ok(None),
+ Some(v) => v
+ .as_array()
+ .and_then(|a| a.iter().map(|name| all.iter().find(|(_, n)| Some(*n) == name.as_str()).map(|(t, _)| *t)).collect::<Option<Vec<T>>>()),
+ };
+ let Some(given) = given else {
+ let names: Vec<&str> = all.iter().map(|(_, n)| *n).collect();
+ return Err(format!("`{key}` must be an array of these names: {}", names.join(", ")));
+ };
+ Ok(Some(all.iter().map(|(t, _)| *t).filter(|t| given.contains(t)).collect()))
+}
+
/// What the rows were listed from: listed again when any of it changes.
#[derive(Clone, PartialEq)]
struct RowsKey {
@@ -240,16 +388,17 @@ struct RowsKey {
open: u64,
layers_only: bool,
query: String,
+ filter: Filter,
}
/// The rows the panel shows, top down: the layers (only the opacity mask's while one is edited)
-/// with the rows of the open ones inside them. A search shows every row whose name, or the name of
-/// anything inside it, contains `query` (lowercase).
-fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str) -> Vec<Row> {
+/// with the rows of the open ones inside them. A search or a filter shows every row whose name
+/// contains `query` (lowercase) and that `filter` keeps, and every row holding one.
+fn list_rows(doc: &Document, open: &OpenRows, opts: &PanelOptions, query: &str, filter: &Filter) -> Vec<Row> {
let mask_layer = doc.mask_edit.map(|m| m.layer);
let mut out = vec![];
for l in doc.layers.iter().rev().filter(|l| mask_layer.is_none_or(|m| m == l.id)) {
- push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query, doc), &mut out);
+ push_rows(l, 0, false, (Color32::PLACEHOLDER, true), (open, opts, query, filter, doc), &mut out);
}
out
}
@@ -261,10 +410,10 @@ fn push_rows(
depth: usize,
clip_path: bool,
(colour, shown): (Color32, bool),
- cx: (&OpenRows, &PanelOptions, &str, &Document),
+ cx: (&OpenRows, &PanelOptions, &str, &Filter, &Document),
out: &mut Vec<Row>,
) {
- let (open_rows, opts, query, doc) = cx;
+ let (open_rows, opts, query, filter, doc) = cx;
if opts.layers_only && !n.is_layer() {
return;
}
@@ -277,10 +426,13 @@ fn push_rows(
};
let shown = shown && n.visible;
let searching = !query.is_empty();
- // A layer's ruler guides are rows in it, above its art (not while searching).
- let guides: Vec<usize> = if n.is_layer() && !opts.layers_only && !searching { doc.guides_on(n.id).map(|(i, _)| i).collect() } else { vec![] };
+ let narrowing = searching || filter.is_on();
+ // A layer's ruler guides are rows in it, above its art (not while searching, nor while the
+ // filter leaves them out).
+ let guides: Vec<usize> =
+ if n.is_layer() && !opts.layers_only && !searching && filter.keeps_guides() { doc.guides_on(n.id).map(|(i, _)| i).collect() } else { vec![] };
let opens = opens(n, opts) || !guides.is_empty();
- let open = opens && (searching || open_rows.contains(n.id));
+ let open = opens && (narrowing || open_rows.contains(n.id));
let at = out.len();
out.push(Row { node: n.clone(), depth, clip_path, opens, open, colour, dim: !shown || n.is_template(), guide: None });
if open {
@@ -293,24 +445,31 @@ fn push_rows(
push_rows(c, depth + 1, i == 0 && n.clips(), (colour, shown), cx, out);
}
}
- // Searching, a row stays for its own name or for a row it keeps inside it.
- if searching && out.len() == at + 1 && !n.display_name().to_lowercase().contains(query) {
+ // Searching or filtering, a row stays for a match of its own (its name holds the search text
+ // and the filter keeps it) or for a row it keeps inside it.
+ if narrowing && out.len() == at + 1 && !(filter.keeps(n) && (!searching || n.display_name().to_lowercase().contains(query))) {
out.truncate(at);
}
}
/// The rows of the active document as [`list_rows`] lists them, listed again only when the
-/// document, its open rows, the search or Show Layers Only changed.
-fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str) -> Arc<Vec<Row>> {
- let now =
- RowsKey { uid: st.uid, revision: st.revision, open: st.layers_open.generation(), layers_only: opts.layers_only, query: query.to_string() };
+/// document, its open rows, the search, the filter or Show Layers Only changed.
+fn rows_of_doc(ui: &Ui, st: &vectorcraft_engine::DocState, opts: &PanelOptions, query: &str, filter: &Filter) -> Arc<Vec<Row>> {
+ let now = RowsKey {
+ uid: st.uid,
+ revision: st.revision,
+ open: st.layers_open.generation(),
+ layers_only: opts.layers_only,
+ query: query.to_string(),
+ filter: filter.clone(),
+ };
let id = key("rows");
if let Some((was, rows)) = ui.data(|d| d.get_temp::<(RowsKey, Arc<Vec<Row>>)>(id))
&& was == now
{
return rows;
}
- let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query));
+ let rows = Arc::new(list_rows(&st.doc, &st.layers_open, opts, query, filter));
ui.data_mut(|d| d.insert_temp(id, (now, rows.clone())));
rows
}
@@ -379,9 +538,20 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
reveal = rows.first().copied();
ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone()));
}
- let query = crate::widgets::search_field(ui, egui::Id::new("layers-search"), tl!("Search All")).trim().to_lowercase();
+ // Search All, and the Filter button at its right.
+ let query = ui
+ .horizontal(|ui| {
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ filter_button(app, ui);
+ crate::widgets::search_field(ui, egui::Id::new("layers-search"), tl!("Search All"))
+ })
+ .inner
+ })
+ .inner
+ .trim()
+ .to_lowercase();
let Some(st) = app.session.active() else { return };
- let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query);
+ let list = rows_of_doc(ui, st, &app.ui.layers_panel, &query, &app.ui.layers_filter);
let view = View {
doc: &doc,
thumbs: ThumbSource::of(app, st, &doc),
@@ -469,6 +639,39 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
+/// 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.
+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| {
+ 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();
+ }
+}
+
/// The bottom bar: the layer count and the panel's buttons.
fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc: &Document, actions: &mut Vec<(String, Value)>) {
let t = &view.t;
@@ -1337,6 +1540,24 @@ pub fn expand(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
Ok(json!({ "count": ids.len() }))
}
+/// `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.
+/// → {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;
+ if let Some(objects) = objects {
+ f.objects = objects;
+ }
+ if let Some(layers) = layers {
+ f.layers = layers;
+ }
+ Ok(json!({"objects": names(&ObjectKind::ALL, &f.objects), "layers": names(&RowState::ALL, &f.layers)}))
+}
+
#[cfg(test)]
mod tests {
use serde_json::json;
@@ -1925,6 +2146,215 @@ mod tests {
let _ = (layer, sub);
}
+ // ---- Search All and the Filter ----
+
+ /// Layer 1 holding a path, a rectangle, type reading "Sky line", a group of an ellipse with an
+ /// effect, a compound path, a guide, an embedded and a linked image and a ruler guide, and on top
+ /// a sublayer "Sub" holding a hidden path named "Sky" and a locked path; only Layer 1 open and
+ /// nothing selected → (app, the rows' ids by name).
+ fn kinds() -> (VectorcraftApp, HashMap<&'static str, NodeId>) {
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ let run = |app: &mut VectorcraftApp, id: &str, p: serde_json::Value| app.session.execute(id, &p).unwrap();
+ let id = |v: serde_json::Value| NodeId(v["id"].as_u64().unwrap());
+ let star = |app: &mut VectorcraftApp, x: u32| id(run(app, "shape.star", json!({"cx": x, "cy": 50, "radius1": 20, "radius2": 10})));
+ run(&mut app, "file.new", json!({"width": 400, "height": 400}));
+ let mut ids = HashMap::from([("layer", app.session.active().unwrap().doc.layers[0].id)]);
+ ids.insert("path", star(&mut app, 50));
+ ids.insert("rect", id(run(&mut app, "shape.rectangle", json!({"x": 0, "y": 100, "width": 20, "height": 20}))));
+ ids.insert("text", id(run(&mut app, "text.create", json!({"x": 10, "y": 200, "text": "Sky line"}))));
+ let ellipse = id(run(&mut app, "shape.ellipse", json!({"x": 100, "y": 100, "width": 20, "height": 20})));
+ run(&mut app, "effect.apply", json!({"effect": "distort.twist", "ids": [ellipse.0]}));
+ run(&mut app, "select.set", json!({"ids": [ellipse.0]}));
+ ids.insert("group", id(run(&mut app, "object.group", json!({}))));
+ ids.insert("ellipse", ellipse);
+ let parts = [star(&mut app, 150), star(&mut app, 160)];
+ run(&mut app, "select.set", json!({"ids": [parts[0].0, parts[1].0]}));
+ ids.insert("compound", id(run(&mut app, "object.compoundPath.make", json!({}))));
+ let guide = id(run(&mut app, "shape.arc", json!({"x1": 0, "y1": 300, "x2": 50, "y2": 350})));
+ run(&mut app, "select.set", json!({"ids": [guide.0]}));
+ run(&mut app, "view.guides.make", json!({}));
+ ids.insert("guide", guide);
+ run(&mut app, "guide.add", json!({"vertical": true, "pos": 50}));
+ let mut png = vec![];
+ image::RgbaImage::from_pixel(4, 4, image::Rgba([200, 40, 40, 255]))
+ .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
+ .unwrap();
+ let placed = |app: &mut VectorcraftApp, p: serde_json::Value| NodeId(run(app, "file.place", p)["ids"][0].as_u64().unwrap());
+ ids.insert("embedded", placed(&mut app, json!({"name": "pic.png", "dataBase64": vectorcraft_format::base64_encode(&png)})));
+ // One file for every test that calls this, written by the first.
+ static LINKED: std::sync::OnceLock<std::path::PathBuf> = std::sync::OnceLock::new();
+ let file = LINKED.get_or_init(|| {
+ let file = vectorcraft_testkit::temp_dir("layers-filter").join("linked.png");
+ std::fs::write(&file, &png).unwrap();
+ file
+ });
+ ids.insert("linked", placed(&mut app, json!({"path": file.to_string_lossy()})));
+ ids.insert("sub", id(run(&mut app, "layer.newSublayer", json!({"name": "Sub"}))));
+ let hidden = star(&mut app, 250);
+ run(&mut app, "layer.setProps", json!({"ids": [hidden.0], "name": "Sky", "visible": false}));
+ let locked = star(&mut app, 300);
+ run(&mut app, "layer.setProps", json!({"ids": [locked.0], "locked": true}));
+ ids.extend([("hidden", hidden), ("locked", locked)]);
+ run(&mut app, "select.none", json!({}));
+ (app, ids)
+ }
+
+ /// The rows [`list_rows`] lists for `query` and `filter`, by their names in `ids` ("ruler guide"
+ /// for a guide's row).
+ fn listed(app: &VectorcraftApp, ids: &HashMap<&'static str, NodeId>, query: &str, filter: &Filter) -> Vec<&'static str> {
+ let st = app.session.active().unwrap();
+ let rows = list_rows(&st.doc, &st.layers_open, &PanelOptions::default(), query, filter);
+ let name = |r: &Row| match r.guide {
+ Some(_) => "ruler guide",
+ None => ids.iter().find(|(_, id)| **id == r.node.id).map_or("?", |(name, _)| *name),
+ };
+ rows.iter().map(name).collect()
+ }
+
+ fn only(k: ObjectKind) -> Filter {
+ Filter { objects: vec![k], layers: vec![] }
+ }
+
+ /// Each object kind keeps exactly the rows of that kind, with the rows holding them, open or
+ /// closed.
+ #[test]
+ fn each_object_kind_keeps_its_rows_and_the_rows_holding_them() {
+ let (app, ids) = kinds();
+ for (k, want) in [
+ (ObjectKind::Paths, vec!["layer", "sub", "locked", "hidden", "compound", "path"]),
+ (ObjectKind::Shapes, vec!["layer", "group", "ellipse", "rect"]),
+ (ObjectKind::Text, vec!["layer", "text"]),
+ (ObjectKind::Images, vec!["layer", "linked", "embedded"]),
+ (ObjectKind::Effects, vec!["layer", "group", "ellipse"]),
+ (ObjectKind::Groups, vec!["layer", "group"]),
+ (ObjectKind::LinkedFiles, vec!["layer", "linked"]),
+ (ObjectKind::Guides, vec!["layer", "ruler guide", "guide"]),
+ ] {
+ assert_eq!(listed(&app, &ids, "", &only(k)), want, "{k:?}");
+ }
+ }
+
+ /// By Layer keeps the rows that are locked or hidden themselves: in a hidden, locked sublayer a
+ /// row stays only for its own lock or eye. Two choices in a section take either; a choice in
+ /// each section takes rows that are both.
+ #[test]
+ fn row_states_keep_locked_or_hidden_rows_and_combine_with_kinds() {
+ let (mut app, ids) = kinds();
+ let f = |objects: Vec<ObjectKind>, layers: Vec<RowState>| Filter { objects, layers };
+ assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
+ assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked])), ["layer", "sub", "locked"]);
+ assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked, RowState::Hidden])), ["layer", "sub", "locked", "hidden"]);
+ assert_eq!(listed(&app, &ids, "", &f(vec![ObjectKind::Text, ObjectKind::Images], vec![])), ["layer", "linked", "embedded", "text"]);
+ assert_eq!(listed(&app, &ids, "", &f(vec![ObjectKind::Paths], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
+ assert!(listed(&app, &ids, "", &f(vec![ObjectKind::Shapes], vec![RowState::Hidden])).is_empty());
+ // Once Sub is hidden and locked, the rows in it stay only for their own lock or eye.
+ app.session.execute("layer.setProps", &json!({"ids": [ids["sub"].0], "visible": false, "locked": true})).unwrap();
+ assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Hidden])), ["layer", "sub", "hidden"]);
+ assert_eq!(listed(&app, &ids, "", &f(vec![], vec![RowState::Locked])), ["layer", "sub", "locked"]);
+ }
+
+ /// The filter and the search combine: a row stays when its name holds the text and the filter
+ /// keeps it, or when it holds such a row.
+ #[test]
+ fn the_filter_combines_with_the_search() {
+ let (app, ids) = kinds();
+ assert_eq!(listed(&app, &ids, "sky", &Filter::default()), ["layer", "sub", "hidden", "text"]);
+ assert_eq!(listed(&app, &ids, "sky", &only(ObjectKind::Text)), ["layer", "text"]);
+ assert_eq!(listed(&app, &ids, "sky", &Filter { objects: vec![], layers: vec![RowState::Hidden] }), ["layer", "sub", "hidden"]);
+ assert!(listed(&app, &ids, "sky", &only(ObjectKind::Groups)).is_empty());
+ }
+
+ /// (target circles, lit 24 pt buttons) one frame of the panel draws.
+ fn circles_and_lit_buttons(app: &mut VectorcraftApp, ctx: &egui::Context) -> (usize, usize) {
+ let lit = Tokens::get(ctx).tool_active;
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui));
+ out.textures_delta.clear();
+ let circles = out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Circle(cs) if cs.radius == 5.0)).count();
+ let buttons =
+ out.shapes.iter().filter(|c| matches!(&c.shape, egui::Shape::Rect(r) if r.fill == lit && (r.rect.width() - 24.0).abs() < 0.01)).count();
+ (circles, buttons)
+ }
+
+ /// `ui.layersFilter` has the panel list its rows again at once and lights the Filter button
+ /// while a filter is on; clearing it lists every row again. The document, its open rows and the
+ /// selection stay as they were.
+ #[test]
+ fn the_panel_lists_its_rows_again_when_the_filter_changes() {
+ let (mut app, ids) = kinds();
+ app.session.execute("select.set", &json!({"ids": [ids["rect"].0]})).unwrap();
+ let ctx = egui::Context::default();
+ let before = circles_and_lit_buttons(&mut app, &ctx);
+ assert_eq!(before.1, 0, "the Filter button is not lit");
+ let st = app.session.active().unwrap();
+ let (revision, open) = (st.revision, st.layers_open.generation());
+ let r = app.run("ui.layersFilter", json!({"objects": ["text"]})).unwrap();
+ assert_eq!(r, json!({"objects": ["text"], "layers": []}));
+ assert_eq!(circles_and_lit_buttons(&mut app, &ctx), (2, 1), "Layer 1 and the type; the button is lit");
+ app.run("ui.layersFilter", json!({"layers": ["hidden"]})).unwrap();
+ assert_eq!(circles_and_lit_buttons(&mut app, &ctx), (0, 1), "no type is hidden");
+ app.run("ui.layersFilter", json!({"objects": [], "layers": []})).unwrap();
+ assert_eq!(circles_and_lit_buttons(&mut app, &ctx), before, "every row again");
+ let st = app.session.active().unwrap();
+ assert_eq!((st.revision, st.layers_open.generation(), st.selection.objects.clone()), (revision, open, vec![ids["rect"]]));
+ }
+
+ /// Clicks in the Filter button's popup tick a kind and a state, and a second click clears the
+ /// kind, while the popup stays open; Clear All turns the filter off.
+ #[test]
+ fn the_filter_popup_ticks_kinds_and_states_and_clear_all_turns_the_filter_off() {
+ let (mut app, _) = kinds();
+ let ctx = egui::Context::default();
+ // The Filter button: the 24 pt square lit while a filter is on.
+ app.run("ui.layersFilter", json!({"layers": ["locked"]})).unwrap();
+ let lit = Tokens::get(&ctx).tool_active;
+ let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(&mut app, ui));
+ out.textures_delta.clear();
+ let filter = out
+ .shapes
+ .iter()
+ .find_map(|c| match &c.shape {
+ egui::Shape::Rect(r) if r.fill == lit && (r.rect.width() - 24.0).abs() < 0.01 => Some(r.rect.center()),
+ _ => None,
+ })
+ .unwrap();
+ app.run("ui.layersFilter", json!({"layers": []})).unwrap();
+ click_with(&mut app, &ctx, filter, egui::Modifiers::NONE);
+ // Where the popup draws `label` (after a frame for it to settle).
+ let at = |app: &mut VectorcraftApp, label: &str| {
+ super::super::tests_appearance::frame_events(&ctx, app, vec![], show);
+ let texts = super::super::tests_appearance::frame_events(&ctx, app, vec![], show);
+ texts.iter().find(|(t, _)| t == label).map(|(_, r)| r.center()).unwrap_or_else(|| panic!("{label} not in {texts:?}"))
+ };
+ let text = at(&mut app, "Text");
+ click_with(&mut app, &ctx, text, egui::Modifiers::NONE);
+ assert_eq!(app.ui.layers_filter, Filter { objects: vec![ObjectKind::Text], layers: vec![] });
+ let hidden = at(&mut app, "Hidden");
+ click_with(&mut app, &ctx, hidden, egui::Modifiers::NONE);
+ assert_eq!(app.ui.layers_filter, Filter { objects: vec![ObjectKind::Text], layers: vec![RowState::Hidden] });
+ click_with(&mut app, &ctx, text, egui::Modifiers::NONE);
+ assert_eq!(app.ui.layers_filter, Filter { objects: vec![], layers: vec![RowState::Hidden] }, "a second click takes it out");
+ let clear = at(&mut app, "Clear All");
+ click_with(&mut app, &ctx, clear, egui::Modifiers::NONE);
+ assert!(!app.ui.layers_filter.is_on());
+ }
+
+ /// `ui.layersFilter` reads its lists by name in the popup's order, keeps a list it is not given,
+ /// and changes nothing when a list holds anything else.
+ #[test]
+ fn the_filter_command_reads_its_lists_by_name() {
+ let mut app = VectorcraftApp::new(Session::new(), Default::default());
+ let r = app.run("ui.layersFilter", json!({"objects": ["guides", "paths", "paths"], "layers": ["hidden"]})).unwrap();
+ assert_eq!(r, json!({"objects": ["paths", "guides"], "layers": ["hidden"]}));
+ let r = app.run("ui.layersFilter", json!({"layers": []})).unwrap();
+ assert_eq!(r, json!({"objects": ["paths", "guides"], "layers": []}));
+ for bad in [json!({"objects": ["paths", "layers"]}), json!({"objects": "paths"}), json!({"objects": [], "layers": ["visible"]})] {
+ let e = app.run("ui.layersFilter", bad.clone()).unwrap_err();
+ let key = if bad["layers"].is_null() { "objects" } else { "layers" };
+ assert!(e.starts_with(&format!("`{key}` must be an array of these names: ")), "{bad}: {e}");
+ }
+ assert_eq!(app.run("ui.layersFilter", json!({})).unwrap(), json!({"objects": ["paths", "guides"], "layers": []}), "unchanged");
+ }
+
#[test]
fn dragging_rows_moves_them_into_other_layers_and_alt_copies() {
let (mut app, [layer, sub, g, _, a, c]) = nested();
diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs
index 52916faeb..d47ac078e 100644
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@ -449,6 +449,10 @@ pub struct UiState {
/// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only).
#[serde(default)]
pub layers_panel: crate::panels::layers::PanelOptions,
+ /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the
+ /// Search All text does.
+ #[serde(skip)]
+ pub layers_filter: crate::panels::layers::Filter,
/// The Image Trace panel's Advanced section is open (as it was last left).
#[serde(default = "yes")]
pub image_trace_advanced: bool,
@@ -750,6 +754,7 @@ impl Default for UiState {
dxf_import: Value::Null,
home: None,
layers_panel: Default::default(),
+ layers_filter: Default::default(),
image_trace_advanced: true,
window: None,
}
diff --git a/docs/mcp.md b/docs/mcp.md
index 754a2d18b..428917488 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -1367,6 +1367,15 @@ and `layerRows`, the rows highlighted in the panel.
layersOnly, rowSize small|medium|large|other, otherSize, thumbLayers, thumbGroups, thumbObjects), and
`ui.layersExpand {ids?, open?}` opens or closes rows as their triangles do (Alt-click: everything inside).
A document opens with only its top-level layers open; the open rows are saved in the native file and reopen that way.
+- **Search and filter** (control channel and the app's MCP): the Search All field keeps the rows whose names hold the
+ text typed, and `ui.layersFilter {objects?, layers?}` sets the choices of the Filter button beside it. `objects` (By
+ Object) takes `paths` (paths and compound paths), `shapes` (live rectangles, ellipses, polygons and lines), `text`,
+ `images`, `effects` (rows with an effect on themselves or on a fill or stroke, shown or hidden), `groups`,
+ `linkedFiles` (linked images and placed documents) and `guides` (paths made into guides, and ruler guides); `layers`
+ (By Layer) takes `locked` and `hidden` (the row's own lock and eye). A row stays when it is one of those kinds and in
+ one of those states (an empty list takes every row) and its name holds the search text, or when a row inside it
+ stays. A key left out keeps its list. The filter lasts the session and does not change the document, its open rows
+ or the selection. `ui.layersFilter` answers `{objects, layers}`.
```json
{"name":"run_command","arguments":{"command":"layer.newSublayer","params":{"name":"Shadows"}}}
diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md
index d3ba92c52..998fdbfc8 100644
--- a/docs/target-app-parity.md
+++ b/docs/target-app-parity.md
@@ -483,6 +483,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
Keep selected in the Pencil and Paintbrush Tool Options is on by default; while it is off, the path a stroke draws or continues is not selected afterwards and the rest of the selection stays as it was (`path.freehand` `keepSelected`).
- **Ruler guides as layer objects:** a guide goes on the current layer, shows, hides, locks and is deleted with it, is listed in the Layers panel (its row selects it) and moves to another layer (`guide.setLayer`, or its row dragged onto that layer's rows); guides on a hidden or locked layer can't be selected, moved or deleted, Duplicate copies a layer's guides and Merge Selected and Flatten Artwork keep them on the merged layer; guides from files saved before guides had layers go on the top visible, unlocked layer when the document opens. Not done: guides stacked among the art of their layer (they are listed above it), a guide row's own eye and lock. Lock Guides also locks the objects made into guides: they can't be selected, moved or deleted (#1543); they are drawn in the guide colour and style of Preferences, and a dragged selection snaps to ruler guides with Smart Guides on (#1583, fixes #1534). The Transform panel shows a selected ruler guide's X or Y, and typing a value moves it (#1659, part of #1597). This is not established by the documentation we could find: the public help pages on guides, rulers and the Transform, Control and Properties panels (read again on 2026-10-14) describe selecting and dragging unlocked guides and the panels' X and Y for a selection, not a guide's position in a panel, and the one public statement of it is a user's [community answer](https://community.adobe.com/questions-652/adding-a-new-custom-guide-785586), which is not documentation. It is kept as a convenience pending the owner's decision, with no parity claim and nothing counted towards a score.
- **Layers panel:** every layer, sublayer, group and object is a clickable row at any depth: a click highlights it and makes its layer current (new art goes there), Shift-click a range, Ctrl/Cmd-click toggles. Sublayers are no longer treated as objects: clicks, marquees, Select All and the Select menu take the art inside them, and each sublayer selects in its own colour. Selection squares on rows with selected art (click selects a row's art, Shift adds or removes; dragging the square moves the selection to another row, Alt copies), the eye and lock on every row with drag-down-the-column (one undo step), Ctrl/Cmd-click an eye for per-layer Outline, Alt-click an eye or lock to hide or lock the other layers (again: show or unlock them all), triangles with Alt to open or close everything inside, drag and drop rows above, below or into layers and groups with a drop line (Alt copies) and a dimmed copy of the row under the pointer (dropped on the trash rows are deleted, on New Layer duplicated, as in Illustrator), inline rename, Delete key on highlighted rows. Buttons and the full panel menu: New Layer/Sublayer (Alt: options, Ctrl: on top), Duplicate, Delete, Options for Selection, clipping mask, isolation, Locate Object, Merge Selected, Flatten Artwork, Collect in New Layer, Release to Layers (Sequence and Build), Reverse Order, Template, Hide/Outline/Lock Others and Show/Preview/Unlock All, Paste Remembers Layers, Panel Options (row size, thumbnails per kind, Show Layers Only). Layer Options: name, colour (presets, each with a chip of its colour, or custom), Template, Lock, Show, Print, Preview (outline drawing and clicking) and Dim Images to %. Every operation is a command (`layer.move`, `layer.highlight`, `layer.merge`…) with validation against cycles and invalid nesting. A document opens with only its top-level layers open; the rows left open are saved in the native file (nothing is written for the default) and reopen that way. Only the rows scrolled into view are laid out, from a row list made once per change: a layer of 5,000 groups of 10 paths, all open, draws the panel in 0.4 ms a frame instead of about 29 s (#638).
+ The Filter button at the right of Search All keeps the rows that are of an object kind ticked under By Object (paths, shapes, text, images, effects, groups, linked files, guides) and in a state ticked under By Layer (locked, hidden), with the rows that hold them; a section with nothing ticked takes every row. The filter combines with the search, the button is lit while a filter is on, and Clear All in its popup turns the filter off (`ui.layersFilter`). The filter lasts the session.
`object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do.
Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`).
Object › Arrange › Send to Current Layer returns the error "the target layer is locked or hidden" and leaves the selected objects where they are when the current layer is hidden or locked, or is inside a hidden or locked layer.