PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Properties ▸ Layer Mask: add Photoshop's Refine row (#2425) (#2639)
Jason0c907fb7f921
diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 61c26a0c1..d8a91bba6 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -1319,6 +1319,7 @@Record ● a sequence of edits, then play ▶ it on any document. Zaznamenejte ● posloupnost úprav a pak ji přehrajte ▶ na libovolném dokumentu.Red ČervenáRedefine style by current selection Předefinovat styl podle aktuálního výběru+ Refine UpřesnitReflected Gradient Zrcadlený přechodRegistration Marks Soutiskové značkyRegular Obyčejnédiff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 9c5284cbf..b6ab73ce9 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -1303,6 +1303,7 @@Record ● a sequence of edits, then play ▶ it on any document. Zeichne ● eine Folge von Bearbeitungen auf und gib sie ▶ auf jedem Dokument wieder.Red RotRedefine style by current selection Stil anhand der aktuellen Auswahl neu definieren+ Refine VerfeinernReflected Gradient Reflektierter VerlaufRegistration Marks PassmarkenRegular Regulärdiff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 33ac5903b..6c2b7adf7 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -2789,6 +2789,7 @@Reduce Noise Μείωση θορύβουReduce Noise… Μείωση θορύβου…Reflected Ανακλώμενο+ Refine ΒελτίωσηReflected Gradient Ανακλώμενη διαβάθμισηRegistration Marks Σημάδια συμπτώσεωςRegular Κανονικόdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 9927431dc..1de20ac83 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -1304,6 +1304,7 @@Record ● a sequence of edits, then play ▶ it on any document. Graba ● una secuencia de ediciones y reprodúcela ▶ en cualquier documento.Red RojoRedefine style by current selection Redefinir el estilo con la selección actual+ Refine RefinarReflected Gradient Degradado reflejadoRegistration Marks Marcas de registroRegular Normaldiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex bd563985a..e71f7cad0 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -1288,6 +1288,7 @@Record ● a sequence of edits, then play ▶ it on any document. Enregistrez ● une suite de modifications, puis rejouez-la ▶ sur n'importe quel document.Red RougeRedefine style by current selection Redéfinir le style d'après la sélection actuelle+ Refine AffinerReflected Gradient Dégradé réfléchiRegistration Marks Repères de montageRegular Normaldiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex d07f9a097..71fb01947 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -1282,6 +1282,7 @@Record ● a sequence of edits, then play ▶ it on any document. Rekam ● urutan pengeditan, lalu putar ▶ di dokumen apa saja.Red MerahRedefine style by current selection Definisikan ulang gaya dengan seleksi saat ini+ Refine PerhalusReflected Gradient Gradien PantulanRegistration Marks Tanda RegistrasiRegular Regulerdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex dfef795cf..c03710735 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -1303,6 +1303,7 @@Record ● a sequence of edits, then play ▶ it on any document. Registra ● una sequenza di modifiche, poi riproduci ▶ su qualsiasi documento.Red RossoRedefine style by current selection Ridefinisci stile con selezione corrente+ Refine RifinisciReflected Gradient Sfumatura riflessaRegistration Marks Crocini di registroRegular Normalediff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex b216a1084..235f66378 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -1309,6 +1309,7 @@Record ● a sequence of edits, then play ▶ it on any document. 一連の編集を記録 ● し、任意のドキュメントで再生 ▶ できます。Red 赤Redefine style by current selection 現在の選択でスタイルを再定義+ Refine 調整Reflected Gradient 反射形グラデーションRegistration Marks 見当合わせマークRegular レギュラーdiff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex 6e66c634a..ca0923b7d 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -1280,6 +1280,7 @@Record ● a sequence of edits, then play ▶ it on any document. 연속된 편집을 ● 기록한 다음 원하는 문서에서 ▶ 재생하세요.Red 빨강Redefine style by current selection 현재 선택으로 스타일 재정의+ Refine 다듬기Reflected Gradient 반사 그레이디언트Registration Marks 맞춤 표시Regular 보통diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex 062280f22..f32b2398f 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -1297,6 +1297,7 @@Record ● a sequence of edits, then play ▶ it on any document. Neem ● een reeks bewerkingen op en speel deze ▶ af op elk document.Red RoodRedefine style by current selection Stijl opnieuw definiëren op basis van huidige selectie+ Refine VerfijnenReflected Gradient Gespiegeld verloopRegistration Marks PastekensRegular Normaaldiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 237f52408..797a79a93 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -1304,6 +1304,7 @@Record ● a sequence of edits, then play ▶ it on any document. Nagraj ● sekwencję edycji, a następnie odtwórz ▶ ją na dowolnym dokumencie.Red CzerwonyRedefine style by current selection Zdefiniuj styl ponownie na podstawie bieżącego zaznaczenia+ Refine DopracujReflected Gradient Gradient odbityRegistration Marks Znaczniki pasowaniaRegular Zwykładiff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 513b7df19..d222d86fb 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -1287,6 +1287,7 @@Record ● a sequence of edits, then play ▶ it on any document. Grave ● uma sequência de edições e depois reproduza-a ▶ em qualquer documento.Red VermelhoRedefine style by current selection Redefinir o estilo pela seleção atual+ Refine RefinarReflected Gradient Degradê refletidoRegistration Marks Marcas de registroRegular Regulardiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 816a4504b..62b7c28fd 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -2081,6 +2081,7 @@Quality КачествоRecent НедавниеReconstruct Восстановление+ Refine УточнениеRegistration Marks Кресты приводкиRegular ОбычныйRemove stop Удалить ограничительdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex a5e4fcbed..96eabeca0 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -2642,6 +2642,7 @@ fontWeight Italic КурсивнийPrevent auto-nesting in and out of Artboards and Frames Запобігати автоматичному вкладенню в монтажні області та кадри або виходу з нихQuick Actions Швидкі діїRadial Gradient Радіальний градієнт+ Refine УточненняReflected Gradient Відбитий градієнтReset to defaults Скинути до типових значеньSearch commands Пошук командdiff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 98b4cb265..52a4f5009 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -1313,6 +1313,7 @@Record ● a sequence of edits, then play ▶ it on any document. 录制 ● 一系列编辑,然后在任意文档上播放 ▶。Red 红色Redefine style by current selection 用当前选区重新定义样式+ Refine 调整Reflected Gradient 对称渐变Registration Marks 套准标记Regular 常规diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex 098400245..9f8ac1f94 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -1310,6 +1310,7 @@Record ● a sequence of edits, then play ▶ it on any document. 錄製 ● 一連串編輯,然後在任何文件上播放 ▶。Red 紅色Redefine style by current selection 依目前選取項目重新定義樣式+ Refine 調整Reflected Gradient 反射性漸層Registration Marks 對齊標記Regular 標準diff --git a/crates/ui-egui/src/mask_props_ui.rs b/crates/ui-egui/src/mask_props_ui.rsindex efbf34464..bfbeeb509 100644--- a/crates/ui-egui/src/mask_props_ui.rs+++ b/crates/ui-egui/src/mask_props_ui.rs@@ -3,8 +3,13 @@use photocraft_doc::Layer;use serde_json::json;+use crate::props_layout::COL_GAP;+use crate::theme::{self, Tokens};use crate::{PhotocraftApp, widgets};+/// Image › Adjustments › Invert, which inverts a targeted layer mask in place (#780).+const INVERT: &str = "image.adjustments.invert";+pub fn targeted(app: &PhotocraftApp, layer: &Layer) -> bool {app.ui.mask_target && !app.ui.vector_mask_target && layer.mask.is_some()}@@ -50,5 +55,39 @@ pub fn properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, layer: &Layer) {}}}+ refine_row(app, ui);});}++/// Photoshop's Refine row below Density and Feather: Select and Mask… and Color Range… open their+/// dialogs (the mask is Select and Mask's input when nothing is selected), and Invert flips the+/// mask. Invert names its target itself (`"target":"mask"`) rather than leaning on the shell's+/// target routing, so it edits the mask and never the layer's pixels (#1137).+fn refine_row(app: &mut PhotocraftApp, ui: &mut egui::Ui) {+ let refine: [(&str, &str); 3] = [(tl!("Select and Mask…"), "select.selectAndMask"), (tl!("Color Range…"), "select.colorRange"), (tl!("Invert"), INVERT)];+ ui.add_space(theme::ROW_GAP / 2.0);+ ui.label(egui::RichText::new(tl!("Refine")).color(Tokens::get(ui.ctx()).text_dim));+ ui.add_space(theme::ROW_GAP / 2.0);+ let avail = ui.available_width();+ // Two buttons to a row in a wide panel, as Quick Actions do; a narrow one stacks them.+ let cols = if avail >= 360.0 { 2 } else { 1 };+ for row in refine.chunks(cols) {+ // A short last row (or a lone button) still spans the panel.+ let w = ((avail - (row.len() - 1) as f32 * COL_GAP) / row.len() as f32).floor();+ ui.horizontal(|ui| {+ ui.spacing_mut().item_spacing.x = COL_GAP;+ for &(label, id) in row {+ // Greyed when its command can't run, by the same rule as the menu item.+ let enabled = crate::menus::is_enabled(app, id);+ if ui.add_enabled_ui(enabled, |ui| widgets::secondary_button(ui, label, w).clicked()).inner {+ let params = if id == INVERT { json!({"target": "mask"}) } else { json!({}) };+ if let Err(error) = crate::menus::invoke(app, ui.ctx(), id, params) {+ app.ui.status = error;+ app.ui.status_error = true;+ }+ }+ }+ });+ ui.add_space(theme::ROW_GAP);+ }+}diff --git a/crates/ui-egui/src/mask_props_ui_tests.rs b/crates/ui-egui/src/mask_props_ui_tests.rsindex 1c3b92767..d65ac275a 100644--- a/crates/ui-egui/src/mask_props_ui_tests.rs+++ b/crates/ui-egui/src/mask_props_ui_tests.rs@@ -116,3 +116,67 @@ fn uncommitted_mask_number_stays_with_its_layer() {let doc = &h.state().session.active().unwrap().doc;assert_ne!(doc.layer(first).unwrap().mask.as_ref().unwrap().density, 0.5, "uncommitted expression is not applied on selection change");}++/// Document-wide row of mask coverage (or of the layer's own red channel) across the middle.+fn row(h: &Harness<'_, PhotocraftApp>, of_mask: bool) -> Vec<f32> {+ let s = h.state().session.active().unwrap();+ let layer = s.doc.layer(s.active_layer.unwrap()).unwrap();+ let surface = if of_mask { &layer.mask.as_ref().unwrap().surface } else { layer.surface().unwrap() };+ (0..64).map(|x| surface.sample_channel(x, 32, 0)).collect()+}++#[test]+fn refine_row_offers_select_and_mask_color_range_and_invert() {+ for theme in [crate::theme::ThemeKind::Pro, crate::theme::ThemeKind::Studio] {+ for adjustment in [false, true] {+ let mut h = harness(adjustment, theme);+ for label in ["Refine", "Select and Mask…", "Color Range…", "Invert"] {+ assert!(h.query_all_by_label(label).next().is_some(), "{theme:?}, adjustment={adjustment}: no {label}");+ }+ h.state_mut().ui.mask_target = false;+ h.run_steps(4);+ assert!(h.query_all_by_label("Select and Mask…").next().is_none(), "{theme:?}: the Refine row belongs to the mask target");+ assert!(h.query_all_by_label("Refine").next().is_none());+ }+ }+}++#[test]+fn refine_invert_inverts_the_mask_and_leaves_the_layer_alone() {+ let mut h = harness(false, crate::theme::ThemeKind::Pro);+ let gradient = |target: &str| json!({"from": [0, 0], "to": [63, 0], "colors": ["#000000", "#ffffff"], "target": target});+ // Pixels and mask both vary, so inverting the wrong surface shows up either way (#1137).+ h.state_mut().session.execute("paint.gradient", gradient("pixels")).unwrap();+ h.state_mut().session.execute("paint.gradient", gradient("mask")).unwrap();+ h.run_steps(3);+ let (mask_before, pixels_before) = (row(&h, true), row(&h, false));+ assert!(mask_before[8] < mask_before[56], "the mask must vary across the document");+ let steps = h.state().session.active().unwrap().history.past_len();+ h.get_by_label("Invert").click();+ h.run_steps(3);+ for (x, (before, after)) in mask_before.iter().zip(row(&h, true)).enumerate() {+ assert!((1.0 - before - after).abs() < 0.01, "mask at x={x}: {before} should invert to {}, got {after}", 1.0 - before);+ }+ assert_eq!(row(&h, false), pixels_before, "the layer's pixels must not be touched");+ assert_eq!(h.state().session.active().unwrap().history.past_len(), steps + 1, "one undoable step");+ h.state_mut().run("edit.undo", json!({})).unwrap();+ assert_eq!(row(&h, true), mask_before, "Undo restores the mask");+}++#[test]+fn refine_row_opens_the_select_and_mask_and_color_range_dialogs() {+ for (label, open) in [("Select and Mask…", "select.refineEdge"), ("Color Range…", crate::color_range_ui::COMMAND)] {+ let mut h = harness(false, crate::theme::ThemeKind::Pro);+ assert!(h.state().ui.dialogs.is_empty());+ h.get_by_label(label).click();+ h.run_steps(3);+ let dialogs = &h.state().ui.dialogs;+ assert_eq!(dialogs.len(), 1, "{label} opens one dialog");+ let fields = &dialogs[0].fields;+ let opened = fields.get("__command").and_then(Value::as_str).unwrap_or(crate::color_range_ui::COMMAND);+ assert_eq!(opened, open, "{label} opened {opened}");+ if open == crate::color_range_ui::COMMAND {+ assert!(crate::color_range_ui::owns(fields), "the Color Range dialog, not the generic one");+ }+ }+}