Merge upstream/main into fix/vp-stamp-tearoff

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
vangel76andClaude Opus 5.5 committed 2026-10-11 10:56:33 +02:00
commit 96dd1956cc
31 files changed
+559 -59

No files matched your search

+16
View File
@@ -361,6 +361,7 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
})),
inbox: None,
open_url: Some(Box::new(|url: &str| open::that(url).map_err(|e| e.to_string()))),
beep: Some(platform_beep),
clipboard_set_image: Some({
let clip = clip.clone();
Box::new(move |w: u32, h: u32, px: &[u8]| {
@@ -407,6 +408,21 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
}
}
/// Preferences ▸ General ▸ Beep When Done: the platform's default information beep.
fn platform_beep() {
#[cfg(target_os = "windows")]
{
let _ = winsafe::MessageBeep(winsafe::co::MBP::OK);
}
#[cfg(not(target_os = "windows"))]
{
// No beep API among this app's other platforms' dependencies: write the terminal bell
// (audible when launched from a terminal, which is the same cue macOS terminals use).
use std::io::Write as _;
let _ = std::io::stdout().write_all(b"\x07").and_then(|()| std::io::stdout().flush());
}
}
/// Flat-image import via photocraft-codecs (kept for reference/tests; the app uses photocraft-io).
#[allow(dead_code)]
pub fn import_flat(name: &str, bytes: &[u8]) -> Result<Document, String> {
+4
View File
@@ -68,7 +68,11 @@ pub fn replayable(id: &str) -> bool {
// Again journals its concrete transform too; recording the wrapper would replay it twice.
id == "actions.play"
|| (!id.starts_with("actions.")
// Browse executes its steps through Session::execute, so those concrete
// commands are already journaled. Recording the wrapper as well replays
// every script edit twice (#3057).
&& id != "edit.transform.again"
&& id != "file.scripts.browse"
&& (shell_view_command(id) || shell_save_command(id) || crate::commands::find(id).is_some_and(|c| c.journal)))
}
+32
View File
@@ -54,6 +54,38 @@ fn browse_runs_a_script_file() {
assert_eq!(r["results"].as_array().unwrap().len(), 1);
}
#[test]
fn recording_browse_script_captures_each_effect_once() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 12, "height": 8})).unwrap();
s.execute("actions.record", json!({"name": "Rotate script"})).unwrap();
let run = s.execute("file.scripts.browse", json!({"steps": [["image.imageRotation.90cw", {}]]})).unwrap();
assert_eq!(run["ok"], true);
assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
let done = s.execute("actions.stop", json!({})).unwrap();
assert_eq!(done["steps"], 1, "Browse must not be recorded a second time");
let recorded = s.execute("actions.get", json!({"action": "Rotate script"})).unwrap();
assert_eq!(recorded["steps"], json!([["image.imageRotation.90cw", {}]]));
s.execute("image.imageRotation.90ccw", json!({})).unwrap();
assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (12, 8));
let replay = s.execute("actions.play", json!({"action": "Rotate script"})).unwrap();
assert_eq!(replay["ran"], 1);
assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
}
#[test]
fn standalone_browse_script_still_runs_and_journals_concrete_commands() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 12, "height": 8})).unwrap();
let start = s.journal.len();
let result = s.execute("file.scripts.browse", json!({"steps": [["image.imageRotation.90cw", {}]]})).unwrap();
assert_eq!(result["ok"], true);
assert_eq!(s.journal.len(), start + 2, "the child and Browse retain their diagnostic journal entries");
assert_eq!(s.journal[start].0, "image.imageRotation.90cw");
assert_eq!((s.active().unwrap().doc.size.width, s.active().unwrap().doc.size.height), (8, 12));
}
#[test]
fn script_events_fire_on_new_and_close() {
let mut s = Session::new();
+21 -1
View File
@@ -127,13 +127,33 @@ fn edit_rgba(s: &mut Session, label: &str, grow: i32, f: impl FnOnce(&mut Vec<[f
fn apply_mask(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, p)?;
s.edit("Apply Layer Mask", |doc, _| {
// Applying a feathered mask must bake the same softened coverage the compositor
// displays. LayerMask::values_into accounts for density but not feather (#3044).
let feathered = {
let layer = doc.layer(id).ok_or(EngineError::NoLayer(id))?;
if layer.mask.as_ref().is_some_and(|m| m.enabled && photocraft_compose::masks::feather_sigma(m.feather) > 0.0) {
// Do not bake an independent vector mask that remains attached after Apply.
let mut mask_only = layer.clone();
mask_only.vector_mask = None;
// Cover off-canvas pixels too: outside its area the combined mask is only the
// mask's default value, which would hide moved-off content (#3043).
let area = layer.surface().map_or(doc.bounds(), |surf| doc.bounds().union(&surf.content_bounds()));
photocraft_compose::masks::combined_mask(&mask_only, area)
} else {
None
}
};
let mask = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask.take().ok_or_else(|| other("the layer has no layer mask"))?;
let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
let r = surf.content_bounds();
if !r.is_empty() {
let mut px = read_rgba(surf, r);
let mut m = Vec::new();
mask.values_into(r, &mut m);
if let Some(ref softened) = feathered {
softened.read_region_into(r, &mut m);
} else {
mask.values_into(r, &mut m);
}
for (q, k) in px.iter_mut().zip(&m) {
q[3] *= k;
}
@@ -580,6 +580,48 @@ fn transfer_effects_moves_or_copies_between_layers() {
assert_eq!(s.active().unwrap().history.past_len(), steps);
}
#[test]
fn applying_a_feathered_mask_preserves_its_soft_composite() {
for depth in DEPTHS {
let mut s = session(depth, "rgb");
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 1.0]);
s.edit("mask fixture", |doc, active| {
let mut mask = LayerMask::hide_all();
mask.surface.fill_rect(Rect::new(0, 0, 20, 30), &[1.0]);
mask.feather = 2.0;
doc.layer_mut(active.unwrap()).unwrap().mask = Some(mask);
Ok(())
})
.unwrap();
let before = photocraft_compose::flatten(doc(&s)).px;
assert!(before[15 * 40 + 19][3] > 0.0 && before[15 * 40 + 19][3] < 1.0, "mask must start with a soft edge");
s.execute("layer.layerMask.apply", json!({})).unwrap();
assert!(active(&s).mask.is_none(), "Apply removes the pixel mask");
let after = photocraft_compose::flatten(doc(&s)).px;
for (a, b) in before.iter().zip(&after) {
assert!((a[3] - b[3]).abs() <= 1.0 / 255.0 + 1e-5, "depth {depth}: alpha {a:?} became {b:?}");
}
assert!(s.undo());
assert!(active(&s).mask.as_ref().is_some_and(|m| m.feather == 2.0));
}
}
#[test]
fn applying_a_disabled_feathered_mask_does_not_hide_pixels() {
let mut s = session(8, "rgb");
paint(&mut s, |_, _| [0.7, 0.2, 0.1, 1.0]);
s.edit("disabled mask", |doc, active| {
let mut mask = LayerMask::hide_all();
mask.feather = 3.0;
mask.enabled = false;
doc.layer_mut(active.unwrap()).unwrap().mask = Some(mask);
Ok(())
})
.unwrap();
s.execute("layer.layerMask.apply", json!({})).unwrap();
assert_eq!(active(&s).surface().unwrap().rgba(20, 15)[3], 1.0);
}
#[test]
fn from_transparency_preserves_mask_coverage_outside_the_canvas() {
for depth in DEPTHS {
@@ -597,3 +639,21 @@ fn from_transparency_preserves_mask_coverage_outside_the_canvas() {
}
}
}
#[test]
fn applying_a_feathered_mask_keeps_off_canvas_pixels_it_reveals() {
let mut s = session(8, "rgb");
paint(&mut s, |_, _| [1.0, 0.0, 0.0, 1.0]);
s.execute("layer.translate", json!({"dx": 20})).unwrap();
s.edit("mask fixture", |doc, active| {
// Reveal the whole layer, including the 20 px now past the right edge.
let mut mask = LayerMask::hide_all();
mask.surface.fill_rect(Rect::new(0, 0, 60, 30), &[1.0]);
mask.feather = 2.0;
doc.layer_mut(active.unwrap()).unwrap().mask = Some(mask);
Ok(())
})
.unwrap();
s.execute("layer.layerMask.apply", json!({})).unwrap();
assert_eq!(active(&s).surface().unwrap().rgba(52, 15)[3], 1.0, "off-canvas pixel stays visible");
}
-2
View File
@@ -981,7 +981,6 @@ pub const SECTIONS: [(&str, &str); 18] = [
/// preference is read anywhere outside `prefs.rs`, and while an unlisted one is read nowhere.
pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[
"general.colorPicker",
"general.beepWhenDone",
"general.alwaysCreateSmartObjectsWhenPlacing",
"general.animatedZoom",
"general.zoomResizesWindows",
@@ -1008,7 +1007,6 @@ pub const HIDDEN_UNTIL_IMPLEMENTED: &[&str] = &[
"type.missingGlyphProtection",
"type.showFontNamesInEnglish",
"type.textEngine",
"type.fontPreview",
"type.recentFonts",
"enhancedControls.scrubbySliderAcceleration",
"enhancedControls.touchGestures",
+11 -1
View File
@@ -511,7 +511,17 @@ pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
}
LiveShape::Ellipse { rect } => LiveShape::Ellipse { rect: r(rect) },
LiveShape::Polygon { rect, sides, star_ratio } => LiveShape::Polygon { rect: r(rect), sides, star_ratio },
LiveShape::Line { from, to, weight } => LiveShape::Line { from: pt(from), to: pt(to), weight },
LiveShape::Line { from, to, weight } => {
// Live-shape edits regenerate the line's filled bar from its parameters.
// Keep the weight in sync with a positive scale of the path, or an
// unchanged endpoint edit unexpectedly restores the old thickness (#3063).
// A line's width scales perpendicular to its direction.
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
let old_length = dx.hypot(dy);
let new_length = (dx * m0).hypot(dy * m3);
let width_scale = if old_length > 0.0 && new_length > 0.0 { m0 * m3 * old_length / new_length } else { m0.min(m3) };
LiveShape::Line { from: pt(from), to: pt(to), weight: weight * width_scale }
}
})
}
// Flips and 90° turns keep rectangles, ellipses and lines live (Image Rotation): the new
@@ -0,0 +1,49 @@
use photocraft_engine::Session;
use serde_json::json;
fn live_line_info(s: &mut Session, layer: u64) -> serde_json::Value {
s.execute("shape.info", json!({"layer": layer})).unwrap()
}
#[test]
fn live_line_keeps_scaled_thickness_after_endpoint_edit() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 128, "height": 128, "background": "transparent"})).unwrap();
let layer = s.execute("shape.create", json!({"kind": "line", "from": [10,20], "to": [30,20], "weight": 4})).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"transform": [2,0,0,2,0,0]})).unwrap();
let after_scale = live_line_info(&mut s, layer);
assert_eq!(after_scale["bounds"], json!([20, 36, 40, 8]));
assert_eq!(after_scale["live"]["weight"], json!(8.0));
s.execute("shape.edit", json!({"to": [60,40]})).unwrap();
let after_edit = live_line_info(&mut s, layer);
assert_eq!(after_edit["bounds"], after_scale["bounds"]);
assert_eq!(after_edit["path"], after_scale["path"]);
assert_eq!(after_edit["live"]["weight"], json!(8.0));
}
#[test]
fn translating_live_lines_leaves_their_weight_unchanged() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 128, "height": 128, "background": "transparent"})).unwrap();
let layer = s.execute("shape.create", json!({"kind": "line", "from": [10,20], "to": [30,20], "weight": 4})).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"move": [10,10]})).unwrap();
let after_move = live_line_info(&mut s, layer);
s.execute("shape.edit", json!({"to": [40,30]})).unwrap();
let after_edit = live_line_info(&mut s, layer);
assert_eq!(after_edit["path"], after_move["path"]);
assert_eq!(after_edit["live"]["weight"], json!(4.0));
}
#[test]
fn nonuniform_scaling_uses_the_direction_perpendicular_to_the_line() {
let mut s = Session::new();
s.execute("file.new", json!({"width": 128, "height": 128, "background": "transparent"})).unwrap();
let horizontal = s.execute("shape.create", json!({"kind": "line", "from": [10,20], "to": [30,20], "weight": 4})).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"transform": [2,0,0,1,0,0]})).unwrap();
assert_eq!(live_line_info(&mut s, horizontal)["live"]["weight"], json!(4.0));
let vertical = s.execute("shape.create", json!({"kind": "line", "from": [50,10], "to": [50,30], "weight": 4})).unwrap()["layer"].as_u64().unwrap();
s.execute("shape.edit", json!({"transform": [2,0,0,1,0,0]})).unwrap();
assert_eq!(live_line_info(&mut s, vertical)["live"]["weight"], json!(8.0));
}
+68 -24
View File
@@ -6,6 +6,7 @@ use std::sync::PoisonError;
use egui::{ColorImage, Rect, TextureHandle, TextureOptions, pos2, vec2};
use photocraft_color::{ColorMode, PixelFormat, SampleType};
use photocraft_doc::TextLayer;
use photocraft_engine::prefs::FontPreview;
use photocraft_geom::Affine;
const SAMPLE: &str = "AaBbCc";
@@ -13,16 +14,44 @@ const SAMPLE: &str = "AaBbCc";
const ARABIC_CORE: [char; 4] = ['\u{627}', '\u{644}', '\u{645}', '\u{639}'];
/// Short, recognisable, and joins letters, so it shows the face's shaping.
const ARABIC_SAMPLE: &str = "أبجد هوز";
/// The Latin and Arabic sample widths and the sample height at the menu's medium (18 pt).
const WIDTH: f32 = 100.0;
const ARABIC_WIDTH: f32 = 72.0;
const GAP: f32 = 6.0;
const HEIGHT: f32 = 24.0;
/// The medium point size the widths above are measured at.
const MEDIUM: f32 = 18.0;
const CACHE_LIMIT: usize = 128;
const CACHE_ID: &str = "font-menu-previews";
/// Family, display scale, and the font database generations, so a family installed or fetched
/// (served fonts) after its first miss gets a sample once it is available.
type Key = (String, u32, (u64, u64));
/// A width or height measured at 18 pt, scaled to the sample's point size.
fn scaled(v: f32, size: f32) -> f32 {
(v * size / MEDIUM).round()
}
/// The Latin sample's `[width, height]` box for a point size: [`WIDTH`]×[`HEIGHT`] at 18 pt (the
/// menu's medium), proportional otherwise.
fn box_for(size: f32) -> [f32; 2] {
[scaled(WIDTH, size), scaled(HEIGHT, size)]
}
/// The font menu's sample geometry for Preferences ▸ Type ▸ Font Preview Size: the sample's point
/// size and its Latin box; `None` when the preview is off.
pub(crate) fn sample(preview: FontPreview) -> Option<(f32, [f32; 2])> {
let size = match preview {
FontPreview::Off => return None,
FontPreview::Small => 14.0,
FontPreview::Medium => MEDIUM,
FontPreview::Large => 24.0,
FontPreview::ExtraLarge => 32.0,
FontPreview::Huge => 40.0,
};
Some((size, box_for(size)))
}
/// Family, display scale, the font database generations (so a family installed or fetched
/// (served fonts) after its first miss gets a sample once it is available) and the point size.
type Key = (String, u32, (u64, u64), u32);
#[derive(Clone)]
struct Samples {
latin: TextureHandle,
@@ -48,15 +77,15 @@ fn sample_texts(chars: &[char]) -> (String, Option<&'static str>) {
(SAMPLE.into(), arabic.then_some(ARABIC_SAMPLE))
}
fn render(engine: &mut photocraft_text::TextEngine, family: &str, text: &str, slot: f32, scale: u32) -> Option<ColorImage> {
fn render(engine: &mut photocraft_text::TextEngine, family: &str, text: &str, slot: f32, scale: u32, size: f32) -> Option<ColorImage> {
if text.is_empty() {
return None;
}
let layer = TextLayer { text: text.into(), font_family: family.into(), size_pt: 18.0 * scale as f32, ..Default::default() };
let layer = TextLayer { text: text.into(), font_family: family.into(), size_pt: size * scale as f32, ..Default::default() };
let layout = engine.layout(&layer, 72.0);
let bounds = layout.bounds()?;
let width = (slot as u32 * scale) as usize;
let height = (HEIGHT as u32 * scale) as usize;
let height = (scaled(HEIGHT, size) as u32 * scale) as usize;
let transform = Affine::translate(f64::from(-bounds[0]), f64::from((height as f32 - (bounds[3] - bounds[1])) / 2.0 - bounds[1]));
// Reject oversized ink before the rasterizer allocates a surface (malformed installed fonts).
let ink = photocraft_text::render::ink_rect(&layout, &transform);
@@ -69,38 +98,38 @@ fn render(engine: &mut photocraft_text::TextEngine, family: &str, text: &str, sl
Some(ColorImage::from_rgba_unmultiplied([width, height], &rgba.into_iter().flat_map(|p| [255, 255, 255, p[3]]).collect::<Vec<_>>()))
}
fn images(engine: &mut photocraft_text::TextEngine, family: &str, scale: u32) -> Option<SampleImages> {
fn images(engine: &mut photocraft_text::TextEngine, family: &str, scale: u32, size: f32) -> Option<SampleImages> {
// Unknown/unreadable families keep their plain menu label, rather than a misleading fallback.
if !engine.fonts.has_family(family) {
return None;
}
let (latin, arabic) = sample_texts(&engine.fonts.charmap(family, 400, false));
let latin = render(engine, family, &latin, WIDTH, scale)?;
let arabic = arabic.and_then(|text| render(engine, family, text, ARABIC_WIDTH, scale));
let latin = render(engine, family, &latin, scaled(WIDTH, size), scale, size)?;
let arabic = arabic.and_then(|text| render(engine, family, text, scaled(ARABIC_WIDTH, size), scale, size));
Some(SampleImages { latin, arabic })
}
fn key(ctx: &egui::Context, family: &str) -> Key {
fn key(ctx: &egui::Context, family: &str, size: f32) -> Key {
let scale = ctx.pixels_per_point().ceil().clamp(1.0, 4.0) as u32;
(family.to_owned(), scale, (photocraft_text::fonts::generation(), photocraft_text::served::generation()))
(family.to_owned(), scale, (photocraft_text::fonts::generation(), photocraft_text::served::generation()), size as u32)
}
/// Width a row reserves for its samples: wider once a painted row showed the family covers
/// Arabic, so the label truncates before the samples. Never renders, so rows scrolled out of
/// view cost nothing.
pub(crate) fn slot_width(ctx: &egui::Context, family: &str) -> f32 {
let key = key(ctx, family);
pub(crate) fn slot_width(ctx: &egui::Context, family: &str, size: f32) -> f32 {
let key = key(ctx, family, size);
let arabic = ctx.data_mut(|d| {
let cache = d.get_temp_mut_or_default::<Cache>(egui::Id::new(CACHE_ID));
cache.0.iter().any(|(k, samples)| k == &key && samples.as_ref().is_some_and(|s| s.arabic.is_some()))
});
if arabic { WIDTH + GAP + ARABIC_WIDTH } else { WIDTH }
if arabic { scaled(WIDTH, size) + GAP + scaled(ARABIC_WIDTH, size) } else { scaled(WIDTH, size) }
}
pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect) {
pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect, size: f32) {
let ctx = ui.ctx();
let scale = ctx.pixels_per_point().ceil().clamp(1.0, 4.0) as u32;
let key = key(ctx, family);
let key = key(ctx, family, size);
let id = egui::Id::new(CACHE_ID);
let cached = ctx.data_mut(|d| {
let cache = d.get_temp_mut_or_default::<Cache>(id);
@@ -111,7 +140,7 @@ pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect) {
Some(samples)
});
let samples = cached.unwrap_or_else(|| {
let samples = images(&mut photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner), family, scale).map(|img| {
let samples = images(&mut photocraft_text::shared().lock().unwrap_or_else(PoisonError::into_inner), family, scale, size).map(|img| {
let load = |image| ctx.load_texture(format!("font-sample-{family}"), image, TextureOptions::LINEAR);
Samples { latin: load(img.latin), arabic: img.arabic.map(load) }
});
@@ -131,10 +160,12 @@ pub(crate) fn paint(ui: &egui::Ui, family: &str, row: Rect) {
if let Some(samples) = samples {
let tint = crate::theme::Tokens::get(ctx).text;
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
let latin = Rect::from_min_size(pos2(row.right() - WIDTH - 8.0, row.center().y - HEIGHT / 2.0), vec2(WIDTH, HEIGHT));
let [w, h] = box_for(size);
let latin = Rect::from_min_size(pos2(row.right() - w - 8.0, row.center().y - h / 2.0), vec2(w, h));
ui.painter().image(samples.latin.id(), latin, uv, tint);
if let Some(arabic) = samples.arabic {
let rect = Rect::from_min_size(pos2(latin.left() - GAP - ARABIC_WIDTH, latin.top()), vec2(ARABIC_WIDTH, HEIGHT));
let aw = scaled(ARABIC_WIDTH, size);
let rect = Rect::from_min_size(pos2(latin.left() - GAP - aw, latin.top()), vec2(aw, h));
ui.painter().image(arabic.id(), rect, uv, tint);
}
}
@@ -145,7 +176,7 @@ mod tests {
use super::*;
fn image(engine: &mut photocraft_text::TextEngine, family: &str, scale: u32) -> Option<ColorImage> {
images(engine, family, scale).map(|i| i.latin)
images(engine, family, scale, MEDIUM).map(|i| i.latin)
}
fn charmap(text: &str) -> Vec<char> {
@@ -166,14 +197,27 @@ mod tests {
assert!(image(&mut engine, "Missing font", 1).is_none());
}
/// Preferences ▸ Type ▸ Font Preview Size: Small…Huge scale the sample, Off removes it.
#[test]
fn the_preview_size_preference_scales_the_sample() {
assert_eq!(sample(FontPreview::Off), None);
assert_eq!(sample(FontPreview::Medium), Some((18.0, [100.0, 24.0])));
let Some((_, [w, h])) = sample(FontPreview::Huge) else { panic!("Huge previews") };
assert!(w > 100.0 && h > 24.0, "Huge is bigger than Medium: {w}×{h}");
assert!(sample(FontPreview::Small).unwrap().1[0] < sample(FontPreview::ExtraLarge).unwrap().1[0], "sizes are ordered");
let mut engine = photocraft_text::TextEngine::new();
let big = images(&mut engine, "Inter", 1, 32.0).unwrap().latin;
assert_eq!(big.size, [178, 43], "the box follows the size");
}
#[test]
fn latin_only_families_get_no_arabic_sample() {
let mut engine = photocraft_text::TextEngine::new();
for family in ["Inter", "JetBrains Mono"] {
assert!(images(&mut engine, family, 1).expect("bundled").arabic.is_none(), "{family}");
assert!(images(&mut engine, family, 1, MEDIUM).expect("bundled").arabic.is_none(), "{family}");
}
assert!(images(&mut engine, "", 1).is_none());
assert!(images(&mut engine, "Missing font", 1).is_none());
assert!(images(&mut engine, "", 1, MEDIUM).is_none());
assert!(images(&mut engine, "Missing font", 1, MEDIUM).is_none());
}
#[test]
@@ -202,7 +246,7 @@ mod tests {
eprintln!("skipped: no installed family covers both Latin and Arabic");
return;
};
let images = images(&mut engine, &family, 1).expect(&family);
let images = images(&mut engine, &family, 1, MEDIUM).expect(&family);
let arabic = images.arabic.expect("Arabic sample");
assert_eq!(arabic.size, [ARABIC_WIDTH as usize, HEIGHT as usize]);
assert!(arabic.pixels.iter().any(|p| p.a() > 0), "{family}");
+9
View File
@@ -2435,6 +2435,15 @@ fontWeight Italic Kurzíva
Quick Selection found nothing there Rychlý výběr zde nic nenašel
Object Selection found nothing there — try a tighter rectangle Výběr objektu zde nic nenašel — zkuste těsnější obdélník
No subject found — try a rectangle around the object Nebyl nalezen žádný objekt — zkuste obdélník kolem objektu
Auto Erase Automatické mazání
Click the first point or press {key} to close · {del} removes a point · Esc cancels Klikněte na první bod nebo stiskněte {key} pro uzavření · {del} odebere bod · Esc zruší
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Klikněte a veďte podél okraje · kliknutím připevníte bod · {alt}-kliknutí pro rovný úsek · dvojklik uzavře
Follows only edges this close to the pointer ([ and ] change it) Sleduje jen okraje takto blízko ukazatele ([ a ] hodnotu mění)
Higher values follow only edges that contrast sharply with their surroundings Vyšší hodnoty sledují jen okraje s výrazným kontrastem k okolí
How often fastening points are placed by themselves Jak často se kotevní body umisťují samy
Scrubby Zoom Plynulá lupa
{mode} Color · {bits} bit Barva {mode} · {bits} bitů
Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels Tažením nakreslete ořez · tažením uvnitř posunete · okraje mění velikost ({ratio} poměr, {centre} střed) · Mezerník posouvá při kreslení · šipky posunují · X prohodí orientaci · {commit} potvrdí · Esc zruší
Appearance Settings… Nastavení vzhledu…
Add to favorites Přidat do oblíbených
Remove from favorites Odebrat z oblíbených
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -2473,6 +2473,11 @@ fontWeight Italic Kursiv
Quick Selection found nothing there Die Schnellauswahl hat dort nichts gefunden
Object Selection found nothing there — try a tighter rectangle Die Objektauswahl hat dort nichts gefunden — versuchen Sie ein engeres Rechteck
No subject found — try a rectangle around the object Kein Motiv gefunden — versuchen Sie ein Rechteck um das Objekt
Click the first point or press {key} to close · {del} removes a point · Esc cancels Klicke auf den ersten Punkt oder drücke {key} zum Schließen · {del} entfernt einen Punkt · Esc bricht ab
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Klicke und bewege dich entlang einer Kante · Klicken setzt einen Ankerpunkt · {alt}-Klick für ein gerades Segment · Doppelklick schließt
Follows only edges this close to the pointer ([ and ] change it) Folgt nur Kanten so nah am Zeiger ([ und ] ändern den Wert)
Higher values follow only edges that contrast sharply with their surroundings Höhere Werte folgen nur Kanten mit starkem Kontrast zur Umgebung
How often fastening points are placed by themselves Wie oft Ankerpunkte automatisch gesetzt werden
Appearance Settings… Erscheinungsbild-Einstellungen…
Add to favorites Zu Favoriten hinzufügen
Remove from favorites Aus Favoriten entfernen
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -2502,6 +2502,11 @@ fontWeight Italic Cursiva
Quick Selection found nothing there Selección rápida no encontró nada ahí
Object Selection found nothing there — try a tighter rectangle Selección de objeto no encontró nada ahí — pruebe un rectángulo más ajustado
No subject found — try a rectangle around the object No se encontró ningún sujeto — pruebe un rectángulo alrededor del objeto
Click the first point or press {key} to close · {del} removes a point · Esc cancels Haz clic en el primer punto o pulsa {key} para cerrar · {del} elimina un punto · Esc cancela
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Haz clic y sigue un borde · haz clic para fijar un punto · {alt}-clic para un segmento recto · doble clic para cerrar
Follows only edges this close to the pointer ([ and ] change it) Solo sigue bordes así de cerca del puntero ([ y ] lo cambian)
Higher values follow only edges that contrast sharply with their surroundings Los valores altos solo siguen bordes con mucho contraste con su entorno
How often fastening points are placed by themselves Con qué frecuencia se colocan puntos de fijación automáticamente
Appearance Settings… Ajustes de apariencia…
Add to favorites Añadir a favoritos
Remove from favorites Quitar de favoritos
Can't render this file because it contains an unexpected character in line 4 and column 47.
+5
View File
@@ -2852,6 +2852,11 @@ fontWeight Italic Italique
Quick Selection found nothing there La Sélection rapide n'a rien trouvé à cet endroit
Object Selection found nothing there — try a tighter rectangle La Sélection d'objet n'a rien trouvé à cet endroit — essayez un rectangle plus serré
No subject found — try a rectangle around the object Aucun sujet trouvé — essayez un rectangle autour de l'objet
Click the first point or press {key} to close · {del} removes a point · Esc cancels Cliquez sur le premier point ou appuyez sur {key} pour fermer · {del} supprime un point · Échap annule
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Cliquez, puis suivez un contour · cliquez pour fixer un point · {alt}-clic pour un segment droit · double-cliquez pour fermer
Follows only edges this close to the pointer ([ and ] change it) Ne suit que les contours aussi proches du pointeur ([ et ] le modifient)
Higher values follow only edges that contrast sharply with their surroundings Plus la valeur est élevée, plus seuls les contours très contrastés sont suivis
How often fastening points are placed by themselves Fréquence de pose automatique des points d’ancrage
Appearance Settings… Réglages d’apparence…
Add to favorites Ajouter aux favoris
Remove from favorites Retirer des favoris
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -2839,6 +2839,11 @@ fontWeight Italic Miring
Quick Selection found nothing there Seleksi Cepat tidak menemukan apa pun di sana
Object Selection found nothing there — try a tighter rectangle Seleksi Objek tidak menemukan apa pun di sana — coba persegi panjang yang lebih rapat
No subject found — try a rectangle around the object Subjek tidak ditemukan — coba persegi panjang di sekitar objek
Click the first point or press {key} to close · {del} removes a point · Esc cancels Klik titik pertama atau tekan {key} untuk menutup · {del} menghapus titik · Esc membatalkan
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Klik, lalu gerakkan di sepanjang tepi · klik untuk menancapkan titik · {alt}-klik untuk segmen lurus · klik dua kali untuk menutup
Follows only edges this close to the pointer ([ and ] change it) Hanya mengikuti tepi sedekat ini dengan penunjuk ([ dan ] mengubahnya)
Higher values follow only edges that contrast sharply with their surroundings Nilai lebih tinggi hanya mengikuti tepi yang kontras tajam dengan sekitarnya
How often fastening points are placed by themselves Seberapa sering titik penambat ditempatkan sendiri
Appearance Settings… Pengaturan Tampilan…
Add to favorites Tambahkan ke favorit
Remove from favorites Hapus dari favorit
Can't render this file because it contains an unexpected character in line 4 and column 47.
+5
View File
@@ -2504,6 +2504,11 @@ fontWeight Italic Corsivo
Quick Selection found nothing there Selezione rapida non ha trovato nulla lì
Object Selection found nothing there — try a tighter rectangle Selezione oggetto non ha trovato nulla lì — prova un rettangolo più stretto
No subject found — try a rectangle around the object Nessun soggetto trovato — prova un rettangolo attorno all'oggetto
Click the first point or press {key} to close · {del} removes a point · Esc cancels Fai clic sul primo punto o premi {key} per chiudere · {del} rimuove un punto · Esc annulla
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Fai clic e segui un bordo · fai clic per fissare un punto · {alt}-clic per un segmento dritto · doppio clic per chiudere
Follows only edges this close to the pointer ([ and ] change it) Segue solo i bordi così vicini al puntatore ([ e ] lo cambiano)
Higher values follow only edges that contrast sharply with their surroundings Valori più alti seguono solo bordi molto contrastati rispetto all’intorno
How often fastening points are placed by themselves Frequenza con cui i punti di ancoraggio vengono posti da soli
Appearance Settings… Impostazioni aspetto…
Add to favorites Aggiungi ai preferiti
Remove from favorites Rimuovi dai preferiti
Can't render this file because it contains an unexpected character in line 2515 and column 53.
+5
View File
@@ -3453,6 +3453,11 @@ fontWeight Italic 斜体
Quick Selection found nothing there クイック選択ではそこに何も見つかりませんでした
Object Selection found nothing there — try a tighter rectangle オブジェクト選択ではそこに何も見つかりませんでした — より狭い長方形で試してください
No subject found — try a rectangle around the object 被写体が見つかりません — オブジェクトを囲む長方形を試してください
Click the first point or press {key} to close · {del} removes a point · Esc cancels 最初の点をクリックするか {key} を押して閉じる · {del} で点を削除 · Esc でキャンセル
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close クリックしてエッジに沿って動かす · クリックで固定ポイント · {alt}-クリックで直線セグメント · ダブルクリックで閉じる
Follows only edges this close to the pointer ([ and ] change it) ポインターからこの距離内のエッジだけをたどる([ と ] で変更)
Higher values follow only edges that contrast sharply with their surroundings 値を大きくすると、周囲とのコントラストが強いエッジだけをたどる
How often fastening points are placed by themselves 固定ポイントが自動で置かれる頻度
Appearance Settings… 外観設定…
Add to favorites お気に入りに追加
Remove from favorites お気に入りから削除
Can't render this file because it contains an unexpected character in line 6 and column 47.
+9
View File
@@ -3013,6 +3013,15 @@ fontWeight Italic 기울임
Quick Selection found nothing there 빠른 선택으로 해당 위치에서 아무것도 찾지 못했습니다
Object Selection found nothing there — try a tighter rectangle 개체 선택으로 해당 위치에서 아무것도 찾지 못했습니다 — 더 좁은 사각형을 사용해 보세요
No subject found — try a rectangle around the object 피사체를 찾을 수 없습니다 — 개체 주위에 사각형을 그려 보세요
Auto Erase 자동 지우기
Click the first point or press {key} to close · {del} removes a point · Esc cancels 첫 점을 클릭하거나 {key}를 눌러 닫기 · {del}로 점 제거 · Esc로 취소
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close 클릭한 다음 가장자리를 따라 이동 · 클릭하여 고정점 추가 · {alt}-클릭으로 직선 구간 · 두 번 클릭하여 닫기
Follows only edges this close to the pointer ([ and ] change it) 포인터에서 이 거리 안의 가장자리만 따라감([ 및 ]로 변경)
Higher values follow only edges that contrast sharply with their surroundings 값이 높을수록 주변과 대비가 강한 가장자리만 따라감
How often fastening points are placed by themselves 고정점이 자동으로 놓이는 빈도
Scrubby Zoom 스크러비 확대/축소
{mode} Color · {bits} bit {mode} 색상 · {bits}비트
Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 드래그하여 자르기 상자 만들기 · 안쪽을 드래그하여 이동 · 가장자리로 크기 조절({ratio} 비율, {centre} 중심) · 그리는 중 Space로 이동 · 화살표로 미세 이동 · X로 방향 전환 · {commit} 적용 · Esc 취소
Appearance Settings… 화면 설정…
Add to favorites 즐겨찾기에 추가
Remove from favorites 즐겨찾기에서 제거
Can't render this file because it contains an unexpected character in line 3028 and column 53.
+45 -4
View File
@@ -732,6 +732,45 @@ mod tests {
}
}
/// `text` with each `#[cfg(test)] mod … { … }` block removed, by brace counting (the test
/// modules in this crate are well formed).
fn without_test_modules(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(at) = rest.find("#[cfg(test)]\nmod ") {
out.push_str(&rest[..at]);
let after = &rest[at..];
let Some(open) = after.find('{') else { return out };
let mut depth = 0usize;
let mut end = after.len();
for (i, c) in after[open..].char_indices() {
match c {
'{' => depth += 1,
'}' => {
depth -= 1;
if depth == 0 {
end = open + i + 1;
break;
}
}
_ => {}
}
}
rest = &after[end..];
}
out.push_str(rest);
out
}
#[test]
fn test_modules_are_cut_out_one_by_one() {
let text = "a\n#[cfg(test)]\nmod t { fn x() { tl!(\"hidden\"); } }\nb tl!(\"seen\")\n#[cfg(test)]\nmod u {}\nc";
let code = without_test_modules(text);
assert!(code.contains("tl!(\"seen\")"), "code after the first test module is scanned: {code}");
assert!(!code.contains("hidden"), "{code}");
assert!(code.starts_with("a\n") && code.ends_with("\nc"), "{code}");
}
/// Every `tl!("literal")` in the shell has an entry in each language that claims complete menus
/// (so a new label can't ship untranslated by accident). Literals that are deliberately shown as
/// they are (names, units) are listed in `KEEP_AS_IS`.
@@ -748,10 +787,12 @@ mod tests {
stack.push(path);
} else if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("lib.rs") {
let text = std::fs::read_to_string(&path).unwrap_or_default().replace("\r\n", "\n");
// Test modules aside, scan every `tl!("…")`. Cut at the test *module*: a
// `#[cfg(test)]` on a single item earlier in the file must not hide the rest.
let code = text.split("#[cfg(test)]\nmod ").next().unwrap_or("");
let mut rest = code;
// Test modules aside, scan every `tl!("…")`. Each test *module* is cut out
// on its own: cutting the file at the first one hid everything after a small
// test module early in a file (panels.rs has one at ~line 540). A
// `#[cfg(test)]` on a single item doesn't count.
let code = without_test_modules(&text);
let mut rest = code.as_str();
while let Some(at) = rest.find("tl!(\"") {
rest = &rest[at + 5..];
let mut end = 0;
+6
View File
@@ -3453,6 +3453,12 @@ cameraRaw Roughness Chropowatość
Quick Selection found nothing there Szybkie zaznaczanie nic tam nie znalazło
Object Selection found nothing there — try a tighter rectangle Zaznaczanie obiektu nic tam nie znalazło — spróbuj ciaśniejszego prostokąta
No subject found — try a rectangle around the object Nie znaleziono obiektu — spróbuj prostokąta wokół obiektu
Click the first point or press {key} to close · {del} removes a point · Esc cancels Kliknij pierwszy punkt lub naciśnij {key}, aby zamknąć · {del} usuwa punkt · Esc anuluje
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Kliknij i prowadź wzdłuż krawędzi · kliknij, aby przypiąć punkt · {alt}-klik dla prostego odcinka · kliknij dwukrotnie, aby zamknąć
Fill Screen Wypełnij ekran
Follows only edges this close to the pointer ([ and ] change it) Podąża tylko za krawędziami tak blisko wskaźnika ([ i ] zmieniają wartość)
Higher values follow only edges that contrast sharply with their surroundings Wyższe wartości podążają tylko za krawędziami mocno kontrastującymi z otoczeniem
How often fastening points are placed by themselves Jak często punkty mocujące są stawiane automatycznie
Appearance Settings… Ustawienia wyglądu…
Add to favorites Dodaj do ulubionych
Remove from favorites Usuń z ulubionych
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -2860,6 +2860,11 @@ fontWeight Italic Itálico
Quick Selection found nothing there A Seleção rápida não encontrou nada ali
Object Selection found nothing there — try a tighter rectangle A Seleção de objeto não encontrou nada ali — tente um retângulo mais justo
No subject found — try a rectangle around the object Nenhum assunto encontrado — tente um retângulo ao redor do objeto
Click the first point or press {key} to close · {del} removes a point · Esc cancels Clique no primeiro ponto ou pressione {key} para fechar · {del} remove um ponto · Esc cancela
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Clique e siga uma borda · clique para fixar um ponto · {alt}-clique para um segmento reto · clique duas vezes para fechar
Follows only edges this close to the pointer ([ and ] change it) Segue só bordas a esta distância do ponteiro ([ e ] mudam o valor)
Higher values follow only edges that contrast sharply with their surroundings Valores altos seguem só bordas com forte contraste com o entorno
How often fastening points are placed by themselves Com que frequência os pontos de fixação são colocados sozinhos
Appearance Settings… Configurações de aparência…
Add to favorites Adicionar aos favoritos
Remove from favorites Remover dos favoritos
Can't render this file because it contains an unexpected character in line 6 and column 47.
+69 -1
View File
@@ -2717,6 +2717,75 @@ fontWeight Italic Курсив
Missing delete command Отсутствует команда удаления
Invalid delete command Недопустимая команда удаления
Layer deleted, but confirmation preference could not be saved: {error} Слой удалён, но не удалось сохранить настройку подтверждения: {error}
Add a layer style Добавить стиль слоя
Add a mask (from the selection; {key} inverts) Добавить маску (из выделения; {key} инвертирует)
Add an adjustment Добавить коррекцию
Add to selection ({key}) Добавить к выделению ({key})
Adjustment visible Коррекция видима
Align and distribute Выровнять и распределить
Align horizontal centers Выровнять центры по горизонтали
Align left edges Выровнять по левому краю
Align right edges Выровнять по правому краю
Always use pressure for opacity Всегда использовать нажим для непрозрачности
Always use pressure for size Всегда использовать нажим для размера
Angle Gradient Угловой градиент
Auto-Select: Автовыбор:
Brush Preset picker Выбор набора кистей
Cancel current crop operation (Esc) Отменить текущее кадрирование (Esc)
Click the first point or press {key} to close · Esc cancels Щёлкните первую точку или нажмите {key}, чтобы замкнуть · Esc отменяет
Click the first point or press {key} to close · {del} removes a point · Esc cancels Щёлкните первую точку или нажмите {key}, чтобы замкнуть · {del} удаляет точку · Esc отменяет
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Щёлкните и ведите вдоль края · щелчок закрепляет точку · {alt}-щелчок — прямой отрезок · двойной щелчок замыкает
Clip to layer below Обтравить по нижнему слою
Color & Swatches Цвет и образцы
Commit current crop operation ({key}) Принять текущее кадрирование ({key})
Create a new group Создать новую группу
Create a new layer Создать новый слой
Create new document from current state Создать новый документ из текущего состояния
Create new fill or adjustment layer Создать новый слой-заливку или корректирующий слой
Create new snapshot Создать новый снимок
Delete Cropped Pixels Удалить отсечённые пикселы
Delete current state Удалить текущее состояние
Delete layer Удалить слой
Diamond Gradient Ромбовидный градиент
Doc: {w} × {h} px Док: {w} × {h} px
Enable airbrush-style build-up effects Включить эффекты наслоения в стиле аэрографа
Filter for adjustment layers Фильтр корректирующих слоёв
Filter for pixel layers Фильтр пиксельных слоёв
Filter for shape layers Фильтр слоёв-фигур
Filter for smart objects Фильтр смарт-объектов
Filter for type layers Фильтр текстовых слоёв
Fixed Ratio Заданные пропорции
Fixed Size Заданный размер
Follows only edges this close to the pointer ([ and ] change it) Следует только за краями на таком расстоянии от указателя ([ и ] меняют его)
Hide Properties Скрыть свойства
Higher values follow only edges that contrast sharply with their surroundings Чем выше значение, тем только более контрастные края учитываются
How often fastening points are placed by themselves Как часто точки привязки ставятся автоматически
Hue/Saturation Цветовой тон/Насыщенность
Intersect with selection ({key}) Пересечь с выделением ({key})
Kind Вид
Linear Gradient Линейный градиент
Link layers Связать слои
Lock Закрепить
Lock all Закрепить все
Lock image pixels Сохранить цвета пикселов
Lock layer Закрепить слой
Lock position Закрепить положение
Lock transparent pixels Сохранить прозрачность пикселов
New selection Новое выделение
No properties Нет свойств
Pressure for Opacity Нажим для непрозрачности
Pressure for Size Нажим для размера
Prevent auto-nesting in and out of Artboards and Frames Запретить автоматическое вложение в монтажные области и кадры и извлечение из них
Radial Gradient Радиальный градиент
Reflected Gradient Зеркальный градиент
Reset to defaults Сбросить к значениям по умолчанию
Set additional smoothing options Дополнительные параметры сглаживания
Show Transform Controls Показать управляющие элементы трансформации
Subtract from selection ({key}) Вычесть из выделения ({key})
Swaps height and width Меняет местами высоту и ширину
Tolerance Допуск
Add vector mask Добавить векторную маску
Click to zoom in · {key}-click to zoom out · drag right/left to zoom in/out Щелчок увеличивает · {key}-щелчок уменьшает · перетаскивание вправо/влево увеличивает/уменьшает
Appearance Settings… Настройки оформления…
Add to favorites Добавить в избранное
Remove from favorites Удалить из избранного
@@ -2748,7 +2817,6 @@ cameraData Lens Объектив
Previous Document Предыдущий документ
W x H x Resolution Ш x В x Разрешение
Front Image Изображение переднего плана
Swaps height and width Меняет местами высоту и ширину
Rasterize Layer Style Растрировать стиль слоя
Search settings… Поиск настроек…
No matching settings Нет подходящих настроек
Can't render this file because it contains an unexpected character in line 6 and column 47.
+5
View File
@@ -3539,6 +3539,11 @@ cameraRaw Masking Маскування
Quick Selection found nothing there Швидке виділення нічого тут не знайшло
Object Selection found nothing there — try a tighter rectangle Виділення об'єктів нічого тут не знайшло — спробуйте вужчий прямокутник
No subject found — try a rectangle around the object Об'єкт не знайдено — спробуйте прямокутник навколо об'єкта
Click the first point or press {key} to close · {del} removes a point · Esc cancels Клацніть першу точку або натисніть {key}, щоб замкнути · {del} видаляє точку · Esc скасовує
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close Клацніть і ведіть уздовж краю · клацання закріплює точку · {alt}-клацання — прямий відрізок · подвійне клацання замикає
Follows only edges this close to the pointer ([ and ] change it) Відстежує лише краї на такій відстані від вказівника ([ і ] змінюють її)
Higher values follow only edges that contrast sharply with their surroundings Що більше значення, то лише краї з різким контрастом до оточення
How often fastening points are placed by themselves Як часто точки прив’язки ставляться автоматично
Appearance Settings… Налаштування вигляду…
Add to favorites Додати до вибраного
Remove from favorites Видалити з вибраного
Can't render this file because it contains an unexpected character in line 1329 and column 18.
+9
View File
@@ -2442,6 +2442,15 @@ fontWeight Italic 斜体
Quick Selection found nothing there 快速选择在该处未找到任何内容
Object Selection found nothing there — try a tighter rectangle 对象选择在该处未找到任何内容 — 请尝试更紧凑的矩形
No subject found — try a rectangle around the object 未找到主体 — 请尝试在对象周围绘制矩形
Auto Erase 自动抹除
Click the first point or press {key} to close · {del} removes a point · Esc cancels 点按第一个点或按 {key} 闭合 · {del} 删除一个点 · Esc 取消
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close 点按,然后沿边缘移动 · 点按固定一个点 · {alt}-点按画直线段 · 双击闭合
Follows only edges this close to the pointer ([ and ] change it) 只跟随离指针这么近的边缘(用 [ 和 ] 调整)
Higher values follow only edges that contrast sharply with their surroundings 数值越高,只跟随与周围对比强烈的边缘
How often fastening points are placed by themselves 自动放置紧固点的频率
Scrubby Zoom 细微缩放
{mode} Color · {bits} bit {mode} 颜色 · {bits} 位
Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移绘制裁剪框 · 在框内拖移以移动 · 拖移边缘调整大小({ratio} 比例,{centre} 中心)· 绘制时按 Space 移动 · 方向键微移 · X 切换方向 · {commit} 确认 · Esc 取消
Appearance Settings… 外观设置…
Add to favorites 添加到收藏
Remove from favorites 从收藏中移除
Can't render this file because it contains an unexpected character in line 2457 and column 53.
+9
View File
@@ -2412,6 +2412,15 @@ fontWeight Italic 斜體
Quick Selection found nothing there 快速選取在該處找不到任何內容
Object Selection found nothing there — try a tighter rectangle 物件選取在該處找不到任何內容 — 請嘗試更緊密的矩形
No subject found — try a rectangle around the object 找不到主體 — 請嘗試在物件周圍繪製矩形
Auto Erase 自動擦除
Click the first point or press {key} to close · {del} removes a point · Esc cancels 按一下第一個點或按 {key} 封閉 · {del} 刪除一個點 · Esc 取消
Click, then move along an edge · click to fasten a point · {alt}-click for a straight segment · double-click to close 按一下,然後沿著邊緣移動 · 按一下固定一個點 · {alt}-按一下畫直線區段 · 按兩下封閉
Follows only edges this close to the pointer ([ and ] change it) 只追蹤離指標這麼近的邊緣(用 [ 和 ] 調整)
Higher values follow only edges that contrast sharply with their surroundings 數值越高,只追蹤與周圍對比強烈的邊緣
How often fastening points are placed by themselves 自動放置固定點的頻率
Scrubby Zoom 細微縮放
{mode} Color · {bits} bit {mode} 色彩 · {bits} 位元
Drag a crop box · drag inside to move · edges resize ({ratio} ratio, {centre} centre) · Space moves while drawing · arrows nudge · X swaps orientation · {commit} commits · Esc cancels 拖移繪製裁切框 · 在框內拖移以移動 · 拖移邊緣調整大小({ratio} 比例,{centre} 中心)· 繪製時按 Space 移動 · 方向鍵微移 · X 切換方向 · {commit} 確認 · Esc 取消
Appearance Settings… 外觀設定…
Add to favorites 加入最愛
Remove from favorites 從最愛移除
Can't render this file because it contains an unexpected character in line 6 and column 47.
+8
View File
@@ -342,6 +342,14 @@ pub fn cancel(app: &mut PhotocraftApp, id: JobId) {
}
fn on_event(app: &mut PhotocraftApp, ctx: &egui::Context, e: JobEvent) {
// Preferences ▸ General ▸ Beep When Done (off by default): a finished operation beeps, like
// Photoshop's cue. Cancelling is the user's own action and stays silent.
if matches!(e.outcome, JobOutcome::Done(_))
&& app.session.prefs().general.beep_when_done
&& let Some(beep) = app.services.beep
{
beep();
}
// Control requests waiting on this job.
let reply = match &e.outcome {
JobOutcome::Done(v) => json!({"ok": true, "result": v}),
+30 -2
View File
@@ -3,7 +3,7 @@
//! dialog, and Esc / Cancel leave the document unchanged.
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use egui::vec2;
@@ -15,13 +15,18 @@ use serde_json::{Value, json};
use crate::PhotocraftApp;
fn app_harness() -> Harness<'static, PhotocraftApp> {
app_harness_with(crate::Services::default())
}
/// [`app_harness`] over the given services (the beep test records the hook's calls).
fn app_harness_with(services: crate::Services) -> Harness<'static, PhotocraftApp> {
let mut h = Harness::builder().with_size(vec2(1280.0, 800.0)).with_max_steps(8).build_eframe(|cc| {
PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());
let mut s = photocraft_engine::Session::new();
s.execute("file.new", json!({"width": 320, "height": 240})).unwrap();
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap();
let mut app = PhotocraftApp::new(s, crate::Services::default());
let mut app = PhotocraftApp::new(s, services);
app.background_jobs = true;
app
});
@@ -549,3 +554,26 @@ fn a_cancelled_save_still_counts_until_its_worker_returns() {
step_until(&mut h, |a| !a.saving());
assert!(!h.state().jobs.close_after_saves, "the held close is repeated once the worker returns");
}
/// Preferences ▸ General ▸ Beep When Done (off by default): a finished background job beeps
/// once through the services hook; with the preference off it stays silent.
#[test]
fn a_finished_job_beeps_when_the_preference_is_on() {
static BEEPS: AtomicUsize = AtomicUsize::new(0);
fn count_beep() {
BEEPS.fetch_add(1, Ordering::Relaxed);
}
BEEPS.store(0, Ordering::Relaxed);
let mut h = app_harness_with(crate::Services { beep: Some(count_beep), ..Default::default() });
// Off by default: the first job finishes without a beep.
let gate = Arc::new(AtomicBool::new(true));
let _ = slow_job(h.state_mut(), &gate);
frames_for(&mut h, 800);
assert_eq!(BEEPS.load(Ordering::Relaxed), 0, "silent by default");
// On: the next finished job beeps once.
h.state_mut().run("prefs.set", json!({"path": "general.beepWhenDone", "value": true})).unwrap();
let gate = Arc::new(AtomicBool::new(true));
let _ = slow_job(h.state_mut(), &gate);
frames_for(&mut h, 800);
assert_eq!(BEEPS.load(Ordering::Relaxed), 1, "one beep for the finished job");
}
+3
View File
@@ -351,6 +351,9 @@ pub struct Services {
pub encode_png: Option<EncodePngFn>,
/// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset.
pub open_url: Option<OpenUrlFn>,
/// Preferences ▸ General ▸ Beep When Done: the platform's default beep, played when a
/// background job finishes successfully. `None` in the web build (and in tests).
pub beep: Option<fn()>,
/// Files delivered asynchronously (web drag-and-drop): drained every frame.
pub inbox: Option<Inbox>,
/// OS clipboard images: copies go out, screenshots and images from other apps come in.
+26 -2
View File
@@ -5,23 +5,29 @@ use egui::accesskit::Role;
use egui::{Key, Modifiers, Rect, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use photocraft_engine::prefs::FontPreview;
struct State {
current: String,
families: Vec<String>,
popup: egui::Id,
preview: FontPreview,
}
fn harness() -> Harness<'static, State> {
harness_with(FontPreview::Medium)
}
fn harness_with(preview: FontPreview) -> Harness<'static, State> {
// Enough families that the unfiltered menu hits its maximum height and scrolls.
let mut families: Vec<String> = (0..60).map(|i| format!("Family {i:02}")).collect();
families.push("Zeta Sans".into());
let state = State { current: "Family 00".into(), families, popup: egui::Id::NULL };
let state = State { current: "Family 00".into(), families, popup: egui::Id::NULL, preview };
let mut h = Harness::builder().with_size(vec2(600.0, 900.0)).build_ui_state(
|ui, s: &mut State| {
s.popup = ui.make_persistent_id(egui::IdSalt::new("type-font")).with("popup");
let fams = s.families.clone();
font_picker_in(ui, &mut s.current, 170.0, &fams);
font_picker_in(ui, &mut s.current, 170.0, &fams, s.preview);
},
state,
);
@@ -376,3 +382,21 @@ fn hovering_a_font_previews_only_the_selected_characters() {
assert_eq!(fonts(&preview), ["JetBrains Mono", "JetBrains Mono", "Inter", "Inter", "Inter", "Inter"]);
assert_eq!(fonts(&app.session.active().unwrap().doc), ["JetBrains Mono", "JetBrains Mono", "Inter", "Inter", "Inter", "Inter"]);
}
/// Preferences ▸ Type ▸ Font Preview Size: Extra Large grows the sample rows, Off drops the
/// samples (rows shrink to the plain height).
#[test]
fn the_preview_size_preference_resizes_or_removes_the_samples() {
let mut h = harness_with(FontPreview::Medium);
open(&mut h);
let medium = h.get_by_label("Family 00").rect().height();
assert!((medium - 28.0).abs() < 0.5, "medium rows hold the 24 px sample: {medium}");
let mut h = harness_with(FontPreview::ExtraLarge);
open(&mut h);
let extra = h.get_by_label("Family 00").rect().height();
assert!(extra > medium, "extra large rows are taller: {extra} vs {medium}");
let mut h = harness_with(FontPreview::Off);
open(&mut h);
let off = h.get_by_label("Family 00").rect().height();
assert!((off - 28.0).abs() < 0.5, "off keeps the plain row height: {off}");
}
+6 -4
View File
@@ -371,6 +371,8 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s
}
});
let defined = |attrs: &Value, k: &str| attrs.get(k).is_some();
// Preferences ▸ Type ▸ Font Preview Size sizes the family picker's samples.
let preview = app.session.prefs().type_.font_preview;
// Preferences ▸ Units & Rulers ▸ Type: the model stores points; the fields may show pixels
// (by the document's resolution) or millimetres.
let (type_unit, unit_label) = crate::type_tool::type_unit(app);
@@ -397,7 +399,7 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s
ui.add_enabled_ui(on, |ui| match kind {
"font" => {
let mut f = v.as_str().unwrap_or("").to_string();
if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f) {
if family_picker(ui, &format!("style-font-{paragraph}-{id}"), &mut f, preview) {
set = Some(json!({ panel: f }));
}
}
@@ -506,9 +508,9 @@ fn options_editor(app: &mut PhotocraftApp, ui: &mut egui::Ui, paragraph: bool, s
}
/// Searchable family combo box.
fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String) -> bool {
fn family_picker(ui: &mut egui::Ui, salt: &str, current: &mut String, preview: photocraft_engine::prefs::FontPreview) -> bool {
let mut shown = if current.is_empty() { photocraft_text::fonts::DEFAULT_FAMILY.to_string() } else { current.clone() };
let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families());
let changed = crate::type_tool::family_picker_in(ui, salt, &mut shown, 140.0, &crate::type_tool::families(), preview);
if changed {
*current = shown;
}
@@ -598,7 +600,7 @@ pub fn glyphs_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
// Font family + style.
ui.horizontal(|ui| {
let mut f = family.clone();
if family_picker(ui, "glyph-family", &mut f) {
if family_picker(ui, "glyph-family", &mut f, app.session.prefs().type_.font_preview) {
app.ui.type_panels.glyph_family = f;
app.ui.type_panels.glyph_style = tl!("Regular").into();
}
+26 -15
View File
@@ -844,8 +844,8 @@ pub fn style_label(style: &str) -> String {
}
/// Searchable font-family combo box.
fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32) -> bool {
family_picker_in(ui, "type-font", current, width, &families())
fn font_picker(ui: &mut egui::Ui, current: &mut String, width: f32, preview: photocraft_engine::prefs::FontPreview) -> bool {
family_picker_in(ui, "type-font", current, width, &families(), preview)
}
/// Maximum height of the font menu.
@@ -853,13 +853,20 @@ const FONT_MENU_HEIGHT: f32 = 460.0;
/// [`font_picker`] over a given family list (tests pass their own).
#[cfg(test)]
fn font_picker_in(ui: &mut egui::Ui, current: &mut String, width: f32, families: &[String]) -> bool {
family_picker_in(ui, "type-font", current, width, families)
fn font_picker_in(ui: &mut egui::Ui, current: &mut String, width: f32, families: &[String], preview: photocraft_engine::prefs::FontPreview) -> bool {
family_picker_in(ui, "type-font", current, width, families, preview)
}
/// Shared by the Type options, Character, style and Glyphs panels. Selection changes still
/// flow through each caller's existing engine command.
pub(crate) fn family_picker_in(ui: &mut egui::Ui, salt: &str, current: &mut String, width: f32, families: &[String]) -> bool {
pub(crate) fn family_picker_in(
ui: &mut egui::Ui,
salt: &str,
current: &mut String,
width: f32,
families: &[String],
preview: photocraft_engine::prefs::FontPreview,
) -> bool {
let mut changed = false;
let search_id = ui.id().with(("font-search", salt));
let combo = egui::ComboBox::from_id_salt(salt)
@@ -917,20 +924,24 @@ pub(crate) fn family_picker_in(ui: &mut egui::Ui, salt: &str, current: &mut Stri
ui.data_mut(|d| d.remove::<String>(search_id));
ui.close();
}
let preview = crate::font_preview::sample(preview);
let row_h = preview.map_or(28.0, |(_, [_, h])| (h + 4.0).max(28.0));
let mut hovered: Option<String> = None;
for f in filtered {
let response = ui.add_sized(
[330.0, 28.0],
egui::Button::selectable(f == current, f)
.truncate()
.right_text(egui::Atom::custom(ui.id().with(("font-sample", f)), egui::vec2(crate::font_preview::slot_width(ui.ctx(), f), 24.0))),
);
let mut button = egui::Button::selectable(f == current, f).truncate();
if let Some((size, [_, h])) = preview {
button =
button.right_text(egui::Atom::custom(ui.id().with(("font-sample", f)), egui::vec2(crate::font_preview::slot_width(ui.ctx(), f, size), h)));
}
let response = ui.add_sized([330.0, row_h], button);
if (down || up) && f == current {
response.scroll_to_me(Some(egui::Align::Center));
}
if ui.is_rect_visible(response.rect) {
crate::font_preview::paint(ui, f, response.rect);
if let Some((size, _)) = preview
&& ui.is_rect_visible(response.rect)
{
crate::font_preview::paint(ui, f, response.rect, size);
}
if response.hovered() {
hovered = Some(f.clone());
@@ -1095,7 +1106,7 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
app.ui.status_error = true;
}
}
if font_picker(ui, &mut fam, 170.0) {
if font_picker(ui, &mut fam, 170.0, app.session.prefs().type_.font_preview) {
app.ui.tool_options.type_font = fam.clone();
let st = styles(&fam);
style = if st.contains(&style) { style } else { st.first().cloned().unwrap_or_else(|| "Regular".into()) };
@@ -1398,7 +1409,7 @@ fn type_sections(app: &mut PhotocraftApp, ui: &mut egui::Ui, character: bool, pa
let w = field_width(full, 2, LABEL_W);
let mut fam = c.font_family.clone();
row(ui, &mut |ui| {
if font_picker(ui, &mut fam, full) {
if font_picker(ui, &mut fam, full, app.session.prefs().type_.font_preview) {
app.ui.tool_options.type_font = fam.clone();
apply(app, ui.ctx(), json!({"font": fam}));
}
+3 -3
View File
@@ -9,7 +9,7 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js
| [Performance](#performance) | 3 | 22 | 22 | 56 scenarios: 3 within budget, 22 over budget or failing, 9 tracked only, 16 not run, 6 not measurable yet (baseline 2026-10-05) |
| [File compatibility](#file-compatibility) | 5 | 11 | 11 | io corpus: oracle ≥ 146/170, round trip ≥ 169/170; psd-tools corpus: oracle ≥ 236/309, round trip ≥ 308/309; photoshop oracles: oracle ≥ 133/256, round trip ≥ 258/256 |
| [Tools](#tools) | 22 | 16 | 4 | |
| [Workspace and UI](#workspace-and-ui) | 6 | 7 | 10 | settings that do nothing: 39 of 152 (target 0) |
| [Workspace and UI](#workspace-and-ui) | 6 | 7 | 10 | settings that do nothing: 37 of 152 (target 0) |
| [Type](#type) | 0 | 3 | 6 | |
| [Automation](#automation) | 3 | 2 | 6 | 630 of 630 menu items live (100.0%) |
| [Reliability](#reliability) | 5 | 2 | 0 | never-crash lints on 28 of 28 crates; panic_hunt present |
@@ -175,9 +175,9 @@ Corpus floors (`crates/io/tests/corpus.rs`): the enforced minimums; the corpus t
## Workspace and UI
**Settings that do nothing: 39 of 152** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
**Settings that do nothing: 37 of 152** (target 0, #204). Counted by the prefs audit (`xtask/src/scorecard.rs`): a `Preferences` field counts as read when code outside the prefs model (`prefs.rs` except its `impl Session` blocks; tests excluded; the schema-driven dialog never names a field) accesses `section.field`, or `.section` and `.field` in the same file, or calls a section method that reads `self.field`. It is a heuristic lower bound: a generic name can look read when it isn't.
Unread: `general.color_picker`, `general.beep_when_done`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `tools.enable_flick_panning`, `tools.show_transformation_values`, `file_handling.image_previews`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.text_engine`, `type_.font_preview`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
Unread: `general.color_picker`, `general.always_create_smart_objects_when_placing`, `general.animated_zoom`, `general.zoom_resizes_windows`, `workspace.auto_collapse_icon_panels`, `workspace.auto_show_hidden_panels`, `workspace.enable_floating_document_window_docking`, `workspace.enable_narrow_options_bar`, `tools.enable_flick_panning`, `tools.show_transformation_values`, `file_handling.image_previews`, `file_handling.save_in_background`, `file_handling.ignore_exif_profile_tag`, `file_handling.maximize_psd_compatibility`, `performance.cache_levels`, `performance.legacy_compositing`, `scratch_disks.disks`, `units_and_rulers.column_width`, `units_and_rulers.gutter`, `units_and_rulers.print_resolution`, `plug_ins.show_extension_panels`, `plug_ins.allow_scripts_to_connect`, `plug_ins.generator_enabled`, `type_.missing_glyph_protection`, `type_.show_font_names_in_english`, `type_.text_engine`, `type_.recent_fonts`, `enhanced_controls.scrubby_slider_acceleration`, `enhanced_controls.touch_gestures`, `raw_defaults.color_space`, `raw_defaults.bit_depth`, `raw_defaults.resolution`, `raw_defaults.sharpen_for`, `raw_defaults.open_as_smart_object`, `raw_defaults.apply_auto_tone`, `integrations.allow_agent_control`, `integrations.control_port`.
| Id | Target | Status | Issue | Note |
|---|---|---|---|---|