Background dialog: adjust an image's offset and scale; visual style names

- The Image tab gains an Adjust card: X/Y offset in pixels (-2000..2000)
  and X/Y scale (-10..10, tenth steps, a negative scale mirrors, zero keeps
  the image's scale) with spinners and Reset, inactive while the image is
  stretched; Keep aspect ratio is a switch and makes both scales follow.
- The preview shows the image at its offset and scale, tiled when tiled,
  and a stretched image kept to its aspect ratio covers the view.
- Automation: step=<field>,+1|-1 and reset; offset/scale take any numbers.
- Shaded with edges, Shades of Gray and Sketchy have catalog entries in
  every language.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ramox81andClaude Opus 5.5 committed 2026-10-13 10:28:18 +03:00
1 parent 064da8829e
commit 0ee95fa4ba
27 files changed
+439 -91

No files matched your search

+2
View File
@@ -584,6 +584,8 @@ impl OpenCADStudio {
| PdfDialogMsg::BgAspect(_)
| PdfDialogMsg::BgOffset(_)
| PdfDialogMsg::BgScale(_)
| PdfDialogMsg::BgStep(..)
| PdfDialogMsg::BgReset
| PdfDialogMsg::BgApply) => return self.update_view_background(message),
message @ (PdfDialogMsg::SecPerimeter(_)
| PdfDialogMsg::SecMaxPoints(_)
+69 -8
View File
@@ -450,8 +450,14 @@ impl OpenCADStudio {
image: String::new(),
position: BgPosition::Center,
aspect: false,
offset: [0.0, 0.0],
scale: [1.0, 1.0],
offset: ["0".into(), "0".into()],
scale: ["1".into(), "1".into()],
scale_base: [1.0, 1.0],
image_size: None,
viewport: {
let (width, height) = self.tabs[i].scene.selection.borrow().view.vp_size;
[width as f32, height as f32]
},
canvas: [0, 1, 2].map(|k| (canvas[k].clamp(0.0, 1.0) * 255.0).round() as u8),
};
let document = &self.tabs[i].scene.document;
@@ -478,8 +484,10 @@ impl OpenCADStudio {
BgPosition::Center
};
state.aspect = value.maintain_aspect_ratio;
state.offset = [value.offset.x, value.offset.y];
state.scale = [value.scale.x, value.scale.y];
state.offset = [value.offset.x, value.offset.y].map(crate::ui::window::pdf_dialogs::short);
state.scale = [value.scale.x, value.scale.y].map(crate::ui::window::pdf_dialogs::short);
state.scale_base = [value.scale.x, value.scale.y];
state.image_size = image::image_dimensions(&value.filename).ok().map(|(w, h)| [w, h]);
}
_ => {}
}
@@ -504,11 +512,42 @@ impl OpenCADStudio {
M::BgKind(kind) => state.kind = kind,
M::BgThree(on) => state.three = on,
M::BgRotation(value) => state.rotation = value,
M::BgImage(value) => state.image = value,
M::BgImage(value) => {
state.image_size = image::image_dimensions(value.trim()).ok().map(|(w, h)| [w, h]);
state.image = value;
}
M::BgPosition(value) => state.position = value,
M::BgAspect(on) => state.aspect = on,
M::BgOffset(value) => state.offset = value,
M::BgScale(value) => state.scale = value,
M::BgScale(value) => {
// Keeping the aspect ratio, both scales follow the one changed.
state.scale = if state.aspect {
let changed = if value[0] != state.scale[0] { 0 } else { 1 };
[value[changed].clone(), value[changed].clone()]
} else {
value
};
}
M::BgStep(field, dir) => {
use crate::ui::window::pdf_dialogs::{bg_step, short};
let current = |text: &String, default: f64| text.trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(default);
if field < 2 {
let k = field as usize;
state.offset[k] = short(bg_step(field, current(&state.offset[k], 0.0), dir));
} else {
let k = field as usize - 2;
let next = short(bg_step(field, current(&state.scale[k], state.scale_base[k]), dir));
if state.aspect {
state.scale = [next.clone(), next];
} else {
state.scale[k] = next;
}
}
}
M::BgReset => {
state.offset = ["0".into(), "0".into()];
state.scale = ["1".into(), "1".into()];
}
M::BgColor(slot, rgb) => match slot {
0 => state.solid = rgb,
1 => state.top = rgb,
@@ -587,14 +626,36 @@ impl OpenCADStudio {
self.command_line.push_error("Invalid Background Image File!");
return Task::none();
}
use crate::ui::window::pdf_dialogs::{BG_OFFSET_LIMIT, BG_SCALE_LIMIT};
let number = |text: &String| text.trim().parse::<f64>().ok().filter(|v| v.is_finite());
let (Some(ox), Some(oy), Some(sx), Some(sy)) = (
number(&state.offset[0]),
number(&state.offset[1]),
number(&state.scale[0]),
number(&state.scale[1]),
) else {
self.command_line.push_error(crate::t!("Requires a number.").as_ref());
return Task::none();
};
// Within the reference's slider ranges; a zero scale
// is ignored there, so the image keeps its scale.
let scale = |value: f64, base: f64| {
if value.abs() < 1e-9 { base } else { value.clamp(-BG_SCALE_LIMIT, BG_SCALE_LIMIT) }
};
Some(D::ImageBackground(ImageBackground {
class_version: 1,
filename: state.image.trim().to_string(),
fit_to_screen: state.position == BgPosition::Stretch,
maintain_aspect_ratio: state.aspect,
use_tiling: state.position == BgPosition::Tile,
offset: codec::types::Vector2::new(state.offset[0], state.offset[1]),
scale: codec::types::Vector2::new(state.scale[0], state.scale[1]),
offset: codec::types::Vector2::new(
ox.clamp(-BG_OFFSET_LIMIT, BG_OFFSET_LIMIT),
oy.clamp(-BG_OFFSET_LIMIT, BG_OFFSET_LIMIT),
),
scale: codec::types::Vector2::new(
scale(sx, state.scale_base[0]),
scale(sy, state.scale_base[1]),
),
}))
}
};
+24 -12
View File
@@ -1798,7 +1798,8 @@ impl OpenCADStudio {
"ribbon_dropdown" => Message::ToggleRibbonDropdown(string(req, "value")?.into()),
// The -VIEW Background dialog, one field per call: "type=gradient",
// "color|top|middle|bottom=r,g,b", "three=1", "rotation=30",
// "image=<path>", "position=center|stretch|tile", "aspect=1", "offset=x,y" (pixels), "scale=x,y" (non-zero),
// "image=<path>", "position=center|stretch|tile", "aspect=1", "offset=x,y" (pixels), "scale=x,y",
// "step=offset_x|offset_y|scale_x|scale_y,+1|-1", "reset",
// "apply" or "cancel".
"view_background" => {
use crate::ui::window::pdf_dialogs::{BgKind, BgPosition, PdfDialogMsg as P};
@@ -1841,20 +1842,31 @@ impl OpenCADStudio {
})),
"aspect" => Message::PdfDialog(P::BgAspect(value == "1")),
"offset" | "scale" => {
let pair: Vec<f64> = value
.split(',')
.map(|part| part.trim().parse::<f64>())
.collect::<Result<_, _>>()
.map_err(|_| bad())?;
let pair = <[f64; 2]>::try_from(pair).map_err(|_| bad())?;
if key == "offset" {
Message::PdfDialog(P::BgOffset(pair))
} else if pair.iter().all(|v| v.is_finite() && *v != 0.0) {
Message::PdfDialog(P::BgScale(pair))
} else {
let pair: Vec<String> = value.split(',').map(|part| part.trim().to_string()).collect();
let pair = <[String; 2]>::try_from(pair).map_err(|_| bad())?;
if pair.iter().any(|v| v.parse::<f64>().map_or(true, |v| !v.is_finite())) {
return Err(bad());
}
if key == "offset" {
Message::PdfDialog(P::BgOffset(pair))
} else {
Message::PdfDialog(P::BgScale(pair))
}
}
"step" => {
// step=offset_x|offset_y|scale_x|scale_y,+1|-1
let (field, dir) = value.split_once(',').ok_or_else(bad)?;
let field = match field {
"offset_x" => 0,
"offset_y" => 1,
"scale_x" => 2,
"scale_y" => 3,
_ => return Err(bad()),
};
let dir: i8 = dir.trim().parse().map_err(|_| bad())?;
Message::PdfDialog(P::BgStep(field, dir))
}
"reset" => Message::PdfDialog(P::BgReset),
_ => return Err(bad()),
}
}
+3
View File
@@ -2994,6 +2994,8 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"Shade plot" => Some(("common", "shade-plot")),
"Shaded" => Some(("view", "shaded")),
"Shaded viewport options" => Some(("plot", "shaded-viewport-options")),
"Shaded with edges" => Some(("common", "shaded-with-edges")),
"Shades of Gray" => Some(("common", "shades-of-gray")),
"Shadow flags" => Some(("common", "shadow-flags")),
"Shadows" => Some(("properties", "shadows")),
"Shape" => Some(("properties", "shape")),
@@ -3020,6 +3022,7 @@ pub(super) fn message_attribute(source: &str) -> Option<(&'static str, &'static
"SingleLine" => Some(("properties", "singleline")),
"Size" => Some(("common", "size")),
"Sketch" => Some(("draw", "sketch")),
"Sketchy" => Some(("common", "sketchy")),
"Snap override: {label} (next pick only)." => Some(("common", "snap-override-label-next-pick-only")),
"Snap to\nUnderlays" => Some(("insert", "snap-to-underlays")),
"Softness" => Some(("properties", "softness")),
+186 -48
View File
@@ -122,9 +122,13 @@ pub enum PdfDialogMsg {
BgBrowse,
BgPosition(BgPosition),
BgAspect(bool),
/// An image background's offset (pixels) and scale.
BgOffset([f64; 2]),
BgScale([f64; 2]),
/// An image background's offset (pixels, x and y) and scale, as typed.
BgOffset([String; 2]),
BgScale([String; 2]),
/// A spinner step on offset x / y (0, 1) or scale x / y (2, 3).
BgStep(u8, i8),
/// Offset 0, scale 1.
BgReset,
BgApply,
}
@@ -2181,19 +2185,23 @@ impl fmt::Display for BgPosition {
}
}
/// How an image background is scaled: to the screen, or keeping its
/// aspect ratio.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct BgAspect(pub bool);
/// Image offsets the reference's Adjust Image sliders reach, in pixels.
pub const BG_OFFSET_LIMIT: f64 = 2000.0;
/// Image scales the reference's sliders reach (slider value / 10).
pub const BG_SCALE_LIMIT: f64 = 10.0;
impl fmt::Display for BgAspect {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&if self.0 {
crate::tr!("view-background", "aspect")
} else {
crate::tr!("view-background", "fit")
})
/// One spinner step on an image background field: a pixel for an offset, a
/// tenth for a scale, which skips 0 (the reference ignores a zero scale).
pub fn bg_step(field: u8, value: f64, dir: i8) -> f64 {
let dir = f64::from(dir.signum());
if field < 2 {
return (value.round() + dir).clamp(-BG_OFFSET_LIMIT, BG_OFFSET_LIMIT);
}
let mut next = ((value * 10.0).round() + dir) / 10.0;
if next.abs() < 0.05 {
next += dir / 10.0;
}
next.clamp(-BG_SCALE_LIMIT, BG_SCALE_LIMIT)
}
/// The Background dialog's fields for one named view.
@@ -2209,9 +2217,15 @@ pub struct ViewBackgroundState {
pub image: String,
pub position: BgPosition,
pub aspect: bool,
/// The image's offset (pixels) and scale, kept from the view's image.
pub offset: [f64; 2],
pub scale: [f64; 2],
/// The image's offset (pixels) and scale as typed, and the scale the
/// view's image had (kept for a zero scale).
pub offset: [String; 2],
pub scale: [String; 2],
pub scale_base: [f64; 2],
/// The chosen image's size in pixels, for the preview.
pub image_size: Option<[u32; 2]>,
/// The drawing viewport's size, which the preview stands for.
pub viewport: [f32; 2],
/// The drawing area colour, shown for no background.
pub canvas: [u8; 3],
}
@@ -2271,20 +2285,68 @@ pub fn view_background<'a>(
}
BgKind::Image => {
if std::path::Path::new(state.image.trim()).is_file() {
let fit = match (state.position, state.aspect) {
(BgPosition::Stretch, false) => iced::ContentFit::Fill,
(BgPosition::Stretch, true) => iced::ContentFit::Contain,
_ => iced::ContentFit::None,
};
container(
image(image::Handle::from_path(state.image.trim()))
.content_fit(fit)
.width(Fill)
.height(Fill),
)
.center(Fill)
.style(fill(Background::Color(rgb(state.canvas))))
.into()
let handle = image::Handle::from_path(state.image.trim());
let canvas = Background::Color(rgb(state.canvas));
if state.position == BgPosition::Stretch {
// Filling the view; keeping the aspect ratio it covers
// the view and the overflow is cut off.
let fit = if state.aspect { iced::ContentFit::Cover } else { iced::ContentFit::Fill };
container(image(handle).content_fit(fit).width(Fill).height(Fill))
.center(Fill)
.clip(true)
.style(fill(canvas))
.into()
} else {
// The image at its size times its scale, moved by its
// offset, in a view of the drawing viewport's shape.
let parse = |v: &String, d: f64| v.trim().parse::<f64>().ok().filter(|v| v.is_finite()).unwrap_or(d);
let offset = [parse(&state.offset[0], 0.0), parse(&state.offset[1], 0.0)];
let scale = [0, 1].map(|k| {
let v = parse(&state.scale[k], state.scale_base[k]);
if v.abs() < 1e-9 { state.scale_base[k] } else { v }
});
let [iw, ih] = state.image_size.unwrap_or([1, 1]);
let viewport = state.viewport;
let tile = state.position == BgPosition::Tile;
container(iced::widget::responsive(move |size| {
let factor = size.height / viewport[1].max(1.0);
let w = (iw as f32 * scale[0].abs() as f32 * factor).max(1.0);
let h = (ih as f32 * scale[1].abs() as f32 * factor).max(1.0);
let x = size.width / 2.0 + offset[0] as f32 * factor - w / 2.0;
let y = size.height / 2.0 + offset[1] as f32 * factor - h / 2.0;
let (cols, rows) = if tile {
((size.width / w).ceil() as i32 + 1, (size.height / h).ceil() as i32 + 1)
} else {
(0, 0)
};
let mut layers = iced::widget::Stack::new()
.width(Fill)
.height(Fill)
.push(container(Space::new()).width(Fill).height(Fill));
let x0 = if tile { x - (x / w).ceil() * w } else { x };
let y0 = if tile { y - (y / h).ceil() * h } else { y };
for row_index in 0..=rows.min(60) {
for col_index in 0..=cols.min(60) {
let at = iced::Point::new(x0 + col_index as f32 * w, y0 + row_index as f32 * h);
layers = layers.push(
iced::widget::pin(
image(handle.clone())
.content_fit(iced::ContentFit::Fill)
.width(Length::Fixed(w))
.height(Length::Fixed(h)),
)
.position(at),
);
}
}
Element::<Message>::from(layers)
}))
.width(Fill)
.height(Fill)
.clip(true)
.style(fill(canvas))
.into()
}
} else {
container(note(crate::tr!("view-background", "no-image")))
.center(Fill)
@@ -2397,28 +2459,22 @@ pub fn view_background<'a>(
]
.spacing(8)
.align_y(iced::Center),
row![
label(crate::tr!("view-background", "scale"), true),
pick_list(
Some(BgAspect(state.aspect)),
vec![BgAspect(false), BgAspect(true)],
|a: &BgAspect| a.to_string()
)
.on_select(|a: BgAspect| msg(PdfDialogMsg::BgAspect(a.0)))
.text_size(12)
.padding([4, 8])
.width(Fill),
]
.spacing(8)
.align_y(iced::Center),
chip(
crate::tr!("view-background", "aspect"),
state.aspect,
msg(PdfDialogMsg::BgAspect(!state.aspect))
),
]
.spacing(8),
),
};
let adjust = (state.kind == BgKind::Image).then(|| adjust_card(state));
let mut body = column![kind, preview, options].spacing(10);
if let Some(adjust) = adjust {
body = body.push(adjust);
}
column![
kind,
preview,
options,
body,
footer(
"background",
None,
@@ -2431,3 +2487,85 @@ pub fn view_background<'a>(
.width(sizing.width)
.into()
}
/// The image's offset and scale (the reference's Adjust Image): pixel offsets
/// and scales with spinners and a reset; inactive while the image is
/// stretched over the view, where the reference ignores them.
fn adjust_card<'a>(state: &'a ViewBackgroundState) -> Element<'a, Message> {
let enabled = state.position != BgPosition::Stretch;
let dim = move |theme: &Theme| {
if enabled {
muted_style(theme)
} else {
text::Style { color: Some(theme.palette().background.strong.color) }
}
};
let spin = |field: u8| -> Element<'a, Message> {
let value = if field < 2 { &state.offset[field as usize] } else { &state.scale[field as usize - 2] };
let mut input = text_input("", value).size(11).padding([4, 8]).width(Length::Fixed(64.0)).style(field_style);
if enabled {
input = input.on_input(move |v| {
if field < 2 {
let mut pair = state.offset.clone();
pair[field as usize] = v;
msg(PdfDialogMsg::BgOffset(pair))
} else {
let mut pair = state.scale.clone();
pair[field as usize - 2] = v;
msg(PdfDialogMsg::BgScale(pair))
}
});
}
let arrow = |up: bool| {
let mut b = button(crate::ui::icons::themed_arrow_toggle(up, 7.0))
.style(button_style(false))
.padding([1, 4]);
if enabled {
b = b.on_press(msg(PdfDialogMsg::BgStep(field, if up { 1 } else { -1 })));
}
b
};
row![input, column![arrow(true), arrow(false)].spacing(1)].spacing(2).align_y(iced::Center).into()
};
let axis = |name: &'static str| text(name).size(11).style(dim);
let line = |label: String, a: u8, b: u8, unit: bool| -> Element<'a, Message> {
let mut r = row![
text(label).size(11).style(dim).width(Length::Fixed(72.0)),
axis("X"),
spin(a),
axis("Y"),
spin(b),
]
.spacing(6)
.align_y(iced::Center);
if unit {
r = r.push(text(crate::tr!("view-background", "pixels")).size(11).style(dim));
}
r.into()
};
let mut reset = button(text(crate::tr!("view-background", "reset")).size(11))
.style(button_style(false))
.padding([3, 10]);
if enabled {
reset = reset.on_press(msg(PdfDialogMsg::BgReset));
}
container(
column![
row![
text(crate::tr!("view-background", "adjust").to_uppercase()).size(10).style(move |theme: &Theme| {
if enabled { accent_text(theme) } else { dim(theme) }
}),
Space::new().width(Fill),
reset,
]
.align_y(iced::Center),
line(crate::tr!("view-background", "offset"), 0, 1, true),
line(crate::tr!("view-background", "scale"), 2, 3, false),
]
.spacing(8),
)
.padding([10, 12])
.width(Fill)
.style(card_style)
.into()
}