mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 19:51:26 -05:00
export-w10: net change of 2 commits
- export-w10: written from its sheet - export-w10: repair 1
This commit is contained in:
@@ -6,6 +6,10 @@
|
||||
//! are `document.export` params (format, path, artboard choice…); `__`-prefixed ones are the
|
||||
//! dialog's.
|
||||
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
|
||||
use craft_ui::text::NumberField;
|
||||
use craft_ui::value_drag::SliderScale;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_engine::cmd::fileio::{self, ArtboardPick, Format};
|
||||
@@ -13,13 +17,11 @@ use vectorcraft_render::AntiAlias;
|
||||
use vectorcraft_render::encode::jpeg::{self, ColorModel, Method};
|
||||
use vectorcraft_render::encode::quantize::{Dither, PaletteOptions, Reduction};
|
||||
|
||||
use super::{DialogSpec, form, psd_options, tiff_bmp_tga};
|
||||
use crate::state::Dialog;
|
||||
use crate::theme::Tokens;
|
||||
use crate::{VectorcraftApp, io, widgets};
|
||||
|
||||
pub(super) const SPEC: DialogSpec =
|
||||
DialogSpec { heading, body, confirm, ok: Some("Export"), min_width: 360.0, inputs: |_| &["path"], ..DialogSpec::FORM };
|
||||
use super::export_host::{self, After, Export, Open};
|
||||
// PLAN: assumed `form::{fields_of, json_of}` (wg.S12, widgets-w12) live in `dialogs::form`.
|
||||
use super::form::{fields_of, json_of};
|
||||
use super::{psd_options, tiff_bmp_tga};
|
||||
use crate::{VectorcraftApp, io};
|
||||
|
||||
/// Resolution presets (pixels per inch).
|
||||
pub(super) const RESOLUTIONS: [f64; 3] = [72.0, 150.0, 300.0];
|
||||
@@ -32,8 +34,6 @@ const BACKGROUND_LABELS: [&str; 4] = ["Transparent", "White", "Black", "Other"];
|
||||
/// JPEG image map param values and their labels.
|
||||
const IMAGE_MAPS: [&str; 3] = ["none", "client", "server"];
|
||||
const IMAGE_MAP_LABELS: [&str; 3] = ["None", "Client-side (.html)", "Server-side (.map)"];
|
||||
/// Palette sizes offered (any 2–256 can be typed).
|
||||
const COLOR_COUNTS: [&str; 8] = ["2", "4", "8", "16", "32", "64", "128", "256"];
|
||||
/// Matte param values and their labels (`Other`: a colour).
|
||||
const MATTES: [&str; 3] = ["none", "white", "black"];
|
||||
const MATTE_LABELS: [&str; 4] = ["None", "White", "Black", "Other"];
|
||||
@@ -43,6 +43,10 @@ const QUALITY_BANDS: [&str; 11] = ["Low", "Low", "Low", "Medium", "Medium", "Med
|
||||
const WEBP_COMPRESSION_LABELS: [&str; 2] = ["Lossless", "Lossy"];
|
||||
/// The lossy WebP quality a new export starts with (0–100).
|
||||
const WEBP_QUALITY: u8 = 90;
|
||||
/// The colour a colour choice's `Other` starts from.
|
||||
const OTHER_COLOR: &str = "#808080";
|
||||
/// Params the engine reads as whole numbers; a row may hold them as floats or as option ids.
|
||||
const INTEGER_KEYS: [&str; 5] = ["quality", "scans", "colors", "ditherAmount", "depth"];
|
||||
|
||||
/// The dialog kind of a raster format (`pngOptions`, `jpgOptions`, `webpOptions`, `gifOptions`,
|
||||
/// `png8Options`).
|
||||
@@ -50,14 +54,14 @@ fn kind(f: &Format) -> String {
|
||||
format!("{}Options", f.id)
|
||||
}
|
||||
|
||||
fn format_of(d: &Dialog) -> Option<&'static Format> {
|
||||
fileio::format(d.kind.strip_suffix("Options")?)
|
||||
}
|
||||
|
||||
/// Open the options of raster format `f` for an export whose params (format, path, artboard
|
||||
/// choice) are `params`.
|
||||
pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) {
|
||||
let selection = params[super::export_as::SELECTION_FIELD] == true;
|
||||
pub fn open(app: &mut VectorcraftApp, f: &Format, params: Value) {
|
||||
open_with(app, f, params, false);
|
||||
}
|
||||
|
||||
/// [`open`] for Export Selection when `selection`: the size shown is the selection's crop.
|
||||
pub(crate) fn open_with(app: &mut VectorcraftApp, f: &Format, mut params: Value, selection: bool) {
|
||||
let size = app.session.active().and_then(|st| match selection {
|
||||
true => vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false).ok().map(|(_, r)| (r.width(), r.height())),
|
||||
false => export_size(&st.doc, ¶ms),
|
||||
@@ -74,7 +78,23 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) {
|
||||
o.insert("__size".into(), json!([w, h]));
|
||||
}
|
||||
}
|
||||
app.ui.dialog = Some(Dialog::new(&kind(f), params));
|
||||
let Some(ctx) = app.ui_ctx.clone() else { return };
|
||||
let size = size.map(|(w, h)| [w, h]);
|
||||
let (id, label, key) = (f.id, f.label, kind(f));
|
||||
let map = params.as_object().cloned().unwrap_or_default();
|
||||
let initial = fields_of(&raster_rows(id, false, size, &DialogFields::new()), &map);
|
||||
let build = {
|
||||
let key = key.clone();
|
||||
move |fields: &mut DialogFields| {
|
||||
normalize_colors(fields);
|
||||
if id == "bmp" {
|
||||
tiff_bmp_tga::normalize_bmp(fields);
|
||||
}
|
||||
ParamDialog::new(key.clone(), heading(label), raster_rows(id, false, size, fields)).values(Bind::bound(fields)).ok_label(tl!("Export"))
|
||||
}
|
||||
};
|
||||
let dialog = HostedParamDialog::new(&ctx, key, initial, build);
|
||||
export_host::open(app, Export::Raster { format: id }, selection, dialog);
|
||||
}
|
||||
|
||||
/// The options raster format `f` starts with (after the resolution): the document's background
|
||||
@@ -132,7 +152,7 @@ fn export_size(doc: &vectorcraft_doc::Document, p: &Value) -> Option<(f64, f64)>
|
||||
Some(false) => vectorcraft_render::encode::art_bounds(doc)?,
|
||||
Some(true) => match pick.resolve(n).ok()?.as_deref() {
|
||||
Some([i]) => doc.artboards.get(*i)?.rect,
|
||||
None if n == 1 => doc.artboards[0].rect,
|
||||
None if n == 1 => doc.artboards.first()?.rect,
|
||||
_ => return None,
|
||||
},
|
||||
None => doc.artboards.get(pick.one(n).ok()?)?.rect,
|
||||
@@ -140,241 +160,226 @@ fn export_size(doc: &vectorcraft_doc::Document, p: &Value) -> Option<(f64, f64)>
|
||||
Some((r.width(), r.height()))
|
||||
}
|
||||
|
||||
fn heading(d: &Dialog) -> String {
|
||||
crate::i18n::fmt(tl!("{format} Options"), &[("format", format_of(d).map_or(tl!("Export"), |f| f.label))])
|
||||
fn heading(label: &str) -> String {
|
||||
crate::i18n::fmt(tl!("{format} Options"), &[("format", label)])
|
||||
}
|
||||
|
||||
fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let id = format_of(d).map_or("png", |f| f.id);
|
||||
let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(tl!(text)).color(t.text_dim));
|
||||
egui::Grid::new("raster-options").num_columns(2).spacing([10.0, 8.0]).show(ui, |ui| {
|
||||
label(ui, tl!("Resolution:"));
|
||||
let ppi = d.f64("ppi", 72.0);
|
||||
let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| !d.bool("__otherPpi"));
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-ppi", RESOLUTION_LABELS[preset.unwrap_or(3)], &RESOLUTION_LABELS, 150.0) {
|
||||
if let Some(p) = RESOLUTIONS.get(i) {
|
||||
d.fields.insert("ppi".into(), json!(p));
|
||||
}
|
||||
d.fields.insert("__otherPpi".into(), json!(i == 3));
|
||||
}
|
||||
if preset.is_none()
|
||||
&& let Some(v) = widgets::range_field(ui, "ro-ppi-other", ppi, 1.0..=4608.0, &super::ppi_suffix(), 0, 80.0)
|
||||
{
|
||||
d.fields.insert("ppi".into(), json!(v));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
option_rows(ui, d, id, false);
|
||||
|
||||
if let Some([w, h]) =
|
||||
d.fields.get("__size").and_then(Value::as_array).map(|a| [0, 1].map(|i| a.get(i).and_then(Value::as_f64).unwrap_or(0.0)))
|
||||
{
|
||||
label(ui, tl!("Size:"));
|
||||
let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), d.f64("ppi", 72.0) / 72.0);
|
||||
ui.label(egui::RichText::new(format!("{pw} × {ph} px")).color(t.text));
|
||||
ui.end_row();
|
||||
}
|
||||
});
|
||||
false
|
||||
/// The rows of raster format `id`'s options: resolution, the size it gives, background,
|
||||
/// anti-aliasing and the format's own. `screens` (Export for Screens' Format Settings) leaves out
|
||||
/// what its rows choose (JPEG quality) and what writes other files (image maps). `size` is the
|
||||
/// region's size in points, when one region is exported.
|
||||
pub(crate) fn raster_params(id: &str, screens: bool, size: Option<[f64; 2]>) -> Vec<Param> {
|
||||
raster_rows(id, screens, size, &DialogFields::new())
|
||||
}
|
||||
|
||||
/// The grid rows of raster format `id`'s options after the resolution: background, anti-aliasing
|
||||
/// and the format's own. `screens` (Export for Screens' Format Settings) leaves out what its rows
|
||||
/// choose (JPEG quality) and what writes other files (image maps).
|
||||
pub(super) fn option_rows(ui: &mut egui::Ui, d: &mut Dialog, id: &str, screens: bool) {
|
||||
let t = Tokens::get(ui.ctx());
|
||||
let label = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(tl!(text)).color(t.text_dim));
|
||||
label(ui, tl!("Background Color:"));
|
||||
let bg = d.str("background");
|
||||
let choice = BACKGROUNDS.iter().position(|v| bg.eq_ignore_ascii_case(v)).unwrap_or(3);
|
||||
/// [`raster_params`] for a dialog whose rows depend on its values (BMP's palette rows).
|
||||
fn raster_rows(id: &str, screens: bool, size: Option<[f64; 2]>, fields: &DialogFields) -> Vec<Param> {
|
||||
let mut rows = vec![resolution_row()];
|
||||
if let Some([w, h]) = size {
|
||||
rows.push(size_row(w, h));
|
||||
}
|
||||
// JPEG has no transparency, nor have some TIFF, BMP and Targa options: their list starts at
|
||||
// White, which is what transparent becomes.
|
||||
let first = usize::from(!tiff_bmp_tga::keeps_alpha(id, d));
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-bg", BACKGROUND_LABELS[choice.max(first)], &BACKGROUND_LABELS[first..], 150.0) {
|
||||
let value = BACKGROUNDS.get(i + first).copied().unwrap_or("#808080");
|
||||
d.fields.insert("background".into(), json!(value));
|
||||
}
|
||||
if choice == 3 {
|
||||
color_button(ui, d, "background");
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Anti-aliasing:"));
|
||||
let aa = AntiAlias::from_id(&d.str("antiAlias")).unwrap_or_default();
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-aa", aa.label(), &AntiAlias::ALL.map(AntiAlias::label), 150.0) {
|
||||
d.fields.insert("antiAlias".into(), json!(AntiAlias::ALL[i].id()));
|
||||
}
|
||||
ui.end_row();
|
||||
|
||||
let format = id.to_string();
|
||||
rows.push(color_choice("background", tl!("Background Color:"), &BACKGROUNDS, &BACKGROUND_LABELS, move |f| {
|
||||
usize::from(!tiff_bmp_tga::keeps_alpha(&format, f))
|
||||
}));
|
||||
rows.push(choice("antiAlias", tl!("Anti-aliasing:"), &AntiAlias::ALL.map(AntiAlias::id), &AntiAlias::ALL.map(AntiAlias::label)));
|
||||
match id {
|
||||
"png" => {
|
||||
ui.label("");
|
||||
form::check(ui, d, "interlaced", tl!("Interlaced"));
|
||||
ui.end_row();
|
||||
"png" => rows.push(check("interlaced", tl!("Interlaced"), false)),
|
||||
"jpg" => rows.extend(jpeg_rows(screens)),
|
||||
"gif" | "png8" => rows.extend(palette_rows()),
|
||||
"webp" => rows.extend(webp_rows()),
|
||||
"psd" => rows.extend(psd_options::params()),
|
||||
id => rows.extend(tiff_bmp_tga::params(id, fields)),
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// A dropdown row bound to `key`: one of `ids`, shown by its label.
|
||||
pub(super) fn choice(key: &str, label: &str, ids: &[impl AsRef<str>], labels: &[&str]) -> Param {
|
||||
let options = ids.iter().zip(labels).map(|(id, l)| (id.as_ref().to_string(), tl!(*l).into())).collect();
|
||||
Param::new(key, tl!(label), ParamKind::choice(options, ids.first().map(|id| id.as_ref().to_string())))
|
||||
}
|
||||
|
||||
/// A check box row bound to `key`.
|
||||
pub(super) fn check(key: &str, label: &str, default: bool) -> Param {
|
||||
Param::new(key, tl!(label), ParamKind::bool(default))
|
||||
}
|
||||
|
||||
/// Resolution: a preset, or Other with a field of its own (`__otherPpi` marks Other, so a typed
|
||||
/// 72 stays Other).
|
||||
fn resolution_row() -> Param {
|
||||
Param::custom("ppi", tl!("Resolution:"), |ui, fields, _| {
|
||||
let ppi = fields.number("ppi").unwrap_or(72.0);
|
||||
let preset = RESOLUTIONS.iter().position(|p| *p == ppi).filter(|_| fields.bool("__otherPpi") != Some(true));
|
||||
let shown = preset.unwrap_or(RESOLUTION_LABELS.len() - 1);
|
||||
ui.horizontal(|ui| {
|
||||
craft_ui::ComboBox::from_id_salt("ro-ppi").selected_text(tl!(RESOLUTION_LABELS.get(shown).copied().unwrap_or_default())).show_ui(
|
||||
ui,
|
||||
|ui| {
|
||||
for (i, label) in RESOLUTION_LABELS.iter().enumerate() {
|
||||
if ui.selectable_label(i == shown, tl!(*label)).clicked() {
|
||||
if let Some(p) = RESOLUTIONS.get(i) {
|
||||
fields.set("ppi", *p);
|
||||
}
|
||||
fields.set("__otherPpi", i == RESOLUTION_LABELS.len() - 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
if preset.is_none() {
|
||||
let field = NumberField::new(tl!("Resolution:"), Bind::given(Some(ppi))).range(1.0..=4608.0).step(1.0).unit(super::ppi_suffix()).show(ui);
|
||||
if let Some(Some(v)) = field.value().copied() {
|
||||
fields.set("ppi", v);
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
})
|
||||
.companions(["__otherPpi"])
|
||||
.opens_with(72.0)
|
||||
}
|
||||
|
||||
/// The pixel size the region of `w` × `h` points gives at the current resolution.
|
||||
fn size_row(w: f64, h: f64) -> Param {
|
||||
Param::custom("__sizeText", tl!("Size:"), move |ui, fields, _| {
|
||||
let (pw, ph) = vectorcraft_render::region_pixels(vectorcraft_geom::Rect::new(0.0, 0.0, w, h), fields.number("ppi").unwrap_or(72.0) / 72.0);
|
||||
ui.label(format!("{pw} × {ph} px"))
|
||||
})
|
||||
}
|
||||
|
||||
/// A colour row: one of `ids` shown by its label, or Other (the last label) with a swatch that
|
||||
/// asks the host's colour picker. The value is an id or `"#rrggbb"`. `first` is where the list
|
||||
/// starts for the current values.
|
||||
fn color_choice(
|
||||
key: &'static str,
|
||||
label: &'static str,
|
||||
ids: &'static [&'static str],
|
||||
labels: &'static [&'static str],
|
||||
first: impl Fn(&DialogFields) -> usize + Send + Sync + 'static,
|
||||
) -> Param {
|
||||
Param::custom(key, tl!(label), move |ui, fields, cx| {
|
||||
let current = fields.text(key).unwrap_or_default().to_string();
|
||||
let at = ids.iter().position(|v| current.eq_ignore_ascii_case(v)).unwrap_or(ids.len());
|
||||
let start = first(fields);
|
||||
let shown = at.max(start);
|
||||
ui.horizontal(|ui| {
|
||||
craft_ui::ComboBox::from_id_salt(("ro", key)).selected_text(tl!(labels.get(shown).copied().unwrap_or_default())).show_ui(ui, |ui| {
|
||||
for (i, l) in labels.iter().enumerate().skip(start) {
|
||||
if ui.selectable_label(i == shown, tl!(*l)).clicked() {
|
||||
fields.set(key, ids.get(i).copied().unwrap_or(OTHER_COLOR));
|
||||
}
|
||||
}
|
||||
});
|
||||
if at == ids.len() {
|
||||
let c = vectorcraft_color::Color::from_hex(¤t).map_or([128, 128, 128, 255], |c| c.to_rgba8(1.0));
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(28.0, 18.0), egui::Sense::click());
|
||||
ui.painter().rect_filled(rect, 2.0, egui::Color32::from_rgb(c[0], c[1], c[2]));
|
||||
if response.clicked() {
|
||||
cx.pick_color(key, craft::theme::Srgba::rgb(f32::from(c[0]) / 255.0, f32::from(c[1]) / 255.0, f32::from(c[2]) / 255.0));
|
||||
}
|
||||
}
|
||||
})
|
||||
.response
|
||||
})
|
||||
}
|
||||
|
||||
/// The picker answers a colour row with a colour value; the dialog keeps one representation, the
|
||||
/// `"#rrggbb"` text the export reads.
|
||||
fn normalize_colors(fields: &mut DialogFields) {
|
||||
for key in ["background", "matte"] {
|
||||
if let Some([r, g, b]) = fields.color(key) {
|
||||
let to8 = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8;
|
||||
fields.set(key, format!("#{:02x}{:02x}{:02x}", to8(r), to8(g), to8(b)));
|
||||
}
|
||||
"jpg" => jpeg_rows(ui, d, &label, screens),
|
||||
"gif" | "png8" => palette_rows(ui, d, &label),
|
||||
"webp" => webp_rows(ui, d, &label),
|
||||
"psd" => psd_options::rows(ui, d, &label),
|
||||
id => tiff_bmp_tga::rows(ui, d, id, &label),
|
||||
}
|
||||
}
|
||||
|
||||
/// The JPEG Options rows: colour model, quality, method and scans, profile and image map (not
|
||||
/// quality and image map for Export for Screens).
|
||||
fn jpeg_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response, screens: bool) {
|
||||
label(ui, tl!("Color Model:"));
|
||||
choice(ui, d, "colorModel", &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label));
|
||||
ui.end_row();
|
||||
|
||||
fn jpeg_rows(screens: bool) -> Vec<Param> {
|
||||
let mut rows = vec![choice("colorModel", tl!("Color Model:"), &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label))];
|
||||
if !screens {
|
||||
quality_row(ui, d, label);
|
||||
rows.push(quality_row());
|
||||
}
|
||||
method_row(ui, d, label);
|
||||
rows.push(choice("method", tl!("Method:"), &Method::ALL.map(Method::id), &Method::ALL.map(Method::label)));
|
||||
let scans = ParamKind::int(Some(i64::from(*jpeg::SCANS.start())), Some(i64::from(*jpeg::SCANS.end())), 3);
|
||||
rows.push(Param::new("scans", tl!("Scans:"), scans).visible_when("method", Method::Progressive.id()));
|
||||
if !screens {
|
||||
label(ui, tl!("Image Map:"));
|
||||
choice(ui, d, "imageMap", &IMAGE_MAPS, &IMAGE_MAP_LABELS);
|
||||
ui.end_row();
|
||||
rows.push(choice("imageMap", tl!("Image Map:"), &IMAGE_MAPS, &IMAGE_MAP_LABELS));
|
||||
}
|
||||
|
||||
ui.label("");
|
||||
form::check(ui, d, "embedIcc", tl!("Embed ICC Profile"));
|
||||
ui.end_row();
|
||||
rows.push(check("embedIcc", tl!("Embed ICC Profile"), true));
|
||||
rows
|
||||
}
|
||||
|
||||
/// JPEG quality on the dialog's 0–10 scale (stored ×10).
|
||||
fn quality_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Quality:"));
|
||||
let mut q = (d.f64("quality", 90.0) / 10.0).round().clamp(0.0, 10.0) as u8;
|
||||
ui.horizontal(|ui| {
|
||||
if widgets::slider(ui, egui::Slider::new(&mut q, 0..=10)).changed() {
|
||||
d.fields.insert("quality".into(), json!(u32::from(q) * 10));
|
||||
}
|
||||
label(ui, QUALITY_BANDS[q as usize]);
|
||||
});
|
||||
ui.end_row();
|
||||
fn quality_row() -> Param {
|
||||
Param::custom("quality", tl!("Quality:"), |ui, fields, _| {
|
||||
let mut q = (fields.number("quality").unwrap_or(90.0) / 10.0).round().clamp(0.0, 10.0) as u8;
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(egui::Slider::new(&mut q, 0..=10)).changed() {
|
||||
fields.set("quality", f64::from(q) * 10.0);
|
||||
}
|
||||
ui.label(tl!(QUALITY_BANDS.get(usize::from(q)).copied().unwrap_or_default()));
|
||||
})
|
||||
.response
|
||||
})
|
||||
.opens_with(90.0)
|
||||
}
|
||||
|
||||
/// The WebP Options rows: Lossless or Lossy compression, and the quality 0–100 that Lossy uses
|
||||
/// (dimmed while Lossless is chosen, keeping its value).
|
||||
fn webp_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Compression:"));
|
||||
let lossless = d.fields.get("lossless").and_then(Value::as_bool).unwrap_or(true);
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-webp", WEBP_COMPRESSION_LABELS[usize::from(!lossless)], &WEBP_COMPRESSION_LABELS, 150.0) {
|
||||
d.fields.insert("lossless".into(), json!(i == 0));
|
||||
}
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Quality:"));
|
||||
let mut q = d.f64("quality", f64::from(WEBP_QUALITY)).round().clamp(0.0, 100.0) as u8;
|
||||
ui.add_enabled_ui(!lossless, |ui| {
|
||||
if widgets::slider(ui, egui::Slider::new(&mut q, 0..=100)).changed() {
|
||||
d.fields.insert("quality".into(), json!(q));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
/// The JPEG method, and its scans when progressive.
|
||||
fn method_row(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Method:"));
|
||||
ui.horizontal(|ui| {
|
||||
choice(ui, d, "method", &Method::ALL.map(Method::id), &Method::ALL.map(Method::label));
|
||||
if Method::from_id(&d.str("method")) == Some(Method::Progressive) {
|
||||
label(ui, tl!("Scans:"));
|
||||
let range = f64::from(*jpeg::SCANS.start())..=f64::from(*jpeg::SCANS.end());
|
||||
if let Some(scans) = widgets::range_field(ui, "scans", d.f64("scans", 3.0), range, "", 0, 44.0) {
|
||||
d.fields.insert("scans".into(), json!(scans as u8));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
/// (disabled while Lossless is chosen, keeping its value).
|
||||
fn webp_rows() -> Vec<Param> {
|
||||
let [lossless, lossy] = WEBP_COMPRESSION_LABELS;
|
||||
let compression = ParamKind::radio(vec![("true".into(), tl!(lossless).into()), ("false".into(), tl!(lossy).into())], Some("true".into()));
|
||||
vec![
|
||||
Param::new("lossless", tl!("Compression:"), compression),
|
||||
Param::new("quality", tl!("Quality:"), ParamKind::range(0.0, 100.0, f64::from(WEBP_QUALITY), SliderScale::Linear)).enabled_when("lossless", "false"),
|
||||
]
|
||||
}
|
||||
|
||||
/// The PNG-8 and GIF Options rows: the palette (reduction, colours, dither and amount),
|
||||
/// transparency and matte, interlacing.
|
||||
fn palette_rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Color Reduction:"));
|
||||
choice(ui, d, "reduction", &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label));
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Colors:"));
|
||||
let mut n = d.f64("colors", 256.0).round().clamp(2.0, 256.0) as u16;
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-colors", &n.to_string(), &COLOR_COUNTS, 70.0) {
|
||||
n = COLOR_COUNTS.get(i).and_then(|c| c.parse().ok()).unwrap_or(n);
|
||||
d.fields.insert("colors".into(), json!(n));
|
||||
}
|
||||
if let Some(n) = widgets::range_field(ui, "colors", f64::from(n), 2.0..=256.0, "", 0, 52.0) {
|
||||
d.fields.insert("colors".into(), json!(n as u16));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Dither:"));
|
||||
ui.horizontal(|ui| {
|
||||
choice(ui, d, "dither", &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label));
|
||||
if Dither::from_id(&d.str("dither")).is_some_and(|x| x != Dither::None)
|
||||
&& let Some(amount) = widgets::range_field(ui, "ditherAmount", d.f64("ditherAmount", 100.0), 0.0..=100.0, "%", 0, 52.0)
|
||||
{
|
||||
d.fields.insert("ditherAmount".into(), json!(amount as u8));
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Matte:"));
|
||||
let matte = d.str("matte");
|
||||
let at = MATTES.iter().position(|v| matte.eq_ignore_ascii_case(v)).unwrap_or(3);
|
||||
ui.horizontal(|ui| {
|
||||
if let Some(i) = widgets::dropdown(ui, "ro-matte", MATTE_LABELS[at], &MATTE_LABELS, 150.0) {
|
||||
d.fields.insert("matte".into(), json!(MATTES.get(i).copied().unwrap_or("#808080")));
|
||||
}
|
||||
if at == 3 {
|
||||
color_button(ui, d, "matte");
|
||||
}
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("");
|
||||
ui.horizontal(|ui| {
|
||||
form::check(ui, d, "transparency", tl!("Transparency"));
|
||||
form::check(ui, d, "interlaced", tl!("Interlaced"));
|
||||
});
|
||||
ui.end_row();
|
||||
fn palette_rows() -> Vec<Param> {
|
||||
let dithering = Dither::ALL.iter().copied().filter(|d| *d != Dither::None).map(Dither::id);
|
||||
vec![
|
||||
choice("reduction", tl!("Color Reduction:"), &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label)),
|
||||
Param::new("colors", tl!("Colors:"), ParamKind::int(Some(2), Some(256), 256)),
|
||||
choice("dither", tl!("Dither:"), &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label)),
|
||||
Param::new("ditherAmount", tl!("Dither Amount:"), ParamKind::int(Some(0), Some(100), 100)).enabled_when_in("dither", dithering),
|
||||
color_choice("matte", tl!("Matte:"), &MATTES, &MATTE_LABELS, |_| 0),
|
||||
check("transparency", tl!("Transparency"), true),
|
||||
check("interlaced", tl!("Interlaced"), false),
|
||||
]
|
||||
}
|
||||
|
||||
/// A colour button bound to `d.fields[key]` (`"#rrggbb"`; grey when unset).
|
||||
pub(super) fn color_button(ui: &mut egui::Ui, d: &mut Dialog, key: &str) {
|
||||
let c = vectorcraft_color::Color::from_hex(&d.str(key)).map_or([128, 128, 128, 255], |c| c.to_rgba8(1.0));
|
||||
let mut rgb = [c[0], c[1], c[2]];
|
||||
if ui.color_edit_button_srgb(&mut rgb).changed() {
|
||||
d.fields.insert(key.into(), json!(format!("#{:02x}{:02x}{:02x}", rgb[0], rgb[1], rgb[2])));
|
||||
}
|
||||
}
|
||||
|
||||
/// A dropdown bound to `d.fields[key]`: one of `ids`, shown by its label (the first when unknown).
|
||||
pub(super) fn choice(ui: &mut egui::Ui, d: &mut Dialog, key: &str, ids: &[&str], labels: &[&str]) {
|
||||
let cur = d.str(key);
|
||||
let at = ids.iter().position(|v| v.eq_ignore_ascii_case(&cur)).unwrap_or(0);
|
||||
if let Some(i) = widgets::dropdown(ui, ("ro", key), labels.get(at).copied().unwrap_or_default(), labels, 150.0)
|
||||
&& let Some(v) = ids.get(i)
|
||||
{
|
||||
d.fields.insert(key.into(), json!(v));
|
||||
/// Whole-number params the rows hold as floats or option ids are written as integers, as the
|
||||
/// export reads them.
|
||||
fn integers(params: &mut Value) {
|
||||
let Some(o) = params.as_object_mut() else { return };
|
||||
for key in INTEGER_KEYS {
|
||||
let number = match o.get(key) {
|
||||
Some(Value::String(text)) => text.parse::<f64>().ok(),
|
||||
Some(Value::Number(n)) => n.as_f64().filter(|_| !n.is_u64() && !n.is_i64()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(n) = number.filter(|n| n.is_finite() && n.fract() == 0.0 && *n >= 0.0) {
|
||||
o.insert(key.into(), json!(n as u64));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the file(s) with the chosen options.
|
||||
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
|
||||
let (format, path) = (d.str("format"), d.str("path"));
|
||||
app.ui.dialog = None;
|
||||
let mut params = form::params(d);
|
||||
pub(super) fn confirm(app: &mut VectorcraftApp, open: &Open, fields: &DialogFields) -> Result<After, String> {
|
||||
let format = fields.text("format").unwrap_or_default().to_string();
|
||||
let path = fields.text("path").unwrap_or_default().to_string();
|
||||
let id = fileio::format(&format).map_or("png", |f| f.id);
|
||||
let mut params = Value::Object(json_of(&raster_rows(id, false, None, fields), fields));
|
||||
integers(&mut params);
|
||||
if format == "psd" {
|
||||
psd_options::drop_unused(&mut params);
|
||||
}
|
||||
io::export(app, Some(&format), Some(path), &super::export_as::exported(d, params))
|
||||
// PLAN: assumed `After: From<Value>` (the export's result, what ex.A1's `confirm` hands the host).
|
||||
io::export(app, Some(&format), Some(path), &super::export_as::exported(open.selection, params)).map(After::from)
|
||||
}
|
||||
|
||||
@@ -2,13 +2,12 @@
|
||||
//! Editability, hidden layers, profile), after the raster export rows it shares with PNG Options ([`super::png_options`]): the
|
||||
//! `psdOptions` dialog.
|
||||
|
||||
use craft_ui::patterns::form_dialogs::{Param, ParamKind};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_render::encode::jpeg::ColorModel;
|
||||
use vectorcraft_render::encode::psd::PsdOptions;
|
||||
|
||||
use super::form;
|
||||
use super::png_options::choice;
|
||||
use crate::state::Dialog;
|
||||
use super::png_options::{check, choice};
|
||||
|
||||
/// The options PSD starts with (`cmyk`: a CMYK document exports CMYK).
|
||||
pub(super) fn defaults(cmyk: bool, o: &mut Map<String, Value>) {
|
||||
@@ -34,34 +33,15 @@ pub(super) fn drop_unused(p: &mut Value) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid rows of PSD's own options.
|
||||
pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, label: &dyn Fn(&mut egui::Ui, &str) -> egui::Response) {
|
||||
label(ui, tl!("Color Model:"));
|
||||
choice(ui, d, "colorModel", &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label));
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Options:"));
|
||||
ui.vertical(|ui| {
|
||||
let mut layers = d.bool("layers");
|
||||
if ui.radio_value(&mut layers, false, tl!("Flat Image")).changed() | ui.radio_value(&mut layers, true, tl!("Write Layers")).changed() {
|
||||
d.fields.insert("layers".into(), json!(layers));
|
||||
}
|
||||
ui.add_enabled_ui(layers, |ui| {
|
||||
for (key, text) in [
|
||||
("preserveText", tl!("Preserve Text Editability")),
|
||||
("maxEditability", tl!("Maximum Editability")),
|
||||
("hiddenLayers", tl!("Include Hidden Layers")),
|
||||
] {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_space(22.0);
|
||||
form::check(ui, d, key, text);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.end_row();
|
||||
|
||||
ui.label("");
|
||||
form::check(ui, d, "embedIcc", tl!("Embed ICC Profile"));
|
||||
ui.end_row();
|
||||
/// The rows of PSD's own options. `layers` is a two-id radio, so the export sees a boolean.
|
||||
pub(super) fn params() -> Vec<Param> {
|
||||
let layers = ParamKind::radio(vec![("false".into(), tl!("Flat Image").into()), ("true".into(), tl!("Write Layers").into())], Some("true".into()));
|
||||
vec![
|
||||
choice("colorModel", tl!("Color Model:"), &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label)),
|
||||
Param::new("layers", tl!("Options:"), layers),
|
||||
check("preserveText", tl!("Preserve Text Editability"), false).enabled_when("layers", "true"),
|
||||
check("maxEditability", tl!("Maximum Editability"), false).enabled_when("layers", "true"),
|
||||
check("hiddenLayers", tl!("Include Hidden Layers"), false).enabled_when("layers", "true"),
|
||||
check("embedIcc", tl!("Embed ICC Profile"), true),
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,51 +1,27 @@
|
||||
//! PSD Options through Export As, drawn headlessly.
|
||||
//! PSD Options' rule for transparency, and its starting colour model.
|
||||
|
||||
use serde_json::json;
|
||||
use craft_ui::patterns::form_dialogs::DialogFields;
|
||||
use serde_json::{Map, json};
|
||||
|
||||
use super::tests_export::{app, frame, kind, set};
|
||||
use super::*;
|
||||
|
||||
/// A flat PSD is flattened on white, so its background list starts at White; layers keep
|
||||
/// transparency. The row `layers` is a two-id radio, so it holds the id text.
|
||||
#[test]
|
||||
fn psd_options_pick_flat_or_layers_and_the_colour_model() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "psd"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("psdOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((spec(&d.kind).heading)(d), "PSD Options");
|
||||
assert_eq!(
|
||||
(d.str("colorModel"), d.bool("layers"), d.bool("preserveText"), d.bool("maxEditability"), d.bool("hiddenLayers"), d.bool("embedIcc")),
|
||||
("rgb".into(), true, false, false, false, true)
|
||||
);
|
||||
assert!(tiff_bmp_tga::keeps_alpha("psd", d), "layers keep transparency");
|
||||
frame(&mut app);
|
||||
set(&mut app, "maxEditability", json!(true));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, psd) = written.borrow()[0].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.psd");
|
||||
assert_eq!(&psd[..4], b"8BPS");
|
||||
// A group with the ellipse: three records, the merged image's alpha their transparency.
|
||||
let at = 26 + 4 + 4 + u32::from_be_bytes(psd[30..34].try_into().unwrap()) as usize;
|
||||
assert_eq!(i16::from_be_bytes([psd[at + 8], psd[at + 9]]), -3);
|
||||
assert!(app.ui.dialog.is_none());
|
||||
|
||||
// Flat: flattened on white, so the background list starts at White. Preserve Text
|
||||
// Editability, still ticked, isn't sent: the export refuses it without layers.
|
||||
app.run("file.exportAs", json!({"format": "psd"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
set(&mut app, "preserveText", json!(true));
|
||||
set(&mut app, "layers", json!(false));
|
||||
set(&mut app, "colorModel", json!("gray"));
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("psd", app.ui.dialog.as_ref().unwrap()));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let psd = written.borrow()[1].1.clone();
|
||||
assert_eq!((u16::from_be_bytes([psd[12], psd[13]]), u16::from_be_bytes([psd[24], psd[25]])), (1, 1), "one grey channel");
|
||||
|
||||
// A CMYK document exports CMYK by default.
|
||||
app.run("object.convertDocumentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("file.exportAs", json!({"format": "psd"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "cmyk");
|
||||
fn a_flat_psd_is_flattened_and_layers_keep_transparency() {
|
||||
let layers = DialogFields::from_pairs([("layers", "true")]);
|
||||
let flat = DialogFields::from_pairs([("layers", "false")]);
|
||||
assert!(tiff_bmp_tga::keeps_alpha("psd", &layers));
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("psd", &flat));
|
||||
}
|
||||
|
||||
/// A CMYK document exports CMYK by default.
|
||||
#[test]
|
||||
fn psd_starts_in_cmyk_for_a_cmyk_document() {
|
||||
let mut o = Map::new();
|
||||
psd_options::defaults(true, &mut o);
|
||||
assert_eq!(o["colorModel"], json!("cmyk"));
|
||||
let mut o = Map::new();
|
||||
psd_options::defaults(false, &mut o);
|
||||
assert_eq!(o["colorModel"], json!("rgb"));
|
||||
}
|
||||
|
||||
@@ -3,9 +3,17 @@
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog};
|
||||
|
||||
use super::tests_export::{app, frame, kind, set};
|
||||
use super::*;
|
||||
|
||||
/// The values of the open options dialog.
|
||||
pub(super) fn fields(app: &VectorcraftApp) -> DialogFields {
|
||||
// PLAN: assumed the open dialog is a `HostedParamDialog` on the window host (`app.dialogs()`, hub-w3).
|
||||
app.dialogs().get::<HostedParamDialog>().map(|d| d.fields().clone()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A JPEG's SOF marker and component count.
|
||||
fn jpeg_frame(file: &[u8]) -> (u8, u8) {
|
||||
let mut i = 2;
|
||||
@@ -15,68 +23,63 @@ fn jpeg_frame(file: &[u8]) -> (u8, u8) {
|
||||
(file[i + 1], file[i + 9])
|
||||
}
|
||||
|
||||
/// Each raster format's option rows, set as the user sets them, reach the written file:
|
||||
/// `(format, the rows set, what the file shows)`.
|
||||
#[test]
|
||||
fn jpeg_options_pick_the_colour_model_method_and_profile() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "jpg"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("jpgOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
(d.str("colorModel"), d.str("method"), d.f64("scans", 0.0), d.bool("embedIcc"), d.str("imageMap")),
|
||||
("rgb".into(), "baseline".into(), 3.0, true, "none".into())
|
||||
);
|
||||
frame(&mut app);
|
||||
set(&mut app, "method", json!("progressive"));
|
||||
set(&mut app, "scans", json!(4));
|
||||
set(&mut app, "colorModel", json!("cmyk"));
|
||||
set(&mut app, "quality", json!(30));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let file = written.borrow()[0].1.clone();
|
||||
assert_eq!(jpeg_frame(&file), (0xC2, 4), "progressive CMYK");
|
||||
assert!(file.windows(12).any(|w| w == b"ICC_PROFILE\0"));
|
||||
|
||||
// A CMYK document exports CMYK by default.
|
||||
app.run("object.convertDocumentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("file.exportAs", json!({"format": "jpg"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "cmyk");
|
||||
fn raster_option_rows_reach_the_export_params() {
|
||||
type Check = fn(&[u8]);
|
||||
let rows: [(&str, &[(&str, serde_json::Value)], Check); 8] = [
|
||||
("jpg", &[("method", json!("progressive")), ("scans", json!(4)), ("colorModel", json!("cmyk")), ("quality", json!(30))], |file| {
|
||||
assert_eq!(jpeg_frame(file), (0xC2, 4), "progressive CMYK");
|
||||
assert!(file.windows(12).any(|w| w == b"ICC_PROFILE\0"));
|
||||
}),
|
||||
("gif", &[("colors", json!(4)), ("dither", json!("pattern")), ("matte", json!("#336699")), ("interlaced", json!(true))], |gif| {
|
||||
assert_eq!(&gif[..6], b"GIF89a");
|
||||
assert_eq!(gif[10] & 0x07, 1, "a global colour table of 4 entries");
|
||||
}),
|
||||
("png8", &[("reduction", json!("gray"))], |png| assert_eq!(png[25], 3, "indexed")),
|
||||
("webp", &[("lossless", json!(false)), ("quality", json!(40))], |file| {
|
||||
assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy");
|
||||
}),
|
||||
("tiff", &[("byteOrder", json!("big")), ("colorModel", json!("cmyk")), ("lzw", json!(false))], |tiff| assert_eq!(&tiff[..4], b"MM\0*")),
|
||||
("tga", &[("depth", json!("32"))], |tga| assert_eq!((tga[16], tga[17]), (32, 8))),
|
||||
("psd", &[("maxEditability", json!(true))], |psd| {
|
||||
assert_eq!(&psd[..4], b"8BPS");
|
||||
// A group with the ellipse: three records, the merged image's alpha their transparency.
|
||||
let at = 26 + 4 + 4 + u32::from_be_bytes(psd[30..34].try_into().unwrap()) as usize;
|
||||
assert_eq!(i16::from_be_bytes([psd[at + 8], psd[at + 9]]), -3);
|
||||
}),
|
||||
// Flat, flattened on white; Preserve Text Editability, still ticked, isn't sent: the export refuses it without layers.
|
||||
("psd", &[("preserveText", json!(true)), ("layers", json!(false)), ("colorModel", json!("gray"))], |psd| {
|
||||
assert_eq!((u16::from_be_bytes([psd[12], psd[13]]), u16::from_be_bytes([psd[24], psd[25]])), (1, 1), "one grey channel");
|
||||
}),
|
||||
];
|
||||
for (format, sets, check) in rows {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": format})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app).map(|k| k.strip_suffix("Options").map(str::to_string)), Some(Some(format.to_string())));
|
||||
frame(&mut app);
|
||||
for (key, value) in sets {
|
||||
set(&mut app, key, value.clone());
|
||||
}
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap_or_else(|e| panic!("{format}: {e}"));
|
||||
let file = written.borrow()[0].1.clone();
|
||||
check(&file);
|
||||
}
|
||||
}
|
||||
|
||||
/// A CMYK document starts the colour-model formats in CMYK.
|
||||
#[test]
|
||||
fn palette_options_reduce_the_colours() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "gif"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("gifOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((spec(&d.kind).heading)(d), "GIF Options");
|
||||
assert_eq!(
|
||||
(d.str("reduction"), d.f64("colors", 0.0), d.str("dither"), d.bool("transparency"), d.str("matte")),
|
||||
("selective".into(), 256.0, "diffusion".into(), true, "white".into())
|
||||
);
|
||||
frame(&mut app);
|
||||
set(&mut app, "colors", json!(4));
|
||||
set(&mut app, "dither", json!("pattern"));
|
||||
set(&mut app, "matte", json!("#336699"));
|
||||
set(&mut app, "interlaced", json!(true));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, gif) = written.borrow()[0].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.gif");
|
||||
assert_eq!(&gif[..6], b"GIF89a");
|
||||
assert_eq!(gif[10] & 0x07, 1, "a global colour table of 4 entries");
|
||||
|
||||
app.run("file.exportAs", json!({"format": "png8"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("png8Options"));
|
||||
set(&mut app, "reduction", json!("gray"));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, png) = written.borrow()[1].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.png");
|
||||
assert_eq!(png[25], 3, "indexed");
|
||||
fn a_cmyk_document_exports_cmyk_by_default() {
|
||||
let (mut app, _) = app(1);
|
||||
app.run("object.convertDocumentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
for format in ["jpg", "tiff", "psd"] {
|
||||
app.run("file.exportAs", json!({"format": format})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(fields(&app).text("colorModel"), Some("cmyk"), "{format}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -86,8 +89,7 @@ fn text_export_options_write_the_stories() {
|
||||
app.run("file.exportAs", json!({"format": "txt"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("txtOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((d.str("path"), d.str("encoding")), ("/out/Untitled-1.txt".into(), "utf8".into()));
|
||||
assert_eq!((fields(&app).text("path"), fields(&app).text("encoding")), (Some("/out/Untitled-1.txt"), Some("utf8")));
|
||||
frame(&mut app);
|
||||
set(&mut app, "lineEndings", json!("crlf"));
|
||||
set(&mut app, "encoding", json!("bogus"));
|
||||
@@ -96,53 +98,22 @@ fn text_export_options_write_the_stories() {
|
||||
set(&mut app, "encoding", json!("utf8"));
|
||||
frame(&mut app);
|
||||
assert_eq!(confirm(&mut app).unwrap()["path"], "/out/Untitled-1.txt");
|
||||
assert!(app.ui.dialog.is_none());
|
||||
assert_eq!(kind(&app), None);
|
||||
let (path, bytes) = written.borrow().last().cloned().unwrap();
|
||||
assert_eq!((path.as_str(), bytes.as_slice()), ("/out/Untitled-1.txt", &b"Hello\r\nthere\r\n"[..]));
|
||||
}
|
||||
|
||||
/// WebP Options: Lossless by default, with the Quality slider disabled; Lossy enables it, and OK
|
||||
/// writes a lossy file at that quality, without a note.
|
||||
/// WebP is lossless by default, and OK writes a lossless file without a note.
|
||||
#[test]
|
||||
fn webp_options_choose_lossless_or_lossy_at_a_quality() {
|
||||
use crate::widgets::accessibility_tests::tree;
|
||||
use egui::accesskit::Role;
|
||||
let quality_disabled = |app: &mut VectorcraftApp| {
|
||||
let t = tree(|ui| show(app, ui.ctx()));
|
||||
t.iter().find(|n| n.role() == Role::Slider).expect("the Quality slider").is_disabled()
|
||||
};
|
||||
fn webp_is_lossless_by_default() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "webp"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("webpOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((&d.fields["lossless"], &d.fields["quality"]), (&json!(true), &json!(90)));
|
||||
assert!(quality_disabled(&mut app), "Quality applies to Lossy");
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default");
|
||||
|
||||
app.run("file.exportAs", json!({"format": "webp"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
set(&mut app, "lossless", json!(false));
|
||||
set(&mut app, "quality", json!(40));
|
||||
assert!(!quality_disabled(&mut app), "Lossy enables Quality");
|
||||
frame(&mut app);
|
||||
// The dialog's options, as `document.export` takes them.
|
||||
let mut options = app.ui.dialog.as_ref().unwrap().fields.clone();
|
||||
options.retain(|k, _| !k.starts_with("__") && k != "path");
|
||||
let r = confirm(&mut app).unwrap();
|
||||
assert_eq!(r["warnings"], json!([]), "{r}");
|
||||
let file = written.borrow().last().unwrap().1.clone();
|
||||
assert!(file.windows(4).any(|w| w == b"VP8 ") && !file.windows(4).any(|w| w == b"VP8L"), "lossy");
|
||||
// The file is the one `document.export` writes with those options at quality 40.
|
||||
let at = |app: &mut VectorcraftApp, q: u8| {
|
||||
let mut p = options.clone();
|
||||
p.insert("quality".into(), json!(q));
|
||||
vectorcraft_format::base64_decode(app.run("document.export", serde_json::Value::Object(p)).unwrap()["dataBase64"].as_str().unwrap()).unwrap()
|
||||
};
|
||||
assert_eq!(file, at(&mut app, 40));
|
||||
assert_ne!(file, at(&mut app, 90));
|
||||
assert_eq!(&written.borrow()[0].1[12..16], b"VP8L", "lossless by default");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -2,6 +2,7 @@ use serde_json::json;
|
||||
use vectorcraft_engine::cmd::fileio;
|
||||
|
||||
use super::tests_export::{app, frame, kind};
|
||||
use super::tests_raster_formats::fields;
|
||||
use super::{confirm, png_options};
|
||||
|
||||
#[test]
|
||||
@@ -9,11 +10,11 @@ fn raster_options_preserve_supplied_values_through_the_png_command() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.export.png", json!({"ppi": 300, "background": "#204080", "antiAlias": "type", "interlaced": true})).unwrap();
|
||||
assert_eq!(kind(&app), Some("pngOptions"));
|
||||
let fields = &app.ui.dialog.as_ref().unwrap().fields;
|
||||
assert_eq!(fields["ppi"], 300);
|
||||
assert_eq!(fields["background"], "#204080");
|
||||
assert_eq!(fields["antiAlias"], "type");
|
||||
assert_eq!(fields["interlaced"], true);
|
||||
let f = fields(&app);
|
||||
assert_eq!(f.number("ppi"), Some(300.0));
|
||||
assert_eq!(f.text("background"), Some("#204080"));
|
||||
assert_eq!(f.text("antiAlias"), Some("type"));
|
||||
assert_eq!(f.bool("interlaced"), Some(true));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
{
|
||||
@@ -29,26 +30,26 @@ fn raster_options_preserve_supplied_values_through_the_png_command() {
|
||||
}
|
||||
|
||||
png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/supplied.jpg", "ppi": 144, "quality": 40}));
|
||||
let fields = &app.ui.dialog.as_ref().unwrap().fields;
|
||||
assert_eq!(fields["quality"], 40);
|
||||
assert_eq!(fields["ppi"], 144);
|
||||
assert_eq!(fields["background"], "white");
|
||||
let f = fields(&app);
|
||||
assert_eq!(f.number("quality"), Some(40.0));
|
||||
assert_eq!(f.number("ppi"), Some(144.0));
|
||||
assert_eq!(f.text("background"), Some("white"));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(written.borrow().len(), 2);
|
||||
|
||||
// Opening again replaces the open dialog of the same kind.
|
||||
for omitted in [json!({}), json!({"ppi": null, "background": null, "antiAlias": null, "interlaced": null})] {
|
||||
app.run("file.export.png", omitted).unwrap();
|
||||
let fields = &app.ui.dialog.as_ref().unwrap().fields;
|
||||
assert_eq!(fields["ppi"], 72);
|
||||
assert_eq!(fields["background"], "transparent");
|
||||
assert_eq!(fields["antiAlias"], "art");
|
||||
assert_eq!(fields["interlaced"], false);
|
||||
app.ui.dialog = None;
|
||||
let f = fields(&app);
|
||||
assert_eq!(f.number("ppi"), Some(72.0));
|
||||
assert_eq!(f.text("background"), Some("transparent"));
|
||||
assert_eq!(f.text("antiAlias"), Some("art"));
|
||||
assert_eq!(f.bool("interlaced"), Some(false));
|
||||
}
|
||||
|
||||
app.run("file.export.png", json!({"ppi": 0})).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ppi"], 0);
|
||||
assert_eq!(fields(&app).number("ppi"), Some(0.0));
|
||||
assert!(confirm(&mut app).unwrap_err().contains("ppi must be a positive number"));
|
||||
assert_eq!(written.borrow().len(), 2);
|
||||
}
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
//! Persistent-context pointer coverage of SVG artboard range validation and recovery.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use egui::{Event, Pos2, Rect, Shape, vec2};
|
||||
use serde_json::json;
|
||||
use vectorcraft_engine::Session;
|
||||
|
||||
use crate::{Services, VectorcraftApp};
|
||||
|
||||
use super::tests_export::Written;
|
||||
|
||||
struct ExportHarness {
|
||||
app: VectorcraftApp,
|
||||
ctx: egui::Context,
|
||||
written: Written,
|
||||
time: f64,
|
||||
}
|
||||
|
||||
impl ExportHarness {
|
||||
fn new() -> Self {
|
||||
let written = Rc::new(RefCell::new(vec![]));
|
||||
let w = written.clone();
|
||||
let services = Services {
|
||||
pick_save: Some(Box::new(|p: &crate::FilePick| Some(format!("/out/{}", p.name)))),
|
||||
write: Some(Box::new(move |p: &str, b: &[u8]| {
|
||||
w.borrow_mut().push((p.to_string(), b.to_vec()));
|
||||
Ok(())
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = VectorcraftApp::new(Session::new(), services);
|
||||
app.run("file.new", json!({"width": 80, "height": 60, "artboards": 80})).unwrap();
|
||||
app.run("paint.setStroke", json!({"none": true})).unwrap();
|
||||
for (i, name, colour, width, height) in
|
||||
[(0, "FirstArt", "#cc2200", 11, 13), (78, "OtherArt", "#2244cc", 9, 7), (79, "LastArt", "#00aa88", 17, 19)]
|
||||
{
|
||||
let r = app.session.active().unwrap().doc.artboards[i].rect;
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
app.run("paint.setFill", json!({"color": colour})).unwrap();
|
||||
app.run("shape.rectangle", json!({"x": r.x0 + 7.0, "y": r.y0 + 11.0, "width": width, "height": height})).unwrap();
|
||||
app.run("object.setProps", json!({"name": name})).unwrap();
|
||||
}
|
||||
app.run("select.none", json!({})).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
crate::theme::install_fonts(&ctx);
|
||||
Self { app, ctx, written, time: 0.0 }
|
||||
}
|
||||
|
||||
fn frame(&mut self, events: Vec<Event>) -> egui::FullOutput {
|
||||
self.time += 0.1;
|
||||
let input = egui::RawInput {
|
||||
events,
|
||||
time: Some(self.time),
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 900.0))),
|
||||
..Default::default()
|
||||
};
|
||||
let mut out = self.ctx.run_ui(input, |ui| super::show(&mut self.app, ui.ctx()));
|
||||
out.textures_delta.clear();
|
||||
out
|
||||
}
|
||||
|
||||
fn settle(&mut self) -> egui::FullOutput {
|
||||
self.frame(vec![]);
|
||||
self.frame(vec![])
|
||||
}
|
||||
|
||||
fn click(&mut self, at: Pos2) -> egui::FullOutput {
|
||||
let button = |pressed| Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
|
||||
self.frame(vec![Event::PointerMoved(at)]);
|
||||
self.frame(vec![button(true)]);
|
||||
self.frame(vec![button(false)]);
|
||||
self.settle()
|
||||
}
|
||||
|
||||
fn choose_range(&mut self, format: &str, range: &str) {
|
||||
self.app.run("file.exportAs", json!({"format": format})).unwrap();
|
||||
let out = self.settle();
|
||||
let out = self.click(text_at(&out, "Use Artboards"));
|
||||
let out = self.click(text_at(&out, "Range:"));
|
||||
assert!(!self.app.ui.dialog.as_ref().unwrap().bool("all"));
|
||||
self.click(text_at(&out, "1-80"));
|
||||
self.frame(vec![Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }]);
|
||||
let out = self.frame(vec![Event::Text(range.into())]);
|
||||
assert_eq!(self.app.ui.dialog.as_ref().unwrap().str("range"), range);
|
||||
assert!(self.written.borrow().is_empty());
|
||||
self.click(text_at(&out, "Export…"));
|
||||
let d = self.app.ui.dialog.as_ref().unwrap();
|
||||
assert!(d.bool("useArtboards"));
|
||||
assert_eq!(d.str("range"), range);
|
||||
}
|
||||
|
||||
fn finish(&mut self, button: &str) {
|
||||
let out = self.settle();
|
||||
self.click(text_at(&out, button));
|
||||
assert!(self.app.ui.dialog.is_none(), "{}", self.app.ui.status);
|
||||
}
|
||||
}
|
||||
|
||||
fn text_at(out: &egui::FullOutput, label: &str) -> Pos2 {
|
||||
fn find(shape: &Shape, label: &str) -> Option<Pos2> {
|
||||
match shape {
|
||||
Shape::Text(t) if t.galley.text().trim() == label => Some(t.pos + vec2(4.0, 4.0)),
|
||||
Shape::Vec(v) => v.iter().find_map(|s| find(s, label)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
out.shapes.iter().find_map(|s| find(&s.shape, label)).unwrap_or_else(|| panic!("missing {label}: {}", crate::tests_labels::shapes_text(out)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_range_preserves_export_dialog_and_writes_nothing() {
|
||||
let mut h = ExportHarness::new();
|
||||
h.app.run("file.exportAs", json!({"format": "svg", "useArtboards": true, "range": "81"})).unwrap();
|
||||
let out = h.settle();
|
||||
h.click(text_at(&out, "Export…"));
|
||||
assert_eq!(h.app.ui.dialog.as_ref().unwrap().kind, "exportAs");
|
||||
assert!(h.written.borrow().is_empty());
|
||||
assert!(h.app.ui.status.contains("81"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_range_in_svg_options_keeps_the_modal_and_saved_options() {
|
||||
let mut h = ExportHarness::new();
|
||||
h.choose_range("svg", "80");
|
||||
let saved = h.app.ui.svg_options.clone();
|
||||
let out = h.settle();
|
||||
h.click(text_at(&out, "80"));
|
||||
h.frame(vec![Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }]);
|
||||
let out = h.frame(vec![Event::Text("81".into())]);
|
||||
assert_eq!(h.app.ui.dialog.as_ref().unwrap().str("range"), "81");
|
||||
h.click(text_at(&out, "OK"));
|
||||
assert_eq!(h.app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("svgOptions"));
|
||||
assert_eq!(h.app.ui.svg_options, saved);
|
||||
assert!(h.written.borrow().is_empty());
|
||||
assert!(h.app.ui.status.contains("81"));
|
||||
let out = h.settle();
|
||||
h.click(text_at(&out, "81"));
|
||||
h.frame(vec![Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }]);
|
||||
h.frame(vec![Event::Text("80".into())]);
|
||||
h.finish("OK");
|
||||
assert_eq!(h.written.borrow().len(), 1);
|
||||
let written = h.written.borrow();
|
||||
let svg = std::str::from_utf8(&written[0].1).unwrap();
|
||||
assert!(svg.contains("viewBox=\"0 0 80 60\"") && svg.contains("LastArt"));
|
||||
}
|
||||
@@ -1,81 +1,46 @@
|
||||
//! TIFF, BMP and Targa Options through Export As, drawn headlessly.
|
||||
//! BMP options and the Targa depth's rule for transparency, drawn headlessly. TIFF and Targa's
|
||||
//! rows reaching the file are rows of `raster_option_rows_reach_the_export_params`.
|
||||
|
||||
use craft_ui::patterns::form_dialogs::DialogFields;
|
||||
use serde_json::json;
|
||||
|
||||
use super::tests_export::{app, frame, kind, set};
|
||||
use super::tests_raster_formats::fields;
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tiff_options_pick_the_model_byte_order_and_compression() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "tiff"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("tiffOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!((spec(&d.kind).heading)(d), "TIFF Options");
|
||||
assert_eq!((d.str("colorModel"), d.str("byteOrder"), d.bool("lzw"), d.bool("embedIcc")), ("rgb".into(), "little".into(), true, true));
|
||||
frame(&mut app);
|
||||
set(&mut app, "byteOrder", json!("big"));
|
||||
set(&mut app, "colorModel", json!("cmyk"));
|
||||
set(&mut app, "lzw", json!(false));
|
||||
frame(&mut app);
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, tiff) = written.borrow()[0].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.tif");
|
||||
assert_eq!(&tiff[..4], b"MM\0*");
|
||||
assert!(app.ui.dialog.is_none());
|
||||
|
||||
// A CMYK document exports CMYK by default.
|
||||
app.run("object.convertDocumentColorMode", json!({"mode": "cmyk"})).unwrap();
|
||||
app.run("file.exportAs", json!({"format": "tiff"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().str("colorModel"), "cmyk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bmp_options_keep_their_choices_writable() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "bmp"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("bmpOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
let f = fields(&app);
|
||||
assert_eq!(
|
||||
(d.str("colorModel"), d.str("fileFormat"), d.f64("depth", 0.0), d.bool("rle"), d.bool("flipRows")),
|
||||
("rgb".into(), "windows".into(), 24.0, false, false)
|
||||
(f.text("colorModel"), f.text("fileFormat"), f.text("depth"), f.bool("rle"), f.bool("flipRows")),
|
||||
(Some("rgb"), Some("windows"), Some("24"), Some(false), Some(false))
|
||||
);
|
||||
frame(&mut app);
|
||||
// OS/2 has no 32 bits: the depth falls back to 24.
|
||||
set(&mut app, "fileFormat", json!("os2"));
|
||||
set(&mut app, "depth", json!(32));
|
||||
set(&mut app, "depth", json!("32"));
|
||||
frame(&mut app);
|
||||
assert_eq!(app.ui.dialog.as_ref().unwrap().f64("depth", 0.0), 24.0);
|
||||
assert_eq!(fields(&app).text("depth"), Some("24"));
|
||||
// Compressed rows are bottom-up: RLE turns flipped rows off.
|
||||
set(&mut app, "fileFormat", json!("windows"));
|
||||
set(&mut app, "depth", json!(8));
|
||||
set(&mut app, "depth", json!("8"));
|
||||
set(&mut app, "flipRows", json!(true));
|
||||
set(&mut app, "rle", json!(true));
|
||||
frame(&mut app);
|
||||
assert!(!app.ui.dialog.as_ref().unwrap().bool("flipRows"));
|
||||
assert_eq!(fields(&app).bool("flipRows"), Some(false));
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, bmp) = written.borrow()[0].clone();
|
||||
assert_eq!(path, "/out/Untitled-1.bmp");
|
||||
assert_eq!((&bmp[..2], bmp[28], bmp[30]), (&b"BM"[..], 8, 1), "8-bit RLE8");
|
||||
}
|
||||
|
||||
/// Targa at 24 bits is flattened on white; its other depths keep transparency.
|
||||
#[test]
|
||||
fn targa_options_pick_the_depth() {
|
||||
let (mut app, written) = app(1);
|
||||
app.run("file.exportAs", json!({"format": "tga"})).unwrap();
|
||||
confirm(&mut app).unwrap();
|
||||
assert_eq!(kind(&app), Some("tgaOptions"));
|
||||
let d = app.ui.dialog.as_ref().unwrap();
|
||||
assert_eq!(((spec(&d.kind).heading)(d), d.f64("depth", 0.0)), ("Targa Options".into(), 24.0));
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("tga", d), "24 bits are flattened on white");
|
||||
frame(&mut app);
|
||||
set(&mut app, "depth", json!(32));
|
||||
frame(&mut app);
|
||||
assert!(tiff_bmp_tga::keeps_alpha("tga", app.ui.dialog.as_ref().unwrap()));
|
||||
confirm(&mut app).unwrap();
|
||||
let (path, tga) = written.borrow()[0].clone();
|
||||
assert_eq!((path.as_str(), tga[16], tga[17]), ("/out/Untitled-1.tga", 32, 8));
|
||||
fn targa_keeps_transparency_above_24_bits() {
|
||||
assert!(!tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "24")])));
|
||||
assert!(tiff_bmp_tga::keeps_alpha("tga", &DialogFields::from_pairs([("depth", "32")])));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! palette, RLE, row order) and Targa (depth), after the raster export rows they share with PNG
|
||||
//! Options ([`super::png_options`]): the `tiffOptions`, `bmpOptions` and `tgaOptions` dialogs.
|
||||
|
||||
use craft_ui::patterns::form_dialogs::{DialogFields, Param};
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_render::encode::bmp::{self, BmpOptions};
|
||||
use vectorcraft_render::encode::jpeg::ColorModel;
|
||||
@@ -9,10 +10,7 @@ use vectorcraft_render::encode::quantize::{Dither, PaletteOptions, Reduction};
|
||||
use vectorcraft_render::encode::tga::{self, TgaOptions};
|
||||
use vectorcraft_render::encode::tiff::{ByteOrder, TiffOptions};
|
||||
|
||||
use super::form;
|
||||
use super::png_options::choice;
|
||||
use crate::state::Dialog;
|
||||
use crate::widgets;
|
||||
use super::png_options::{check, choice};
|
||||
|
||||
/// BMP colour models and layouts: param values and labels.
|
||||
const BMP_MODELS: [&str; 2] = ["rgb", "gray"];
|
||||
@@ -23,8 +21,6 @@ const LAYOUT_LABELS: [&str; 2] = ["Windows", "OS/2"];
|
||||
const BMP_DEPTH_LABELS: [&str; 6] = ["1 bit", "4 bit", "8 bit", "16 bit", "24 bit", "32 bit"];
|
||||
const TGA_DEPTH_LABELS: [&str; 3] = ["16 bits/pixel", "24 bits/pixel", "32 bits/pixel"];
|
||||
|
||||
type Label<'a> = &'a dyn Fn(&mut egui::Ui, &str) -> egui::Response;
|
||||
|
||||
/// The options format `id` starts with (`cmyk`: a CMYK document exports CMYK TIFFs).
|
||||
pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map<String, Value>) {
|
||||
match id {
|
||||
@@ -43,7 +39,7 @@ pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map<String, Value>) {
|
||||
o.extend([
|
||||
("colorModel".into(), json!(BMP_MODELS[usize::from(b.gray)])),
|
||||
("fileFormat".into(), json!(LAYOUTS[usize::from(b.os2)])),
|
||||
("depth".into(), json!(b.depth)),
|
||||
("depth".into(), json!(b.depth.to_string())),
|
||||
("rle".into(), json!(b.rle)),
|
||||
("flipRows".into(), json!(b.top_down)),
|
||||
("reduction".into(), json!(p.reduction.id())),
|
||||
@@ -51,115 +47,81 @@ pub(super) fn defaults(id: &str, cmyk: bool, o: &mut Map<String, Value>) {
|
||||
]);
|
||||
}
|
||||
"tga" => {
|
||||
o.insert("depth".into(), json!(TgaOptions::default().depth));
|
||||
o.insert("depth".into(), json!(TgaOptions::default().depth.to_string()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The bits per pixel the dialog holds: an option id (text) or a number.
|
||||
fn depth(f: &DialogFields) -> f64 {
|
||||
f.number("depth").or_else(|| f.text("depth").and_then(|t| t.parse().ok())).unwrap_or(24.0)
|
||||
}
|
||||
|
||||
/// Does format `id` keep transparency with the dialog's options (else it is flattened on white)?
|
||||
pub(super) fn keeps_alpha(id: &str, d: &Dialog) -> bool {
|
||||
pub(super) fn keeps_alpha(id: &str, f: &DialogFields) -> bool {
|
||||
match id {
|
||||
"jpg" => false,
|
||||
"tiff" => ColorModel::from_id(&d.str("colorModel")).unwrap_or_default() == ColorModel::Rgb,
|
||||
"bmp" => d.f64("depth", 24.0) == 32.0,
|
||||
"tga" => d.f64("depth", 24.0) != 24.0,
|
||||
"tiff" => ColorModel::from_id(f.text("colorModel").unwrap_or_default()).unwrap_or_default() == ColorModel::Rgb,
|
||||
"bmp" => depth(f) == 32.0,
|
||||
"tga" => depth(f) != 24.0,
|
||||
// A flat PSD is flattened; its layers keep transparency.
|
||||
"psd" => d.bool("layers"),
|
||||
"psd" => f.text("layers") == Some("true"),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The grid rows of format `id`'s own options.
|
||||
pub(super) fn rows(ui: &mut egui::Ui, d: &mut Dialog, id: &str, label: Label) {
|
||||
/// The rows of format `id`'s own options; BMP's depend on `fields`.
|
||||
pub(super) fn params(id: &str, fields: &DialogFields) -> Vec<Param> {
|
||||
match id {
|
||||
"tiff" => tiff_rows(ui, d, label),
|
||||
"bmp" => bmp_rows(ui, d, label),
|
||||
"tga" => {
|
||||
label(ui, tl!("Depth:"));
|
||||
depth_row(ui, d, "tga-depth", &tga::DEPTHS, &TGA_DEPTH_LABELS, |_| true);
|
||||
ui.end_row();
|
||||
}
|
||||
_ => {}
|
||||
"tiff" => vec![
|
||||
choice("colorModel", tl!("Color Model:"), &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label)),
|
||||
choice("byteOrder", tl!("Byte Order:"), &ByteOrder::ALL.map(ByteOrder::id), &ByteOrder::ALL.map(ByteOrder::label)),
|
||||
check("lzw", tl!("LZW Compression"), true),
|
||||
check("embedIcc", tl!("Embed ICC Profile"), true),
|
||||
],
|
||||
"bmp" => bmp_params(fields),
|
||||
"tga" => vec![choice("depth", tl!("Depth:"), &tga::DEPTHS.map(|d| d.to_string()), &TGA_DEPTH_LABELS)],
|
||||
_ => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn tiff_rows(ui: &mut egui::Ui, d: &mut Dialog, label: Label) {
|
||||
label(ui, tl!("Color Model:"));
|
||||
choice(ui, d, "colorModel", &ColorModel::ALL.map(ColorModel::id), &ColorModel::ALL.map(ColorModel::label));
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("Byte Order:"));
|
||||
choice(ui, d, "byteOrder", &ByteOrder::ALL.map(ByteOrder::id), &ByteOrder::ALL.map(ByteOrder::label));
|
||||
ui.end_row();
|
||||
|
||||
ui.label("");
|
||||
ui.horizontal(|ui| {
|
||||
form::check(ui, d, "lzw", tl!("LZW Compression"));
|
||||
form::check(ui, d, "embedIcc", tl!("Embed ICC Profile"));
|
||||
});
|
||||
ui.end_row();
|
||||
}
|
||||
|
||||
fn bmp_rows(ui: &mut egui::Ui, d: &mut Dialog, label: Label) {
|
||||
label(ui, tl!("Color Model:"));
|
||||
choice(ui, d, "colorModel", &BMP_MODELS, &BMP_MODEL_LABELS);
|
||||
ui.end_row();
|
||||
|
||||
label(ui, tl!("File Format:"));
|
||||
choice(ui, d, "fileFormat", &LAYOUTS, &LAYOUT_LABELS);
|
||||
ui.end_row();
|
||||
|
||||
let os2 = d.str("fileFormat") == LAYOUTS[1];
|
||||
label(ui, tl!("Depth:"));
|
||||
depth_row(ui, d, "bmp-depth", &bmp::DEPTHS, &BMP_DEPTH_LABELS, |depth| !os2 || bmp::OS2_DEPTHS.contains(&depth));
|
||||
ui.end_row();
|
||||
|
||||
fn bmp_params(fields: &DialogFields) -> Vec<Param> {
|
||||
let os2 = fields.text("fileFormat") == Some(LAYOUTS[1]);
|
||||
let depths = bmp::DEPTHS.map(|d| d.to_string());
|
||||
let mut rows = vec![
|
||||
choice("colorModel", tl!("Color Model:"), &BMP_MODELS, &BMP_MODEL_LABELS),
|
||||
choice("fileFormat", tl!("File Format:"), &LAYOUTS, &LAYOUT_LABELS),
|
||||
choice("depth", tl!("Depth:"), &depths, &BMP_DEPTH_LABELS)
|
||||
.disabled_options(bmp::DEPTHS.iter().filter(|d| os2 && !bmp::OS2_DEPTHS.contains(d)).map(|d| d.to_string())),
|
||||
];
|
||||
// The palette of a colour image at 4 or 8 bits (1 bit is black and white; greys are fixed).
|
||||
let depth = d.f64("depth", 24.0) as u8;
|
||||
if matches!(depth, 4 | 8) && d.str("colorModel") != BMP_MODELS[1] {
|
||||
label(ui, tl!("Color Reduction:"));
|
||||
choice(ui, d, "reduction", &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label));
|
||||
ui.end_row();
|
||||
label(ui, tl!("Dither:"));
|
||||
choice(ui, d, "dither", &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label));
|
||||
ui.end_row();
|
||||
if matches!(depth(fields) as u8, 4 | 8) && fields.text("colorModel") != Some(BMP_MODELS[1]) {
|
||||
rows.push(choice("reduction", tl!("Color Reduction:"), &Reduction::ALL.map(Reduction::id), &Reduction::ALL.map(Reduction::label)));
|
||||
rows.push(choice("dither", tl!("Dither:"), &Dither::ALL.map(Dither::id), &Dither::ALL.map(Dither::label)));
|
||||
}
|
||||
|
||||
ui.label("");
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_enabled_ui(!os2 && matches!(depth, 4 | 8), |ui| form::check(ui, d, "rle", tl!("Compress (RLE)")));
|
||||
ui.add_enabled_ui(!os2 && !d.bool("rle"), |ui| form::check(ui, d, "flipRows", tl!("Flip Row Order")));
|
||||
});
|
||||
ui.end_row();
|
||||
normalize_bmp(d);
|
||||
// OS/2 has neither compression nor flipped rows; RLE needs 4 or 8 bits, and flipped rows need it off.
|
||||
let rle = check("rle", tl!("Compress (RLE)"), false);
|
||||
let flip = check("flipRows", tl!("Flip Row Order"), false);
|
||||
rows.push(if os2 { rle.enabled_when("fileFormat", LAYOUTS[0]) } else { rle.enabled_when_in("depth", ["4", "8"]) });
|
||||
rows.push(if os2 { flip.enabled_when("fileFormat", LAYOUTS[0]) } else { flip.enabled_when("rle", false) });
|
||||
rows
|
||||
}
|
||||
|
||||
/// Keep the BMP options writable together: OS/2 has no 16 or 32 bits, compression or flipped
|
||||
/// rows; only 4- and 8-bit images are compressed, and those store their rows bottom-up.
|
||||
fn normalize_bmp(d: &mut Dialog) {
|
||||
let os2 = d.str("fileFormat") == LAYOUTS[1];
|
||||
let mut depth = d.f64("depth", 24.0) as u8;
|
||||
if os2 && !bmp::OS2_DEPTHS.contains(&depth) {
|
||||
depth = 24;
|
||||
d.fields.insert("depth".into(), json!(depth));
|
||||
pub(super) fn normalize_bmp(f: &mut DialogFields) {
|
||||
let os2 = f.text("fileFormat") == Some(LAYOUTS[1]);
|
||||
let mut bits = depth(f) as u8;
|
||||
if os2 && !bmp::OS2_DEPTHS.contains(&bits) {
|
||||
bits = 24;
|
||||
f.set("depth", bits.to_string());
|
||||
}
|
||||
let rle = d.bool("rle") && !os2 && matches!(depth, 4 | 8);
|
||||
for (key, on) in [("rle", rle), ("flipRows", d.bool("flipRows") && !os2 && !rle)] {
|
||||
if d.bool(key) != on {
|
||||
d.fields.insert(key.into(), json!(on));
|
||||
let rle = f.bool("rle").unwrap_or(false) && !os2 && matches!(bits, 4 | 8);
|
||||
let flip = f.bool("flipRows").unwrap_or(false) && !os2 && !rle;
|
||||
for (key, on) in [("rle", rle), ("flipRows", flip)] {
|
||||
if f.bool(key).unwrap_or(false) != on {
|
||||
f.set(key, on);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bits-per-pixel dropdown bound to `d.fields["depth"]` (`depths` shown as `labels`); `enabled`
|
||||
/// greys out depths.
|
||||
fn depth_row(ui: &mut egui::Ui, d: &mut Dialog, id: &str, depths: &[u8], labels: &[&str], enabled: impl Fn(u8) -> bool) {
|
||||
let cur = d.f64("depth", 24.0);
|
||||
let shown = depths.iter().position(|b| f64::from(*b) == cur).and_then(|i| labels.get(i)).copied().unwrap_or_default();
|
||||
if let Some(depth) =
|
||||
widgets::dropdown_with(ui, id, shown, labels, 150.0, |i| depths.get(i).is_some_and(|b| enabled(*b))).and_then(|i| depths.get(i))
|
||||
{
|
||||
d.fields.insert("depth".into(), json!(depth));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user