1#![forbid(unsafe_code)]
9#![warn(missing_docs)]
10
11mod png;
12mod potpack;
13mod sdf;
14
15use std::collections::BTreeMap;
16use std::fmt::Write as _;
17
18#[derive(Debug, thiserror::Error)]
20pub enum Error {
21 #[error("invalid SVG for icon `{id}`: {reason}")]
23 InvalidSvg {
24 id: String,
26 reason: String,
28 },
29 #[error("duplicate icon id `{0}`")]
31 DuplicateId(String),
32 #[error("no icons given")]
34 Empty,
35 #[error("icon `{id}` has zero size")]
37 ZeroSize {
38 id: String,
40 },
41}
42
43pub struct RenderedIcon {
45 pub id: String,
47 pub width: u32,
49 pub height: u32,
51 pub pixels: Vec<u8>,
55 pub sdf: bool,
57}
58
59#[derive(Clone, Copy, Default, Debug)]
61pub struct RenderOptions {
62 pub sdf: bool,
69}
70
71pub fn render_icon(id: &str, svg: &str, pixel_ratio: u8) -> Result<RenderedIcon, Error> {
76 render_icon_with_options(id, svg, pixel_ratio, RenderOptions::default())
77}
78
79pub fn render_icon_with_options(
84 id: &str,
85 svg: &str,
86 pixel_ratio: u8,
87 render_options: RenderOptions,
88) -> Result<RenderedIcon, Error> {
89 let options = resvg::usvg::Options::default();
90 let tree = resvg::usvg::Tree::from_str(svg, &options).map_err(|error| Error::InvalidSvg {
91 id: id.to_owned(),
92 reason: error.to_string(),
93 })?;
94 let size = tree.size();
95 let ratio = f32::from(pixel_ratio);
96 let width = (size.width() * ratio).ceil() as u32;
97 let height = (size.height() * ratio).ceil() as u32;
98 if width == 0 || height == 0 {
99 return Err(Error::ZeroSize { id: id.to_owned() });
100 }
101
102 let mut pixmap = resvg::tiny_skia::Pixmap::new(width, height)
103 .ok_or_else(|| Error::ZeroSize { id: id.to_owned() })?;
104 resvg::render(
105 &tree,
106 resvg::tiny_skia::Transform::from_scale(ratio, ratio),
107 &mut pixmap.as_mut(),
108 );
109
110 let mut pixels = Vec::with_capacity(pixmap.data().len());
112 for pixel in pixmap.pixels() {
113 let straight = pixel.demultiply();
114 pixels.extend_from_slice(&[
115 straight.red(),
116 straight.green(),
117 straight.blue(),
118 straight.alpha(),
119 ]);
120 }
121
122 if render_options.sdf {
123 let (width, height, pixels) = sdf::alpha_to_sdf(width, height, &pixels, pixel_ratio);
124 return Ok(RenderedIcon {
125 id: id.to_owned(),
126 width,
127 height,
128 pixels,
129 sdf: true,
130 });
131 }
132
133 Ok(RenderedIcon {
134 id: id.to_owned(),
135 width,
136 height,
137 pixels,
138 sdf: false,
139 })
140}
141
142#[derive(Clone, Copy, PartialEq, Eq, Debug)]
144pub struct SpriteIndexEntry {
145 pub x: u32,
147 pub y: u32,
149 pub width: u32,
151 pub height: u32,
153 pub pixel_ratio: u8,
155 pub sdf: bool,
157}
158
159pub struct SpriteSheet {
161 pub png: Vec<u8>,
163 pub index: BTreeMap<String, SpriteIndexEntry>,
165}
166
167#[derive(Clone, Copy, Default)]
169pub struct BuildOptions {
170 pub fast: bool,
172}
173
174struct Deduplicated<'a> {
175 representatives: Vec<&'a RenderedIcon>,
176 representative_for_icon: Vec<usize>,
177}
178
179fn deduplicate<'a>(icons: &[&'a RenderedIcon]) -> Deduplicated<'a> {
180 let mut representatives: Vec<&RenderedIcon> = Vec::new();
181 let mut representative_for_icon = Vec::with_capacity(icons.len());
182
183 for icon in icons {
184 let representative = representatives.iter().position(|candidate| {
185 candidate.width == icon.width
186 && candidate.height == icon.height
187 && candidate.sdf == icon.sdf
188 && candidate.pixels == icon.pixels
189 });
190 let representative = representative.unwrap_or_else(|| {
191 representatives.push(icon);
192 representatives.len() - 1
193 });
194 representative_for_icon.push(representative);
195 }
196
197 Deduplicated {
198 representatives,
199 representative_for_icon,
200 }
201}
202
203pub fn build_sprite_sheet(
208 icons: &[RenderedIcon],
209 pixel_ratio: u8,
210 options: BuildOptions,
211) -> Result<SpriteSheet, Error> {
212 if icons.is_empty() {
213 return Err(Error::Empty);
214 }
215
216 let mut ordered: Vec<&RenderedIcon> = icons.iter().collect();
217 ordered.sort_by(|left, right| left.id.cmp(&right.id));
218 for pair in ordered.windows(2) {
219 if pair[0].id == pair[1].id {
220 return Err(Error::DuplicateId(pair[0].id.clone()));
221 }
222 }
223 for icon in &ordered {
224 if icon.width == 0 || icon.height == 0 {
225 return Err(Error::ZeroSize {
226 id: icon.id.clone(),
227 });
228 }
229 }
230
231 let deduplicated = deduplicate(&ordered);
232 let rectangles = deduplicated
233 .representatives
234 .iter()
235 .enumerate()
236 .map(|(index, icon)| potpack::Rectangle {
237 index,
238 id: &icon.id,
239 width: u64::from(icon.width) + 2,
240 height: u64::from(icon.height) + 2,
241 })
242 .collect();
243 let layout = potpack::pack(rectangles);
244 let mut rgba = vec![0; layout.width as usize * layout.height as usize * 4];
245
246 for (representative, &(packed_x, packed_y)) in
247 deduplicated.representatives.iter().zip(&layout.positions)
248 {
249 let x = packed_x + 1;
250 let y = packed_y + 1;
251 for row in 0..representative.height {
252 let source_start = (row * representative.width * 4) as usize;
253 let source_end = source_start + (representative.width * 4) as usize;
254 let destination_start = (((y + row) * layout.width + x) * 4) as usize;
255 let destination_end = destination_start + (representative.width * 4) as usize;
256 rgba[destination_start..destination_end]
257 .copy_from_slice(&representative.pixels[source_start..source_end]);
258 }
259 }
260
261 let mut index = BTreeMap::new();
262 for (icon, &representative) in ordered.iter().zip(&deduplicated.representative_for_icon) {
263 let (packed_x, packed_y) = layout.positions[representative];
264 index.insert(
265 icon.id.clone(),
266 SpriteIndexEntry {
267 x: packed_x + 1,
268 y: packed_y + 1,
269 width: icon.width,
270 height: icon.height,
271 pixel_ratio,
272 sdf: icon.sdf,
273 },
274 );
275 }
276
277 let png = png::encode(layout.width, layout.height, &rgba, options.fast);
278 Ok(SpriteSheet { png, index })
279}
280
281pub fn index_to_json(index: &BTreeMap<String, SpriteIndexEntry>) -> String {
287 if index.is_empty() {
288 return "{}\n".to_owned();
289 }
290
291 let mut json = String::from("{\n");
292 for (entry_number, (id, entry)) in index.iter().enumerate() {
293 json.push_str(" ");
294 push_json_string(&mut json, id);
295 json.push_str(": {\n");
296 writeln!(json, " \"x\": {},", entry.x).expect("writing to a String cannot fail");
297 writeln!(json, " \"y\": {},", entry.y).expect("writing to a String cannot fail");
298 writeln!(json, " \"width\": {},", entry.width).expect("writing to a String cannot fail");
299 writeln!(json, " \"height\": {},", entry.height)
300 .expect("writing to a String cannot fail");
301 if entry.sdf {
302 writeln!(json, " \"pixelRatio\": {},", entry.pixel_ratio)
303 .expect("writing to a String cannot fail");
304 json.push_str(" \"sdf\": true\n");
305 } else {
306 writeln!(json, " \"pixelRatio\": {}", entry.pixel_ratio)
307 .expect("writing to a String cannot fail");
308 }
309 json.push_str(" }");
310 if entry_number + 1 != index.len() {
311 json.push(',');
312 }
313 json.push('\n');
314 }
315 json.push_str("}\n");
316 json
317}
318
319fn push_json_string(output: &mut String, value: &str) {
320 output.push('"');
321 for character in value.chars() {
322 match character {
323 '"' => output.push_str("\\\""),
324 '\\' => output.push_str("\\\\"),
325 '\u{08}' => output.push_str("\\b"),
326 '\u{0c}' => output.push_str("\\f"),
327 '\n' => output.push_str("\\n"),
328 '\r' => output.push_str("\\r"),
329 '\t' => output.push_str("\\t"),
330 '\u{00}'..='\u{1f}' => {
331 write!(output, "\\u{:04x}", character as u32)
332 .expect("writing to a String cannot fail");
333 }
334 _ => output.push(character),
335 }
336 }
337 output.push('"');
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 fn icon(id: &str, width: u32, height: u32, pixels: Vec<u8>) -> RenderedIcon {
345 RenderedIcon {
346 id: id.to_owned(),
347 width,
348 height,
349 pixels,
350 sdf: false,
351 }
352 }
353
354 #[test]
355 fn deduplicates_identical_pixels_using_the_first_id() {
356 let icons = vec![
357 icon("z-copy", 1, 1, vec![10, 20, 30, 255]),
358 icon("a-original", 1, 1, vec![10, 20, 30, 255]),
359 ];
360 let mut ordered: Vec<_> = icons.iter().collect();
361 ordered.sort_by(|left, right| left.id.cmp(&right.id));
362 let deduplicated = deduplicate(&ordered);
363 assert!(std::ptr::eq(deduplicated.representatives[0], ordered[0]));
364
365 let sheet = build_sprite_sheet(&icons, 1, BuildOptions { fast: true }).unwrap();
366 assert_eq!(sheet.index["a-original"], sheet.index["z-copy"]);
367 assert_eq!(u32::from_be_bytes(sheet.png[16..20].try_into().unwrap()), 3);
368 assert_eq!(u32::from_be_bytes(sheet.png[20..24].try_into().unwrap()), 3);
369 }
370
371 #[test]
372 fn does_not_merge_sdf_and_plain_icons_with_identical_pixels() {
373 let mut sdf_icon = icon("b-sdf", 1, 1, vec![0, 0, 0, 255]);
374 sdf_icon.sdf = true;
375 let icons = vec![icon("a-plain", 1, 1, vec![0, 0, 0, 255]), sdf_icon];
376 let sheet = build_sprite_sheet(&icons, 1, BuildOptions { fast: true }).unwrap();
377 assert_ne!(
378 (sheet.index["a-plain"].x, sheet.index["a-plain"].y),
379 (sheet.index["b-sdf"].x, sheet.index["b-sdf"].y)
380 );
381 assert!(!sheet.index["a-plain"].sdf);
382 assert!(sheet.index["b-sdf"].sdf);
383 }
384
385 #[test]
386 fn renders_sdf_icons_with_padding() {
387 let svg = r#"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="10" height="10"/></svg>"#;
388 let plain = render_icon("square", svg, 2).unwrap();
389 let sdf = render_icon_with_options("square", svg, 2, RenderOptions { sdf: true }).unwrap();
390 assert!(!plain.sdf);
391 assert!(sdf.sdf);
392 assert_eq!((plain.width, plain.height), (20, 20));
393 assert_eq!((sdf.width, sdf.height), (32, 32));
394 }
395
396 #[test]
397 fn reports_required_error_cases() {
398 assert!(matches!(
399 build_sprite_sheet(&[], 1, BuildOptions::default()),
400 Err(Error::Empty)
401 ));
402
403 let duplicate = vec![
404 icon("same", 1, 1, vec![0; 4]),
405 icon("same", 1, 1, vec![255; 4]),
406 ];
407 assert!(matches!(
408 build_sprite_sheet(&duplicate, 1, BuildOptions::default()),
409 Err(Error::DuplicateId(id)) if id == "same"
410 ));
411
412 let zero = vec![icon("zero", 0, 1, Vec::new())];
413 assert!(matches!(
414 build_sprite_sheet(&zero, 1, BuildOptions::default()),
415 Err(Error::ZeroSize { id }) if id == "zero"
416 ));
417
418 assert!(matches!(
419 render_icon("bad", "not svg", 1),
420 Err(Error::InvalidSvg { id, .. }) if id == "bad"
421 ));
422 assert!(matches!(
423 render_icon(
424 "zero-ratio",
425 r#"<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1"/>"#,
426 0,
427 ),
428 Err(Error::ZeroSize { id }) if id == "zero-ratio"
429 ));
430 }
431
432 #[test]
433 fn index_json_format_and_escaping_are_fixed() {
434 let index = BTreeMap::from([
435 (
436 "a\n\"".to_owned(),
437 SpriteIndexEntry {
438 x: 1,
439 y: 2,
440 width: 3,
441 height: 4,
442 pixel_ratio: 2,
443 sdf: false,
444 },
445 ),
446 (
447 "b".to_owned(),
448 SpriteIndexEntry {
449 x: 5,
450 y: 6,
451 width: 7,
452 height: 8,
453 pixel_ratio: 2,
454 sdf: true,
455 },
456 ),
457 ]);
458 assert_eq!(
459 index_to_json(&index),
460 concat!(
461 "{\n",
462 " \"a\\n\\\"\": {\n",
463 " \"x\": 1,\n",
464 " \"y\": 2,\n",
465 " \"width\": 3,\n",
466 " \"height\": 4,\n",
467 " \"pixelRatio\": 2\n",
468 " },\n",
469 " \"b\": {\n",
470 " \"x\": 5,\n",
471 " \"y\": 6,\n",
472 " \"width\": 7,\n",
473 " \"height\": 8,\n",
474 " \"pixelRatio\": 2,\n",
475 " \"sdf\": true\n",
476 " }\n",
477 "}\n",
478 ),
479 );
480 assert_eq!(index_to_json(&BTreeMap::new()), "{}\n");
481 }
482}