Skip to content

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

Merge upstream/main (cdfec72f) into Smart Filters editors

abc2cb641155b3bcab
diff --cc crates/ui-egui/src/canvas.rs
index 017c2a814,0ed696064..263294077
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -1469,9 -1623,17 +1627,17 @@@ pub(crate) fn ensure_filter_preview(app
}
let st = app.session.documents().get(idx)?;
// Filters whose features don't scale with a proxy preview at full resolution (#2063).
- let k = crate::filter_dialog::preview_factor(&cmd, &params, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)));
+ let k = crate::filter_dialog::smart_preview_factor(&st.doc, &cmd, &params, crate::proxy::preview_factor(&st.doc, crate::proxy::reduced_previews(app)));
- let request =
- crate::filter_dialog::FilterPreviewKey { doc: st.doc.id, revision: st.revision, dialog: d.id, active: st.active_layer, command: cmd, params, k };
+ let request = crate::filter_dialog::FilterPreviewKey {
+ doc: st.doc.id,
+ revision: st.revision,
+ dialog: d.id,
+ active: st.active_layer,
+ target: st.channel_view.target,
+ command: cmd,
+ params,
+ k,
+ };
let key = request.doc.0 ^ (1u64 << 61);
// Every filter's preview computes off the UI thread in the desktop app: Gaussian Blur at
// 1000 px takes long enough to freeze the window. Once the slider settles, a preview still
diff --cc crates/ui-egui/src/filter_dialog.rs
index 110512483,4c19b8943..4402528a4
--- a/crates/ui-egui/src/filter_dialog.rs
+++ b/crates/ui-egui/src/filter_dialog.rs
@@@ -752,72 -860,19 +860,75 @@@ pub(crate) fn preview_document_for_targ
// Warp Text renders the type again from the layer model (font size, position), which a
// reduced proxy doesn't scale: it runs at full size and the result is reduced (#218).
let (run_k, reduce_k) = if command == "type.warpText" { (1, k) } else { (k, 1) };
- let proxy = crate::proxy::proxy_document(doc, run_k);
+ let mut proxy = crate::proxy::proxy_document(doc, run_k);
+ let mut p = params.clone();
+ if is_smart_edit(command) {
+ let layer = photocraft_doc::LayerId(params.get("layer")?.as_u64()?);
+ let index = usize::try_from(params.get("index")?.as_u64()?).ok()?;
+ let photocraft_doc::LayerContent::Smart(sm) = &mut proxy.layer_mut(layer)?.content else { return None };
+ // Proxy_document scales the visible cache only. Editing a filter re-renders its source:
+ // scale the placement, every filter's lengths and the shared mask as well.
+ if run_k > 1 {
+ let divisor = f64::from(run_k);
+ sm.transform.m = sm.transform.m.map(|v| v / divisor);
+ if let Some(h) = &mut sm.perspective {
+ for v in h.iter_mut().take(6) {
+ *v /= divisor;
+ }
+ }
+ if let Some(mask) = &mut sm.filter_mask {
+ mask.surface = crate::proxy::downsample(&mask.surface, run_k);
+ mask.feather /= run_k as f32;
+ }
+ for f in &mut sm.smart_filters {
+ scale_preview_params(&f.command, &mut f.params, run_k);
+ }
+ if command == "layer.smartFilter.setParams" {
+ let f = sm.smart_filters.get(index)?;
+ scale_preview_params(&f.command, p.get_mut("params")?, run_k);
+ }
+ }
+ } else {
+ scale_preview_params(command, &mut p, run_k);
+ }
let mut s = photocraft_engine::Session::new();
s.set_inline_job_ctx(cancel.cloned());
+ let doc_id = proxy.id;
s.add_document(proxy, None);
- let mut p = params.clone();
+ add_source_documents(&mut s, doc_id, command, &mut p, documents, run_k);
if let Some(id) = active {
s.select_layer(id).ok()?;
}
+ s.active_mut()?.channel_view.target = target;
- if run_k > 1
- && let Some(o) = p.as_object_mut()
+ s.execute(command, p).ok()?;
+ s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))
+}
+
+fn is_smart_edit(command: &str) -> bool {
+ matches!(command, "layer.smartFilter.setParams" | "layer.smartFilter.blendingOptions")
+}
+
+/// Each stage constrains the proxy factor; an unscalable filter keeps full-resolution preview.
+pub(crate) fn smart_preview_factor(doc: &Document, command: &str, params: &Value, k: u32) -> u32 {
+ if !is_smart_edit(command) {
+ return preview_factor(command, params, k);
+ }
+ let Some(layer) = params.get("layer").and_then(Value::as_u64).and_then(|id| doc.layer(photocraft_doc::LayerId(id))) else { return 1 };
+ let photocraft_doc::LayerContent::Smart(sm) = &layer.content else { return 1 };
+ let mut factor = sm.smart_filters.iter().fold(k, |k, f| preview_factor(&f.command, &f.params, k));
+ if command == "layer.smartFilter.setParams"
+ && let Some(index) = params.get("index").and_then(Value::as_u64).and_then(|i| usize::try_from(i).ok())
+ && let Some(f) = sm.smart_filters.get(index)
+ && let Some(p) = params.get("params")
+ {
+ factor = preview_factor(&f.command, p, factor);
+ }
+ factor
+}
+
+fn scale_preview_params(command: &str, params: &mut Value, k: u32) {
+ if k > 1
+ && let Some(o) = params.as_object_mut()
{
let spec = photocraft_engine::commands::find(command).map(|c| parse_spec(c.params)).unwrap_or_default();
for (key, v) in o.iter_mut() {
@@@ -838,8 -893,38 +949,36 @@@
}
}
}
- s.execute(command, p).ok()?;
- s.active().map(|d| crate::proxy::proxy_document(&d.doc, reduce_k))
}
+ /// The preview session holds only the proxy of the edited document (index 0), so a document param
+ /// pointing at another open document found nothing there: Match Color's preview with a Source
+ /// document failed, or matched the image to itself (#4851). Add each referenced document (as a
+ /// proxy at the same factor) and point the param at its index in the preview session.
+ fn add_source_documents(s: &mut photocraft_engine::Session, doc_id: photocraft_doc::DocId, command: &str, p: &mut Value, documents: &[Arc<Document>], k: u32) {
+ let Some(spec) = photocraft_engine::commands::find(command) else { return };
+ let Some(o) = p.as_object_mut() else { return };
+ let mut added: Vec<(usize, usize)> = Vec::new();
+ for param in parse_spec(spec.params).into_iter().filter(|p| p.kind == Kind::Document) {
+ let Some(v) = o.get_mut(&param.key) else { continue };
+ let Some(i) = v.as_u64().and_then(|i| usize::try_from(i).ok()) else { continue };
+ // An index past the open documents stays as given, so the preview fails like OK would.
+ let Some(src) = documents.get(i) else { continue };
+ let at = if src.id == doc_id {
+ 0
+ } else if let Some(&(_, at)) = added.iter().find(|(j, _)| *j == i) {
+ at
+ } else {
+ let at = s.add_document(crate::proxy::proxy_document(src, k), None);
+ added.push((i, at));
+ at
+ };
+ *v = json!(at);
+ }
+ // Adding a document makes it active: the command still runs on the edited one.
+ s.set_active(0);
+ }
+
/// Cached preview state on the app.
pub struct FilterPreview {
pub key: FilterPreviewKey,
diff --cc crates/ui-egui/src/i18n/hu.tsv
index a0843549d,f60b798d8..390571416
--- a/crates/ui-egui/src/i18n/hu.tsv
+++ b/crates/ui-egui/src/i18n/hu.tsv
@@@ -3965,18 -3997,54 +3997,62 @@@ cameraRaw Yellow Sárg
Protect: Védelem:
Remove after each stroke Eltávolítás minden ecsetvonás után
Saving {percent} Mentés: {percent}
- Scale or rotate the moved area, then press {key} Méretezze vagy forgassa el az áthelyezett területet, majd nyomja meg: {key}
+ Scale or rotate the moved area, then press {key} Méretezd vagy forgasd el az áthelyezett területet, majd nyomd meg: {key}
Smooth the curve values A görbeértékek simítása
Strokes to remove: {n} (Enter applies, Esc cancels) Eltávolítandó ecsetvonások: {n} (Enter: alkalmazás, Esc: mégse)
- The layer or its mask changed. Drag the mask onto the Trash again. A réteg vagy a maszkja megváltozott. Húzza újra a maszkot a Kukába.
+ The layer or its mask changed. Drag the mask onto the Trash again. A réteg vagy a maszkja megváltozott. Húzd újra a maszkot a Kukába.
Transform On Drop Átalakítás elengedéskor
Vanishing Point is not active Az Enyészpont nem aktív
- Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattintson a négy sarokra
+ Vanishing Point: click four corners to create a plane Enyészpont: sík létrehozásához kattints a négy sarokra
+ Clear Brush Controls Ecsetvezérlők törlése
+ Reset All Locked Settings Összes zárolt beállítás visszaállítása
+ Copy Texture to Other Tools Textúra másolása más eszközökre
+
+ # Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
+ Load Actions… Műveletek betöltése…
+ Save Actions… Műveletek mentése…
+ {name} (Photoshop) {name} (Photoshop)
+ {message} ({note}) {message} ({note})
+ @plural Loaded {n} action from {file}|Loaded {n} actions from {file} {n} művelet betöltve. Forrás: {file}
+ @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} lépésnek még nincs megfelelője a PhotoCraftban
+ @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} művelet mentve. Cél: {file}
+ @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out {n} Photoshop-megfelelő nélküli lépés kihagyva
+
+ # Actions panel: set folders, dialog toggle, Insert Stop
+ Insert Stop… Leállítás beszúrása…
+ Save Set… Készlet mentése…
+ Message: Üzenet:
+ Allow Continue Folytatás engedélyezése
+ Show dialog during playback Párbeszédablak megjelenítése lejátszáskor
+ Select an action first Először válassz ki egy műveletet
+ Action playback stopped A művelet lejátszása leállt
+ Step {step} is waiting for its dialog A(z) {step}. lépés a párbeszédablakára vár
+ @plural {n} action|{n} actions {n} művelet
+ Object Finder Objektumkereső
+ No object found there — drag a rectangle around it Ott nem található objektum – húzz köré egy téglalapot
+ Drag to pan · Scroll to zoom · Double-click to fit Húzás: mozgatás · Görgetés: nagyítás · Dupla kattintás: igazítás
+ Gradient Preset Options Színátmenet-előbeállítás beállításai
+ Import .GRD .GRD importálása
+ Choose a gradient file (.grd). Válasszon színátmenetfájlt (.grd).
+ Save Settings… Beállítások mentése…
+ Load Settings… Beállítások betöltése…
+ Save these settings as a Camera Raw .xmp file A beállítások mentése Camera Raw .xmp-fájlként
+ Load settings from a Camera Raw .xmp file Beállítások betöltése Camera Raw .xmp-fájlból
+ Loaded Camera Raw settings from {file} Camera Raw-beállítások betöltve innen: {file}
+ Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw-beállítások betöltve innen: {file} ({n} nem támogatott)
+ Auto Add/Delete Automatikus hozzáadás/törlés
+ ICO is limited to 256 × 256 pixels Az ICO legfeljebb 256 × 256 képpont lehet
+
+ # Channel Options and New Spot Channel (#3761)
+ Channel Color Csatorna színe
+ Color Indicates: A szín jelzése:
+ Ink Characteristics Festék jellemzői
+ Solidity: Fedőképesség:
+
+# Layers panel options and Smart Filter editors
+ Blending Options ({filter}) Keverési beállítások ({filter})
+ Hide the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek elrejtése ({key}+kattintás: minden réteg)
+ Opacity must be between 0% and 100%. Az átlátszatlanságnak 0% és 100% között kell lennie.
+ Show the layer's effects and Smart Filters ({key}-click: all layers) A réteg effektusainak és intelligens szűrőinek megjelenítése ({key}+kattintás: minden réteg)
- The document or Smart Filter changed. Reopen its dialog. A dokumentum vagy az intelligens szűrő megváltozott. Nyissa meg újra a párbeszédablakát.
- Wait for the current job to finish. Várja meg, amíg az aktuális feladat befejeződik.
++ The document or Smart Filter changed. Reopen its dialog. A dokumentum vagy az intelligens szűrő megváltozott. Nyisd meg újra a párbeszédablakát.
++ Wait for the current job to finish. Várd meg, amíg az aktuális feladat befejeződik.
diff --cc crates/ui-egui/src/i18n/tr.tsv
index 48aac2cdf,23986a8c5..379aba40c
--- a/crates/ui-egui/src/i18n/tr.tsv
+++ b/crates/ui-egui/src/i18n/tr.tsv
@@@ -3784,11 -3815,47 +3815,55 @@@ cameraData Lens Len
@plural {n} step|{n} steps {n} adım
@plural {warning} (+{n} more brush preset warning)|{warning} (+{n} more brush preset warnings) {warning} (+{n} fırça ön ayarı uyarısı daha)
@plural {what} with {n} warning|{what} with {n} warnings {what}, {n} uyarı ile
+ Clear Brush Controls Fırça Denetimlerini Temizle
+ Reset All Locked Settings Tüm Kilitli Ayarları Sıfırla
+ Copy Texture to Other Tools Dokuyu Diğer Araçlara Kopyala
+
+ # Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
+ Load Actions… Eylemleri Yükle…
+ Save Actions… Eylemleri Kaydet…
+ {name} (Photoshop) {name} (Photoshop)
+ {message} ({note}) {message} ({note})
+ @plural Loaded {n} action from {file}|Loaded {n} actions from {file} {file} dosyasından {n} eylem yüklendi
+ @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} adımın PhotoCraft’ta henüz karşılığı yok
+ @plural Saved {n} action to {file}|Saved {n} actions to {file} {n} eylem {file} dosyasına kaydedildi
+ @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Photoshop karşılığı olmayan {n} adım atlandı
+
+ # Actions panel: set folders, dialog toggle, Insert Stop
+ Insert Stop… Durdurma Ekle…
+ Save Set… Seti Kaydet…
+ Message: İleti:
+ Allow Continue Devam Etmeye İzin Ver
+ Show dialog during playback Oynatma sırasında iletişim kutusunu göster
+ Select an action first Önce bir eylem seçin
+ Action playback stopped Eylem oynatma durduruldu
+ Step {step} is waiting for its dialog {step}. adım iletişim kutusunu bekliyor
+ @plural {n} action|{n} actions {n} eylem
+ Object Finder Nesne Bulucu
+ No object found there — drag a rectangle around it Orada nesne bulunamadı — çevresine bir dikdörtgen sürükleyin
+ Drag to pan · Scroll to zoom · Double-click to fit Kaydırmak için sürükleyin · Yakınlaştırmak için kaydırın · Sığdırmak için çift tıklayın
+ Gradient Preset Options Gradyan Ön Ayarı Seçenekleri
+ Import .GRD .GRD İçe Aktar
+ Choose a gradient file (.grd). Bir gradyan dosyası (.grd) seçin.
+ Save Settings… Ayarları Kaydet…
+ Load Settings… Ayarları Yükle…
+ Save these settings as a Camera Raw .xmp file Bu ayarları Camera Raw .xmp dosyası olarak kaydet
+ Load settings from a Camera Raw .xmp file Ayarları bir Camera Raw .xmp dosyasından yükle
+ Loaded Camera Raw settings from {file} Camera Raw ayarları {file} dosyasından yüklendi
+ Loaded Camera Raw settings from {file} ({n} not supported) Camera Raw ayarları {file} dosyasından yüklendi ({n} desteklenmiyor)
+ Auto Add/Delete Otomatik Ekle/Sil
+ ICO is limited to 256 × 256 pixels ICO 256 × 256 piksel ile sınırlıdır
+
+ # Channel Options and New Spot Channel (#3761)
+ Channel Color Kanal Rengi
+ Color Indicates: Rengin Gösterdiği:
+ Ink Characteristics Mürekkep Özellikleri
+ Solidity: Doluluk:
+
+# Layers panel options and Smart Filter editors
+ Blending Options ({filter}) Karışım Seçenekleri ({filter})
+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini gizle ({key}-tık: tüm katmanlar)
+ Opacity must be between 0% and 100%. Opaklık %0 ile %100 arasında olmalıdır.
+ Show the layer's effects and Smart Filters ({key}-click: all layers) Katmanın efektlerini ve Akıllı Filtrelerini göster ({key}-tık: tüm katmanlar)
+ The document or Smart Filter changed. Reopen its dialog. Belge veya Akıllı Filtre değişti. İletişim kutusunu yeniden açın.
+ Wait for the current job to finish. Geçerli işin bitmesini bekleyin.
diff --cc crates/ui-egui/src/i18n/vi.tsv
index 9394c4238,e56eaf305..761356dc2
--- a/crates/ui-egui/src/i18n/vi.tsv
+++ b/crates/ui-egui/src/i18n/vi.tsv
@@@ -3536,11 -3583,32 +3583,40 @@@ curves Smooth Làm mượ
Remove after each stroke Xóa sau mỗi nét vẽ
Apply the removal ({key}) Áp dụng việc xóa ({key})
Strokes to remove: {n} (Enter applies, Esc cancels) Nét vẽ cần xóa: {n} (Enter áp dụng, Esc hủy)
+ Clear Brush Controls Xóa điều khiển cọ
+ Reset All Locked Settings Đặt lại tất cả cài đặt đã khóa
+ Copy Texture to Other Tools Sao chép họa tiết sang các công cụ khác
+
+ # Actions panel: Load/Save Actions (.atn) and kept Photoshop steps
+ Load Actions… Nạp hành động…
+ Save Actions… Lưu hành động…
+ {name} (Photoshop) {name} (Photoshop)
+ {message} ({note}) {message} ({note})
+ @plural Loaded {n} action from {file}|Loaded {n} actions from {file} Đã nạp {n} hành động từ {file}
+ @plural {n} step has no PhotoCraft equivalent yet|{n} steps have no PhotoCraft equivalent yet {n} bước chưa có chức năng tương ứng trong PhotoCraft
+ @plural Saved {n} action to {file}|Saved {n} actions to {file} Đã lưu {n} hành động vào {file}
+ @plural {n} step with no Photoshop equivalent left out|{n} steps with no Photoshop equivalent left out Đã bỏ qua {n} bước không có chức năng tương ứng trong Photoshop
+
+ # Actions panel: set folders, dialog toggle, Insert Stop
+ Insert Stop… Chèn điểm dừng…
+ Save Set… Lưu bộ…
+ Message: Thông báo:
+ Allow Continue Cho phép tiếp tục
+ Show dialog during playback Hiện hộp thoại khi phát
+ Select an action first Hãy chọn một hành động trước
+ Action playback stopped Đã dừng phát hành động
+ Step {step} is waiting for its dialog Bước {step} đang chờ hộp thoại của nó
+ @plural {n} action|{n} actions {n} hành động
+ Gradient Preset Options Tùy chọn thiết lập sẵn chuyển sắc
+ Import .GRD Nhập .GRD
+ Choose a gradient file (.grd). Chọn tệp chuyển sắc (.grd).
+ Auto Add/Delete Tự động thêm/xóa
+ ICO is limited to 256 × 256 pixels ICO giới hạn ở 256 × 256 pixel
+
+# Layers panel options and Smart Filter editors
+ Blending Options ({filter}) Tùy chọn hòa trộn ({filter})
+ Hide the layer's effects and Smart Filters ({key}-click: all layers) Ẩn hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp)
+ Opacity must be between 0% and 100%. Độ mờ phải nằm trong khoảng từ 0% đến 100%.
+ Show the layer's effects and Smart Filters ({key}-click: all layers) Hiện hiệu ứng và bộ lọc thông minh của lớp ({key}-bấm: tất cả các lớp)
+ The document or Smart Filter changed. Reopen its dialog. Tài liệu hoặc bộ lọc thông minh đã thay đổi. Hãy mở lại hộp thoại của nó.
+ Wait for the current job to finish. Hãy chờ tác vụ hiện tại hoàn tất.
diff --cc crates/ui-egui/src/layer_row_ui.rs
index d510bb90f,7ac725a7c..31c50ed5f
--- a/crates/ui-egui/src/layer_row_ui.rs
+++ b/crates/ui-egui/src/layer_row_ui.rs
@@@ -72,18 -71,11 +72,18 @@@ pub fn layout(row: Rect, name_left: f32
/// Width the always-shown indicators of `l` take at the row's right (blend label excluded).
pub fn reserved_width(l: &Layer) -> f32 {
let mut w = RIGHT_PAD;
- if l.locks.transparency || l.locks.position || l.locks.all {
+ if l.locks.any() {
w += ICON_W + GAP;
}
+ let smart = crate::smart_ui::has_filters(l);
+ if !l.effects.items.is_empty() || smart {
+ w += TRIANGLE_W + GAP;
+ }
if !l.effects.items.is_empty() {
- w += TRIANGLE_W + 1.0 + 13.0 + GAP;
+ w += 13.0 + GAP;
+ }
+ if smart {
+ w += ICON_W + GAP;
}
if l.link_group.is_some() {
w += ICON_W + GAP;
diff --cc crates/ui-egui/src/smart_ui.rs
index 614a1898e,48b2f0a72..25e5867be
--- a/crates/ui-egui/src/smart_ui.rs
+++ b/crates/ui-egui/src/smart_ui.rs
@@@ -1,8 -1,10 +1,10 @@@
//! Layers-panel pieces for smart objects: the thumbnail badge and the Smart Filters sub-rows
- //! (eye toggles; double-click a filter to re-open its dialog with the recorded parameters).
+ //! (eye toggles; double-click a filter to re-open its dialog with the recorded parameters; click
+ //! to select one; drag onto another smart object to move it there, ⌥-drag to copy it, #4271;
+ //! drag it up or down its own stack to reorder it).
- use egui::{Color32, Rect, Sense, Stroke, pos2, vec2};
- use photocraft_doc::{Document, Layer, LayerContent, SmartObject};
-use egui::{Align2, Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
++use egui::{Color32, Rect, Sense, Stroke, StrokeKind, pos2, vec2};
+ use photocraft_doc::{Document, Layer, LayerContent, LayerId, SmartObject};
use serde_json::{Value, json};
use crate::theme::Tokens;
@@@ -51,11 -78,29 +89,26 @@@ pub fn filter_rows(app: &mut Photocraft
return;
}
let t = Tokens::get(ui.ctx());
- let indent = 30.0 + depth as f32 * 14.0 + 34.0;
+ let indent = 30.0 + crate::layer_row_ui::indent(depth, ui.available_width(), 130.0);
+ let Some(st) = app.session.active() else { return };
- let (active, doc) = (st.active_layer == Some(l.id), st.doc.id);
- let picked = ui.ctx().data(|d| d.get_temp::<FilterDrag>(selected_key(doc)));
++ let active = st.active_layer == Some(l.id);
++ let picked = ui.ctx().data(|d| d.get_temp::<FilterDrag>(selected_key(doc.id)));
let rows = std::iter::once(None).chain((0..sm.smart_filters.len()).rev().map(Some));
for index in rows {
- let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if index.is_none() { 30.0 } else { 22.0 }), Sense::hover());
- if resp.hovered() {
- let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag());
- if resp.drag_started() {
- ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(drag_key(), (l.id.0, index)));
- }
++ let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), if index.is_none() { 30.0 } else { 22.0 }), Sense::click_and_drag());
+ if let Some((to, action)) = reorder_drop(ui, l, sm.smart_filters.len(), index, rect) {
+ // The moved filter ends up selected, with its smart object active, as after a click.
- ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(selected_key(doc), (l.id.0, Some(to))));
++ ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(selected_key(doc.id), (l.id.0, Some(to))));
+ actions.push(action);
+ if !active {
+ actions.push(("layer.select".into(), json!({"layer": l.id.0})));
+ }
+ }
+ // Selected as in Photoshop: the row stays highlighted while its smart object is active.
+ let selected = active && picked == Some((l.id.0, index));
+ if selected {
+ ui.painter().rect_filled(rect, 0.0, if t.pro { t.row_selected } else { t.hover });
- } else if resp.hovered() {
++ } else if resp.contains_pointer() {
ui.painter().rect_filled(rect, 0.0, t.hover.gamma_multiply(0.35));
}
if t.pro {
@@@ -81,52 -125,153 +134,198 @@@
Some(i) => ("layer.smartFilter.setVisible".into(), json!({"layer": l.id.0, "index": i})),
});
}
- let x = rect.left() + indent + if index.is_none() { 0.0 } else { 16.0 };
+ let x = rect.left() + indent + 60.0;
if index.is_none() {
- let sw = Rect::from_center_size(pos2(x - 12.0, rect.center().y), vec2(14.0, 10.0));
- ui.painter().rect_filled(sw, 1.0, if sm.filter_mask.as_ref().is_some_and(|m| m.enabled) { Color32::from_gray(200) } else { Color32::WHITE });
+ let sw = Rect::from_center_size(pos2(x - 20.0, rect.center().y), vec2(24.0, 24.0));
+ if let Some(mask) = &sm.filter_mask {
+ let tex = app.mask_thumb_kind(ui.ctx(), doc, l.id, mask, crate::mask_thumbs_ui::THUMB_SMART_MASK);
+ ui.painter().image(tex, sw, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
+ if !mask.enabled {
+ ui.painter().line_segment([sw.left_top(), sw.right_bottom()], Stroke::new(1.0, t.danger));
+ ui.painter().line_segment([sw.right_top(), sw.left_bottom()], Stroke::new(1.0, t.danger));
+ }
+ } else {
+ ui.painter().rect_filled(sw, 0.0, Color32::WHITE);
+ }
ui.painter().rect_stroke(sw, 1.0, Stroke::new(1.0, t.field_border), egui::StrokeKind::Inside);
}
- ui.painter().text(pos2(x, rect.center().y), Align2::LEFT_CENTER, &name, egui::FontId::proportional(11.5), if on { t.text_dim } else { t.text_faint });
- resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name));
- if resp.clicked() {
- ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(selected_key(doc), (l.id.0, index)));
+ let blend = index.map(|_| Rect::from_center_size(pos2(rect.right() - crate::layer_row_ui::RIGHT_PAD - 9.0, rect.center().y), vec2(18.0, 18.0)));
+ let right = blend.map_or(rect.right() - crate::layer_row_ui::RIGHT_PAD, |r| r.left() - 4.0);
+ crate::layer_row_ui::label(
+ ui.painter(),
+ x,
+ rect.center().y,
+ right,
+ &name,
+ egui::FontId::proportional(11.5),
+ if on { t.text_dim } else { t.text_faint },
+ );
- if let Some(i) = index {
++ // A filter's name is its own target, apart from the Blending Options icon (#3283): it
++ // selects, drags (#4271) and opens the filter's editor on a double-click. The row around
++ // it does the same, but only the name carries the row's label and selected state.
++ let name_resp = index.map(|i| {
+ let name_rect = Rect::from_min_max(pos2(x.min(right), rect.top()), pos2(right, rect.bottom()));
- let name_resp = ui.interact(name_rect, ui.id().with(("sf-name", l.id.0, i)), Sense::click());
- name_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &name));
- if name_resp.double_clicked() {
- open_editor(app, ui.ctx(), l.id.0, sm, i);
++ ui.interact(name_rect, ui.id().with(("sf-name", l.id.0, i)), Sense::click_and_drag())
++ });
++ match &name_resp {
++ Some(r) => r.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name)),
++ None => resp.widget_info(|| egui::WidgetInfo::selected(egui::WidgetType::SelectableLabel, true, selected, &name)),
++ }
++ let hit = |f: fn(&egui::Response) -> bool| f(&resp) || name_resp.as_ref().is_some_and(f);
++ if hit(egui::Response::drag_started) {
++ ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(drag_key(), (l.id.0, index)));
++ }
++ if hit(egui::Response::clicked) {
++ ui.ctx().data_mut(|d| d.insert_temp::<FilterDrag>(selected_key(doc.id), (l.id.0, index)));
+ if !active {
+ actions.push(("layer.select".into(), json!({"layer": l.id.0})));
}
- if let Some(r) = blend {
- let blend_resp = ui.interact(r, ui.id().with(("sf-blend", l.id.0, i)), Sense::click());
- icons::paint(ui, r, "sliders-horizontal", 13.0, if blend_resp.hovered() { t.text } else { t.icon });
- let label = crate::i18n::fmt(tl!("Blending Options ({filter})"), &[("filter", &name)]);
- blend_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));
- if blend_resp.double_clicked()
- && let Err(e) = crate::smart_filter_dialog::open(app, l.id, i)
- {
- crate::notices::error(app, e);
- }
- blend_resp.on_hover_text(label);
+ }
+ if let Some(i) = index
- && resp.double_clicked()
++ && hit(egui::Response::double_clicked)
+ {
+ open_editor(app, ui.ctx(), l.id.0, sm, i);
+ }
++ if let (Some(i), Some(r)) = (index, blend) {
++ let blend_resp = ui.interact(r, ui.id().with(("sf-blend", l.id.0, i)), Sense::click());
++ icons::paint(ui, r, "sliders-horizontal", 13.0, if blend_resp.hovered() { t.text } else { t.icon });
++ let label = crate::i18n::fmt(tl!("Blending Options ({filter})"), &[("filter", &name)]);
++ blend_resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, &label));
++ if blend_resp.double_clicked()
++ && let Err(e) = crate::smart_filter_dialog::open(app, l.id, i)
++ {
++ crate::notices::error(app, e);
++ }
++ blend_resp.on_hover_text(label);
++ }
+ }
+ }
+
+ /// Smart filter rows being dragged: the smart object and the filter index (`None` = the Smart
+ /// Filters row, all of them). Also what a click selects.
+ pub(crate) type FilterDrag = (u64, Option<usize>);
+
+ pub(crate) fn drag_key() -> egui::Id {
+ egui::Id::new("smart-filter-drag")
+ }
+
+ /// The selected smart filter row of a document.
+ fn selected_key(doc: photocraft_doc::DocId) -> egui::Id {
+ egui::Id::new(("smart-filter-selected", doc))
+ }
+
+ /// The selected smart filter row, while its smart object is active and the filter still exists.
+ pub(crate) fn selected(ctx: &egui::Context, doc: &Document, active: Option<LayerId>) -> Option<FilterDrag> {
+ let (layer, filter) = ctx.data(|d| d.get_temp::<FilterDrag>(selected_key(doc.id)))?;
+ if active != Some(LayerId(layer)) {
+ return None;
+ }
+ let LayerContent::Smart(sm) = &doc.layer(LayerId(layer))?.content else { return None };
+ let exists = match filter {
+ Some(i) => i < sm.smart_filters.len(),
+ None => !sm.smart_filters.is_empty(),
+ };
+ exists.then_some((layer, filter))
+ }
+
+ /// Forgets the selected smart filter row: its smart object's own row was clicked, or the filter
+ /// was deleted (its index would now name the next one).
+ pub(crate) fn deselect(ctx: &egui::Context, doc: photocraft_doc::DocId) {
+ ctx.data_mut(|d| d.remove::<FilterDrag>(selected_key(doc)));
+ }
+
+ /// While smart filters are dragged: their name by the pointer, and the copy cursor while ⌥ is held.
+ pub(crate) fn drag_feedback(ctx: &egui::Context, doc: &Document) {
+ let Some((from, filter)) = ctx.data(|d| d.get_temp::<FilterDrag>(drag_key())) else { return };
+ let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return };
+ let label = match (filter, doc.layer(LayerId(from)).map(|l| &l.content)) {
+ (Some(i), Some(LayerContent::Smart(sm))) => sm.smart_filters.get(i).map_or_else(String::new, filter_label),
+ _ => "Smart Filters".to_string(),
+ };
+ crate::layer_transfer::ghost(ctx, p, &label);
+ if ctx.input(|i| i.modifiers.alt) {
+ ctx.set_cursor_icon(egui::CursorIcon::Copy);
+ }
+ }
+
+ /// The command for dropping the smart filters of `from` on the smart object `target`: they move
+ /// there, or with ⌥ held on release are copied (Photoshop).
+ pub(crate) fn drop_action(from: u64, filter: Option<usize>, target: LayerId, copy: bool) -> (String, Value) {
+ let mut payload = json!({"from": from, "to": target.0, "copy": copy});
+ if let (Some(i), Some(o)) = (filter, payload.as_object_mut()) {
+ o.insert("filter".into(), json!(i));
+ }
+ ("layer.smartFilter.transfer".into(), payload)
+ }
+
+ /// Another smart object's row accepts the smart filters being dragged: outlined while the pointer
+ /// is over it, dropped on release. Other layers don't take them, as in Photoshop.
+ pub(crate) fn drop_on_row(ctx: &egui::Context, ui: &egui::Ui, l: &Layer, rect: Rect, actions: &mut Vec<(String, Value)>) {
+ let Some((from, filter)) = ctx.data(|d| d.get_temp::<FilterDrag>(drag_key())) else { return };
+ let Some(p) = ctx.input(|i| i.pointer.interact_pos()) else { return };
+ if from == l.id.0 || !matches!(l.content, LayerContent::Smart(_)) || !rect.contains(p) {
+ return;
+ }
+ let t = Tokens::get(ctx);
+ ui.painter().rect_stroke(rect.shrink(1.0), t.radius_sm, Stroke::new(2.0, t.accent), StrokeKind::Inside);
+ if ctx.input(|i| i.pointer.any_released()) {
+ actions.push(drop_action(from, filter, l.id, ctx.input(|i| i.modifiers.alt)));
+ }
+ }
+
+ /// Where `layer.smartFilter.move` puts filter `src` (stack index, 0 = bottom) dropped on the row
+ /// of filter `row` (`None`: the Smart Filters row, i.e. on top of the stack), `above` or below
+ /// it, in a stack of `n`. `None` when the filter would stay where it is.
+ fn reorder_target(src: usize, row: Option<usize>, above: bool, n: usize) -> Option<usize> {
+ let to = match row {
+ None => n.checked_sub(1)?,
+ Some(i) if i == src => return None,
+ // Above a row is just over it in the stack, below a row just under it. `move` removes
+ // the filter first, so the filters over `src` shift down by one.
+ Some(i) if above => {
+ if src < i {
+ i
+ } else {
+ i + 1
+ }
+ }
+ Some(i) => {
+ if src < i {
+ i - 1
+ } else {
+ i
}
}
+ };
+ (to < n && to != src).then_some(to)
+ }
+
+ /// A filter dragged up or down its own smart object's stack (Photoshop): over another row of the
+ /// stack a line marks where it lands, above or below that row (the Smart Filters row: on top),
+ /// and the release moves it there. The bottom filter is applied first, so the order changes the
+ /// result (Unsharp Mask over a blur sharpens the blurred image; under it, the sharpening is
+ /// blurred). Returns the filter's new index and the command.
+ fn reorder_drop(ui: &egui::Ui, l: &Layer, n: usize, row: Option<usize>, rect: Rect) -> Option<(usize, (String, Value))> {
+ let ctx = ui.ctx();
+ let (from, src) = ctx.data(|d| d.get_temp::<FilterDrag>(drag_key()))?;
+ let (src, p) = (src?, ctx.input(|i| i.pointer.interact_pos())?);
+ if from != l.id.0 || !rect.contains(p) {
+ return None;
+ }
+ let above = p.y < rect.center().y;
+ let to = reorder_target(src, row, above, n)?;
+ let t = Tokens::get(ctx);
+ let y = if above && row.is_some() { rect.top() } else { rect.bottom() };
+ ui.painter().line_segment([pos2(rect.left() + 30.0, y), pos2(rect.right(), y)], Stroke::new(2.0, t.accent));
+ ctx.input(|i| i.pointer.any_released()).then(|| (to, ("layer.smartFilter.move".into(), json!({"layer": l.id.0, "index": src, "to": to}))))
+ }
+
+ /// Smart filters dropped on the footer's Delete button: a filter's row deletes that filter, the
+ /// Smart Filters row clears them all.
+ pub(crate) fn trash_action((layer, filter): FilterDrag) -> (String, Value) {
+ match filter {
+ Some(i) => ("layer.smartFilter.delete".into(), json!({"layer": layer, "index": i})),
+ None => ("layer.smartFilter.clearSmartFilters".into(), json!({"layer": layer})),
}
}
@@@ -180,5 -313,88 +379,91 @@@ pub fn confirm_command(app: &Photocraft
}
}
+#[cfg(test)]
- mod tests;
++mod editor_tests;
++
+ #[cfg(test)]
+ mod tests {
+ use super::*;
+
+ /// A pixel layer, a shape layer and a smart object, in that order.
+ fn layers() -> [Layer; 3] {
+ let mut s = photocraft_engine::Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48})).unwrap();
+ // An empty layer can't become a smart object: fill it first.
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#336699"})).unwrap();
+ let smart = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap()["layer"].as_u64().unwrap();
+ let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [8, 8, 40, 24], "fill": "#cc3333"})).unwrap()["layer"].as_u64().unwrap();
+ let pixel = s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap();
+ let doc = &s.active().unwrap().doc;
+ [pixel, shape, smart].map(|id| doc.layer(photocraft_doc::LayerId(id)).unwrap().clone())
+ }
+
+ /// Stack [A, B, C] (A at the bottom, drawn last): where a dragged filter lands.
+ #[test]
+ fn a_filter_dropped_above_or_below_a_row_lands_next_to_it() {
+ // A over C: [B, C, A]. A under C: [B, A, C].
+ assert_eq!(reorder_target(0, Some(2), true, 3), Some(2));
+ assert_eq!(reorder_target(0, Some(2), false, 3), Some(1));
+ // C under A: [C, A, B]. C over A: [A, C, B].
+ assert_eq!(reorder_target(2, Some(0), false, 3), Some(0));
+ assert_eq!(reorder_target(2, Some(0), true, 3), Some(1));
+ // The Smart Filters row: on top.
+ assert_eq!(reorder_target(0, None, false, 3), Some(2));
+ // Next to where it already is, or on itself: nothing to do.
+ assert_eq!(reorder_target(1, Some(2), false, 3), None);
+ assert_eq!(reorder_target(1, Some(0), true, 3), None);
+ assert_eq!(reorder_target(1, Some(1), true, 3), None);
+ assert_eq!(reorder_target(2, None, true, 3), None);
+ assert_eq!(reorder_target(0, None, true, 0), None);
+ }
+
+ #[test]
+ fn shape_layers_and_smart_objects_carry_a_thumbnail_badge() {
+ let [pixel, shape, smart] = layers();
+ assert_eq!(thumb_badge_kind(&pixel), None);
+ assert_eq!(thumb_badge_kind(&shape), Some(ThumbBadge::Shape), "#4584");
+ assert_eq!(thumb_badge_kind(&smart), Some(ThumbBadge::Smart));
+ }
+
+ /// The rects `thumb_badge` fills for `l` over `thumb`, with their colours.
+ fn filled(l: &Layer, thumb: Rect) -> Vec<(Rect, Color32)> {
+ let l = l.clone();
+ let mut h = egui_kittest::Harness::new_ui(move |ui| thumb_badge(ui, &l, thumb));
+ h.run();
+ let badge = thumb_badge_rect(thumb).expand(0.5);
+ let rects = h.output().shapes.iter().filter_map(|s| match &s.shape {
+ egui::Shape::Rect(r) if badge.contains_rect(r.rect) && r.fill != Color32::TRANSPARENT => Some((r.rect, r.fill)),
+ _ => None,
+ });
+ rects.collect()
+ }
+
+ /// #4584: a shape layer's thumbnail shows a path with four anchor points in its corner.
+ #[test]
+ fn shape_badge_paints_a_path_with_an_anchor_on_each_corner() {
+ let [pixel, shape, smart] = layers();
+ let thumb = Rect::from_min_size(pos2(20.0, 20.0), vec2(34.0, 34.0));
+ let t = Tokens::get(&egui::Context::default());
+ let frame = thumb_badge_rect(thumb);
+ assert!(frame.right() > thumb.right() && frame.bottom() > thumb.bottom(), "over the bottom-right corner");
+ assert!(filled(&pixel, thumb).is_empty(), "a pixel layer has no badge");
+
+ let drawn = filled(&shape, thumb);
+ assert!(drawn.contains(&(frame, t.field)), "the badge's frame");
+ let anchors: Vec<Rect> = drawn.iter().filter(|(_, c)| *c == t.icon).map(|(r, _)| *r).collect();
+ let path = frame.shrink(SHAPE_PATH_INSET);
+ let corners = [path.left_top(), path.right_top(), path.right_bottom(), path.left_bottom()];
+ assert_eq!(anchors.iter().map(Rect::center).collect::<Vec<_>>(), corners);
+ for a in &anchors {
+ assert_eq!(a.size(), vec2(SHAPE_ANCHOR, SHAPE_ANCHOR));
+ assert!(frame.shrink(1.0).contains_rect(*a), "inside the frame's border");
+ }
+
+ // The smart-object badge keeps its frame and draws no anchors.
+ let drawn = filled(&smart, thumb);
+ assert!(drawn.contains(&(frame, t.field)));
+ assert!(drawn.iter().all(|(_, c)| *c != t.icon));
+ }
+ }
diff --cc crates/ui-egui/src/smart_ui/editor_tests.rs
index c007b2ca6,000000000..c007b2ca6
mode 100644,000000..100644
--- a/crates/ui-egui/src/smart_ui/editor_tests.rs
+++ b/crates/ui-egui/src/smart_ui/editor_tests.rs