1use std::path::PathBuf;
34
35use proc_macro::TokenStream;
36use proc_macro2::TokenStream as TokenStream2;
37use quote::quote;
38use syn::parse::{Parse, ParseStream};
39use syn::{Ident, Result, Token, Visibility, parse_macro_input};
40
41enum ResInput {
46 Expr(syn::LitStr),
48 Static {
50 vis: Visibility,
51 name: Ident,
52 path: syn::LitStr,
53 },
54}
55
56impl Parse for ResInput {
57 fn parse(input: ParseStream) -> Result<Self> {
58 if input.peek(Token![pub]) || (input.peek(Ident) && input.peek2(Token![=])) {
60 let vis: Visibility = input.parse()?;
61 let name: Ident = input.parse()?;
62 let _eq: Token![=] = input.parse()?;
63 let path: syn::LitStr = input.parse()?;
64 Ok(ResInput::Static { vis, name, path })
65 } else {
66 let path: syn::LitStr = input.parse()?;
67 Ok(ResInput::Expr(path))
68 }
69 }
70}
71
72#[derive(Clone, Copy)]
77enum ResourceKind {
78 Svg,
79 Png,
80 Webp,
81}
82
83fn detect_kind(path: &str) -> Option<ResourceKind> {
84 if path.ends_with(".svg") {
85 Some(ResourceKind::Svg)
86 } else if path.ends_with(".png") {
87 Some(ResourceKind::Png)
88 } else if path.ends_with(".webp") {
89 Some(ResourceKind::Webp)
90 } else {
91 None
92 }
93}
94
95fn validate_svg(data: &[u8], path: &str) -> std::result::Result<(), String> {
119 let text = std::str::from_utf8(data).map_err(|e| format!("{path}: not valid UTF-8: {e}"))?;
120 let icon = teksilo_canvas::svg::SvgIcon::parse(text).map_err(|e| format!("{path}: {e}"))?;
121 if icon.is_empty() {
122 return Err(format!(
123 "{path}: parses as SVG but contains no vector geometry, so it would render as a \
124 blank icon. The icon renderer draws paths, not pixels: it skips <image> and <text>. \
125 If this file is an embedded bitmap in an XML wrapper (an <image> with a \
126 `data:image/png;base64,…` href — check with `grep -c '<path' <file>`), embed the \
127 bitmap itself with res!(\"….png\") instead, or export the artwork as real vector paths."
128 ));
129 }
130 Ok(())
131}
132
133fn validate_png(data: &[u8], path: &str) -> std::result::Result<(), String> {
134 const PNG_MAGIC: &[u8; 8] = b"\x89PNG\r\n\x1a\n";
135 if data.len() < 8 {
136 return Err(format!("{path}: file too small for PNG"));
137 }
138 if &data[..8] != PNG_MAGIC {
139 return Err(format!("{path}: invalid PNG magic bytes"));
140 }
141 if data.len() < 16 {
144 return Err(format!("{path}: truncated PNG (no IHDR chunk header)"));
145 }
146 if &data[12..16] != b"IHDR" {
147 return Err(format!("{path}: first PNG chunk is not IHDR"));
148 }
149 let ihdr_len = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);
150 if ihdr_len != 13 {
151 return Err(format!(
152 "{path}: PNG IHDR length is {ihdr_len}, expected 13"
153 ));
154 }
155 Ok(())
156}
157
158fn validate_webp(data: &[u8], path: &str) -> std::result::Result<(), String> {
159 if data.len() < 12 {
160 return Err(format!("{path}: file too small for WebP"));
161 }
162 if &data[..4] != b"RIFF" {
163 return Err(format!("{path}: missing RIFF header"));
164 }
165 if &data[8..12] != b"WEBP" {
166 return Err(format!("{path}: missing WEBP signature"));
167 }
168 Ok(())
169}
170
171fn webp_is_animated(data: &[u8]) -> bool {
173 if data.len() < 12 {
175 return false;
176 }
177 let mut pos = 12;
178 while pos + 8 <= data.len() {
179 let chunk_id = &data[pos..pos + 4];
180 if chunk_id == b"ANIM" {
181 return true;
182 }
183 let chunk_size =
184 u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]])
185 as usize;
186 pos = pos
188 .saturating_add(8)
189 .saturating_add(chunk_size)
190 .saturating_add(chunk_size & 1);
191 }
192 false
193}
194
195fn emit_expr(kind: ResourceKind, rel_path: &str, animated: bool) -> TokenStream2 {
202 let watch = quote! {
203 const _: &[u8] = ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path));
204 };
205 let (ty, init) = lazy_type_and_init(kind, rel_path, animated);
206 quote! {
207 {
208 #watch
209 static __TEKSILO_RES: ::std::sync::LazyLock<#ty> =
210 ::std::sync::LazyLock::new(|| { #init });
211 &*__TEKSILO_RES
212 }
213 }
214}
215
216fn emit_static(
218 vis: &Visibility,
219 name: &Ident,
220 kind: ResourceKind,
221 rel_path: &str,
222 animated: bool,
223) -> TokenStream2 {
224 let watch = quote! {
225 const _: &[u8] = ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path));
226 };
227 let (ty, init) = lazy_type_and_init(kind, rel_path, animated);
228 quote! {
229 #watch
230 #vis static #name: ::std::sync::LazyLock<#ty> =
231 ::std::sync::LazyLock::new(|| { #init });
232 }
233}
234
235fn lazy_type_and_init(
241 kind: ResourceKind,
242 rel_path: &str,
243 animated: bool,
244) -> (TokenStream2, TokenStream2) {
245 match kind {
246 ResourceKind::Svg => (
247 quote!(::teksilo::canvas::svg::SvgIcon),
248 quote! {
249 ::teksilo::canvas::svg::SvgIcon::parse(
250 ::core::include_str!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path))
251 ).expect("teksilo-resources: SVG validated at compile time")
252 },
253 ),
254 ResourceKind::Png => (
255 quote!(::teksilo::canvas::raster::RasterIcon),
256 quote! {
257 ::teksilo::canvas::raster::RasterIcon::decode_png(
258 ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path))
259 ).expect("teksilo-resources: PNG validated at compile time")
260 },
261 ),
262 ResourceKind::Webp if animated => (
263 quote!(::teksilo::canvas::animated::AnimatedIcon),
264 quote! {
265 ::teksilo::canvas::animated::AnimatedIcon::decode_webp(
266 ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path))
267 ).expect("teksilo-resources: animated WebP validated at compile time")
268 },
269 ),
270 ResourceKind::Webp => (
271 quote!(::teksilo::canvas::raster::RasterIcon),
272 quote! {
273 ::teksilo::canvas::raster::RasterIcon::decode_webp(
274 ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path))
275 ).expect("teksilo-resources: WebP validated at compile time")
276 },
277 ),
278 }
279}
280
281fn emit_raw_expr(rel_path: &str) -> TokenStream2 {
283 quote! {
284 ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path))
285 }
286}
287
288fn emit_raw_static(vis: &Visibility, name: &Ident, rel_path: &str) -> TokenStream2 {
290 quote! {
291 #vis static #name: &[u8] =
292 ::core::include_bytes!(::core::concat!(::core::env!("CARGO_MANIFEST_DIR"), "/", #rel_path));
293 }
294}
295
296#[proc_macro]
304pub fn res(input: TokenStream) -> TokenStream {
305 let parsed = parse_macro_input!(input as ResInput);
306
307 let (rel_path_lit, span) = match &parsed {
308 ResInput::Expr(lit) => (lit, lit.span()),
309 ResInput::Static { path, .. } => (path, path.span()),
310 };
311 let rel_path = rel_path_lit.value();
312
313 let manifest = match std::env::var("CARGO_MANIFEST_DIR") {
315 Ok(m) => m,
316 Err(_) => {
317 return syn::Error::new(span, "CARGO_MANIFEST_DIR is not set")
318 .to_compile_error()
319 .into();
320 }
321 };
322 let abs_path = PathBuf::from(&manifest).join(&rel_path);
323
324 let data = match std::fs::read(&abs_path) {
326 Ok(d) => d,
327 Err(e) => {
328 return syn::Error::new(
329 span,
330 format!(
331 "teksilo-resources: cannot read `{}`: {e}",
332 abs_path.display()
333 ),
334 )
335 .to_compile_error()
336 .into();
337 }
338 };
339
340 let kind = detect_kind(&rel_path);
342
343 if let Some(k) = kind {
345 let validation_result = match k {
346 ResourceKind::Svg => validate_svg(&data, &rel_path),
347 ResourceKind::Png => validate_png(&data, &rel_path),
348 ResourceKind::Webp => validate_webp(&data, &rel_path),
349 };
350 if let Err(msg) = validation_result {
351 return syn::Error::new(span, format!("teksilo-resources: {msg}"))
352 .to_compile_error()
353 .into();
354 }
355 }
356
357 let animated = matches!(kind, Some(ResourceKind::Webp)) && webp_is_animated(&data);
359
360 match (parsed, kind) {
362 (ResInput::Expr(_), Some(k)) => emit_expr(k, &rel_path, animated).into(),
363 (ResInput::Static { vis, name, .. }, Some(k)) => {
364 emit_static(&vis, &name, k, &rel_path, animated).into()
365 }
366 (ResInput::Expr(_), None) => emit_raw_expr(&rel_path).into(),
368 (ResInput::Static { vis, name, .. }, None) => {
369 emit_raw_static(&vis, &name, &rel_path).into()
370 }
371 }
372}
373
374#[cfg(test)]
379mod tests {
380 use super::*;
381
382 #[test]
385 fn svg_with_geometry_is_accepted() {
386 let svg = br#"<svg viewBox="0 0 24 24"><path d="M2 2L22 2L22 22Z"/></svg>"#;
387 assert!(validate_svg(svg, "ok.svg").is_ok());
388 let via_use = br##"<svg viewBox="0 0 24 24">
390 <defs><path id="p" d="M2 2L22 2L22 22Z"/></defs>
391 <use href="#p"/>
392 </svg>"##;
393 assert!(validate_svg(via_use, "use.svg").is_ok());
394 }
395
396 #[test]
401 fn an_image_only_svg_is_rejected_as_having_no_geometry() {
402 let svg = br#"<svg width="512" height="512" xmlns="http://www.w3.org/2000/svg">
403 <g><image x="0" y="0" width="512" height="512"
404 xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUg"/></g>
405 </svg>"#;
406 let err = validate_svg(svg, "logo.svg").unwrap_err();
407 assert!(
408 err.contains("no vector geometry") && err.contains("blank icon"),
409 "the error must name the problem, got: {err}"
410 );
411 }
412
413 #[test]
417 fn files_the_parser_would_panic_on_are_rejected_at_compile_time() {
418 assert!(
420 validate_svg(
421 br#"<svg viewBox="0 0 24 24"><path d="M x!"/></svg>"#,
422 "b.svg"
423 )
424 .is_err()
425 );
426 assert!(validate_svg(b"<html><body/></html>", "b.svg").is_err());
428 assert!(validate_svg(br#"<svg><path d="M0 0L1 1Z"/></svg>"#, "b.svg").is_err());
430 assert!(validate_svg(&[0xFF, 0xFE, 0x00], "b.svg").is_err());
432 }
433
434 #[test]
437 fn png_ok() {
438 let mut data = b"\x89PNG\r\n\x1a\n".to_vec(); data.extend_from_slice(&13u32.to_be_bytes()); data.extend_from_slice(b"IHDR"); data.extend_from_slice(&[0u8; 17]); assert!(validate_png(&data, "ok.png").is_ok());
444 }
445
446 #[test]
447 fn png_too_small() {
448 let err = validate_png(b"\x89PNG", "f.png").unwrap_err();
449 assert!(err.contains("file too small"), "{err}");
450 }
451
452 #[test]
453 fn png_bad_magic() {
454 let mut data = [0u8; 16];
455 data[0] = 0xFF; let err = validate_png(&data, "f.png").unwrap_err();
457 assert!(err.contains("invalid PNG magic bytes"), "{err}");
458 }
459
460 #[test]
461 fn png_truncated_before_ihdr() {
462 let err = validate_png(b"\x89PNG\r\n\x1a\n", "f.png").unwrap_err();
464 assert!(err.contains("truncated PNG"), "{err}");
465 }
466
467 #[test]
468 fn png_wrong_first_chunk_type() {
469 let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
470 data.extend_from_slice(&0u32.to_be_bytes()); data.extend_from_slice(b"IDAT"); let err = validate_png(&data, "f.png").unwrap_err();
473 assert!(err.contains("first PNG chunk is not IHDR"), "{err}");
474 }
475
476 #[test]
477 fn png_wrong_ihdr_length() {
478 let mut data = b"\x89PNG\r\n\x1a\n".to_vec();
479 data.extend_from_slice(&5u32.to_be_bytes()); data.extend_from_slice(b"IHDR");
481 let err = validate_png(&data, "f.png").unwrap_err();
482 assert!(err.contains("IHDR length is 5"), "{err}");
483 }
484
485 #[test]
488 fn svg_ok_viewbox() {
489 let xml = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
490 <circle cx="12" cy="12" r="10"/>
491 </svg>"#;
492 assert!(validate_svg(xml, "ok.svg").is_ok());
493 }
494
495 #[test]
496 fn svg_ok_width_height() {
497 let xml = br#"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24">
499 <rect width="24" height="24"/>
500 </svg>"#;
501 assert!(validate_svg(xml, "ok.svg").is_ok());
502 }
503
504 #[test]
508 fn an_empty_svg_is_rejected() {
509 let xml = br#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"></svg>"#;
510 let err = validate_svg(xml, "empty.svg").unwrap_err();
511 assert!(err.contains("no vector geometry"), "{err}");
512 }
513
514 #[test]
515 fn svg_not_utf8() {
516 let bad = b"\xff\xfe not utf-8";
517 let err = validate_svg(bad, "f.svg").unwrap_err();
518 assert!(err.contains("not valid UTF-8"), "{err}");
519 }
520
521 #[test]
522 fn svg_malformed_xml() {
523 let err = validate_svg(b"<not closed", "f.svg").unwrap_err();
524 assert!(err.contains("XML"), "{err}");
525 }
526
527 #[test]
528 fn svg_wrong_root() {
529 let xml = b"<html><body></body></html>";
530 let err = validate_svg(xml, "f.svg").unwrap_err();
531 assert!(err.contains("no <svg> root"), "{err}");
532 }
533
534 #[test]
535 fn svg_missing_viewbox_and_dimensions() {
536 let xml = br#"<svg xmlns="http://www.w3.org/2000/svg"><rect width="8" height="8"/></svg>"#;
537 let err = validate_svg(xml, "f.svg").unwrap_err();
538 assert!(err.contains("viewBox"), "{err}");
539 }
540
541 #[test]
544 fn webp_ok() {
545 let mut data = b"RIFF".to_vec();
546 data.extend_from_slice(&0u32.to_le_bytes()); data.extend_from_slice(b"WEBP");
548 assert!(validate_webp(&data, "ok.webp").is_ok());
549 }
550
551 #[test]
552 fn webp_too_small() {
553 let err = validate_webp(b"RIFF", "f.webp").unwrap_err();
554 assert!(err.contains("file too small"), "{err}");
555 }
556
557 #[test]
558 fn webp_missing_riff() {
559 let data = b"XXXX\x00\x00\x00\x00WEBP";
560 let err = validate_webp(data, "f.webp").unwrap_err();
561 assert!(err.contains("missing RIFF header"), "{err}");
562 }
563
564 #[test]
565 fn webp_missing_webp_signature() {
566 let data = b"RIFF\x00\x00\x00\x00XXXX";
567 let err = validate_webp(data, "f.webp").unwrap_err();
568 assert!(err.contains("missing WEBP signature"), "{err}");
569 }
570
571 #[test]
574 fn webp_static_has_no_anim_chunk() {
575 let mut data = b"RIFF\x00\x00\x00\x00WEBP".to_vec();
576 data.extend_from_slice(b"VP8L");
578 data.extend_from_slice(&4u32.to_le_bytes());
579 data.extend_from_slice(&[0u8; 4]);
580 assert!(!webp_is_animated(&data));
581 }
582
583 #[test]
584 fn webp_animated_has_anim_chunk() {
585 let mut data = b"RIFF\x00\x00\x00\x00WEBP".to_vec();
586 data.extend_from_slice(b"VP8L");
588 data.extend_from_slice(&4u32.to_le_bytes());
589 data.extend_from_slice(&[0u8; 4]);
590 data.extend_from_slice(b"ANIM");
592 data.extend_from_slice(&6u32.to_le_bytes());
593 data.extend_from_slice(&[0u8; 6]);
594 assert!(webp_is_animated(&data));
595 }
596
597 #[test]
598 fn webp_animated_chunk_walker_does_not_overflow() {
599 let mut data = b"RIFF\x00\x00\x00\x00WEBP".to_vec();
601 data.extend_from_slice(b"VP8L");
602 data.extend_from_slice(&u32::MAX.to_le_bytes()); assert!(!webp_is_animated(&data));
605 }
606}