1use std::path::{Path, PathBuf};
2
3use globset::GlobSet;
4
5use crate::config::{
6 project_relative, AspectRatio, Config, FitMode, FormatKind, PresetConfig, PresetOverrideConfig,
7};
8use crate::hash::hash_bytes;
9use crate::pipeline::{path_to_string, Operation, Plan, SourceImage};
10use crate::quality::{
11 allowed_upscale_warning, append_unique, cover_crop_warning, lossy_quality_warnings,
12 skipped_upscale_warning,
13};
14use crate::scan::compile_globs;
15use crate::warnings::{warning_message, PLAN_METADATA_NOT_PRESERVED, PLAN_NO_VARIANTS};
16use crate::{DevimgError, Result};
17
18pub fn build_plan(config: &Config, sources: &[SourceImage]) -> Result<Plan> {
19 let mut operations = Vec::new();
20 let mut warnings = Vec::new();
21 let overrides = compile_overrides(config)?;
22 if !config.project.strip_metadata {
23 warnings.push(warning_message(
24 PLAN_METADATA_NOT_PRESERVED,
25 "strip_metadata=false was requested, but current encoders re-encode images and do not preserve source metadata",
26 ));
27 }
28
29 for source in sources {
30 let mut planned_for_source = 0usize;
31 for preset in &config.presets {
32 let effective_preset = apply_overrides(source, preset, &overrides);
33 for width in &effective_preset.widths {
34 let (target_width, target_height) =
35 target_dimensions(source.width, source.height, *width, &effective_preset);
36 if !effective_preset.allow_upscale
37 && (target_width > source.width || target_height > source.height)
38 {
39 append_unique(
40 &mut warnings,
41 [skipped_upscale_warning(
42 source,
43 &effective_preset,
44 *width,
45 target_width,
46 target_height,
47 )],
48 );
49 continue;
50 }
51 append_unique(
52 &mut warnings,
53 lossy_quality_warnings(source, &effective_preset),
54 );
55 append_unique(
56 &mut warnings,
57 allowed_upscale_warning(
58 source,
59 &effective_preset,
60 *width,
61 target_width,
62 target_height,
63 ),
64 );
65 append_unique(
66 &mut warnings,
67 cover_crop_warning(
68 source,
69 &effective_preset,
70 *width,
71 target_width,
72 target_height,
73 ),
74 );
75 for format in &effective_preset.formats {
76 let output_path = output_path_for(source, &effective_preset, *width, *format)?;
77 if output_path == source.path {
78 return Err(DevimgError::UnsafeOverwrite { path: output_path });
79 }
80 let output_project_path =
81 path_to_string(&project_relative(config, &output_path));
82 let op_hash = operation_hash(
83 source,
84 &effective_preset,
85 *format,
86 target_width,
87 target_height,
88 &output_project_path,
89 OperationHashOptions {
90 strip_metadata: config.project.strip_metadata,
91 content_hash_filenames: config.project.content_hash_filenames,
92 },
93 );
94 operations.push(Operation {
95 source: source.clone(),
96 preset: effective_preset.name.clone(),
97 fit: effective_preset.fit,
98 crop: effective_preset.crop,
99 quality: effective_preset.quality,
100 format: *format,
101 width: target_width,
102 height: target_height,
103 strip_metadata: config.project.strip_metadata,
104 content_hash_filenames: config.project.content_hash_filenames,
105 output_path,
106 output_project_path,
107 operation_hash: op_hash,
108 });
109 planned_for_source += 1;
110 }
111 }
112 }
113 if planned_for_source == 0 {
114 warnings.push(warning_message(
115 PLAN_NO_VARIANTS,
116 format!(
117 "no variants planned for {} after applying presets",
118 source.project_path
119 ),
120 ));
121 }
122 }
123
124 operations.sort_by(|left, right| left.output_project_path.cmp(&right.output_project_path));
125 Ok(Plan {
126 operations,
127 warnings,
128 })
129}
130
131fn output_path_for(
132 source: &SourceImage,
133 preset: &PresetConfig,
134 width: u32,
135 format: FormatKind,
136) -> Result<PathBuf> {
137 let stem = source
138 .relative_path
139 .file_stem()
140 .ok_or_else(|| DevimgError::image(&source.path, "could not derive file stem"))?
141 .to_string_lossy();
142 let parent = source
143 .relative_path
144 .parent()
145 .unwrap_or_else(|| Path::new(""));
146 let file_name = format!("{stem}.{}.{}.{}", preset.name, width, format.extension());
147 Ok(source.output_root.join(parent).join(file_name))
148}
149
150fn target_dimensions(
151 source_width: u32,
152 source_height: u32,
153 requested_width: u32,
154 preset: &PresetConfig,
155) -> (u32, u32) {
156 let box_width = requested_width.max(1);
157 let box_height = match preset.aspect_ratio {
158 Some(AspectRatio { width, height }) => {
159 ((u64::from(box_width) * u64::from(height) + u64::from(width / 2)) / u64::from(width))
160 .max(1) as u32
161 }
162 None => ((u64::from(box_width) * u64::from(source_height) + u64::from(source_width / 2))
163 / u64::from(source_width))
164 .max(1) as u32,
165 };
166
167 if preset.fit != FitMode::Contain {
168 return (box_width, box_height);
169 }
170
171 if u64::from(source_width) * u64::from(box_height)
172 >= u64::from(source_height) * u64::from(box_width)
173 {
174 let height = ((u64::from(box_width) * u64::from(source_height)
175 + u64::from(source_width / 2))
176 / u64::from(source_width))
177 .max(1) as u32;
178 (box_width, height)
179 } else {
180 let width = ((u64::from(box_height) * u64::from(source_width)
181 + u64::from(source_height / 2))
182 / u64::from(source_height))
183 .max(1) as u32;
184 (width, box_height)
185 }
186}
187
188fn operation_hash(
189 source: &SourceImage,
190 preset: &PresetConfig,
191 format: FormatKind,
192 width: u32,
193 height: u32,
194 output_path: &str,
195 options: OperationHashOptions,
196) -> String {
197 let mut input = format!(
198 "operation-hash-v2|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
199 source.hash,
200 source.project_path,
201 output_path,
202 preset.name,
203 preset.fit.label(),
204 preset.crop.label(),
205 preset.quality,
206 width,
207 height,
208 format.label(),
209 options.strip_metadata,
210 );
211 if let Some(component) = encoder_hash_component(format) {
212 input.push('|');
213 input.push_str(component);
214 }
215 if options.content_hash_filenames {
216 input.push_str("|filename:content-hash-v1");
217 }
218 hash_bytes(input.as_bytes())
219}
220
221#[derive(Debug, Clone, Copy)]
222struct OperationHashOptions {
223 strip_metadata: bool,
224 content_hash_filenames: bool,
225}
226
227pub(crate) fn legacy_operation_hash(operation: &Operation, config_hash: &str) -> String {
228 let mut input = format!(
229 "{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}|{}",
230 config_hash,
231 operation.source.hash,
232 operation.source.project_path,
233 operation.output_project_path,
234 operation.preset,
235 operation.fit.label(),
236 operation.crop.label(),
237 operation.quality,
238 operation.width,
239 operation.height,
240 operation.format.label(),
241 operation.strip_metadata,
242 );
243 if let Some(component) = encoder_hash_component(operation.format) {
244 input.push('|');
245 input.push_str(component);
246 }
247 if operation.content_hash_filenames {
248 input.push_str("|filename:content-hash-v1");
249 }
250 hash_bytes(input.as_bytes())
251}
252
253fn encoder_hash_component(format: FormatKind) -> Option<&'static str> {
254 match format {
255 FormatKind::Webp => Some("encoder:webp-libwebp-lossy-v1"),
256 FormatKind::Avif => Some("encoder:ravif-0.13-speed8-v1"),
257 FormatKind::Png | FormatKind::Jpeg => None,
258 }
259}
260
261struct CompiledPresetOverride<'a> {
262 config: &'a PresetOverrideConfig,
263 includes: GlobSet,
264 excludes: GlobSet,
265}
266
267fn compile_overrides(config: &Config) -> Result<Vec<CompiledPresetOverride<'_>>> {
268 config
269 .overrides
270 .iter()
271 .map(|preset_override| {
272 Ok(CompiledPresetOverride {
273 config: preset_override,
274 includes: compile_globs(
275 &config.path,
276 "override include",
277 &preset_override.include,
278 )?,
279 excludes: compile_globs(
280 &config.path,
281 "override exclude",
282 &preset_override.exclude,
283 )?,
284 })
285 })
286 .collect()
287}
288
289fn apply_overrides(
290 source: &SourceImage,
291 preset: &PresetConfig,
292 overrides: &[CompiledPresetOverride<'_>],
293) -> PresetConfig {
294 let mut effective = preset.clone();
295 let relative_path = path_to_string(&source.relative_path);
296 for preset_override in overrides {
297 if !override_matches(preset_override, &relative_path, &preset.name) {
298 continue;
299 }
300 if let Some(quality) = preset_override.config.quality {
301 effective.quality = quality;
302 }
303 if let Some(fit) = preset_override.config.fit {
304 effective.fit = fit;
305 }
306 if let Some(crop) = preset_override.config.crop {
307 effective.crop = crop;
308 }
309 if let Some(allow_upscale) = preset_override.config.allow_upscale {
310 effective.allow_upscale = allow_upscale;
311 }
312 }
313 effective
314}
315
316fn override_matches(
317 preset_override: &CompiledPresetOverride<'_>,
318 relative_path: &str,
319 preset_name: &str,
320) -> bool {
321 if !preset_override.config.presets.is_empty()
322 && !preset_override
323 .config
324 .presets
325 .iter()
326 .any(|candidate| candidate == preset_name)
327 {
328 return false;
329 }
330 if !preset_override.config.include.is_empty()
331 && !preset_override.includes.is_match(relative_path)
332 {
333 return false;
334 }
335 !preset_override.excludes.is_match(relative_path)
336}
337
338pub(crate) fn cover_dimensions(
339 source_width: u32,
340 source_height: u32,
341 target_width: u32,
342 target_height: u32,
343) -> (u32, u32) {
344 let sw = u128::from(source_width);
345 let sh = u128::from(source_height);
346 let tw = u128::from(target_width);
347 let th = u128::from(target_height);
348
349 if sw * th >= sh * tw {
350 let resize_width = (sw * th).div_ceil(sh) as u32;
351 (resize_width, target_height)
352 } else {
353 let resize_height = (sh * tw).div_ceil(sw) as u32;
354 (target_width, resize_height)
355 }
356}