#![allow(unsafe_code)]
use crate::IconData;
use objc2::rc::Retained;
use objc2_app_kit::{NSFontWeightRegular, NSImage, NSImageSymbolConfiguration, NSImageSymbolScale};
use objc2_core_foundation::{CGPoint, CGRect, CGSize};
use objc2_core_graphics::{
CGBitmapContextCreate, CGColorSpace, CGContext, CGImage, CGImageAlphaInfo,
};
use objc2_foundation::NSString;
use std::ffi::c_void;
use std::ptr;
const DEFAULT_ICON_SIZE: u32 = 24;
fn load_symbol(name: &str, point_size: f64) -> Option<Retained<NSImage>> {
let ns_name = NSString::from_str(name);
let image = NSImage::imageWithSystemSymbolName_accessibilityDescription(&ns_name, None)?;
let weight = unsafe { NSFontWeightRegular };
let config = NSImageSymbolConfiguration::configurationWithPointSize_weight_scale(
point_size,
weight,
NSImageSymbolScale::Medium,
);
image.imageWithSymbolConfiguration(&config)
}
fn extract_cgimage(image: &NSImage) -> Option<Retained<CGImage>> {
unsafe { image.CGImageForProposedRect_context_hints(ptr::null_mut(), None, None) }
}
fn rasterize(cg_image: &CGImage, width: u32, height: u32) -> Option<Vec<u8>> {
let buf_size = crate::icons::raster_bytes_in_bound(width, height)?;
let color_space = CGColorSpace::new_device_rgb()?;
let bytes_per_row = usize::try_from(width).ok()?.checked_mul(4)?;
let mut buffer = vec![0u8; buf_size];
let bitmap_info = CGImageAlphaInfo::PremultipliedLast.0;
let context = unsafe {
CGBitmapContextCreate(
buffer.as_mut_ptr() as *mut c_void,
width as usize,
height as usize,
8,
bytes_per_row,
Some(&color_space),
bitmap_info,
)
}?;
let rect = CGRect {
origin: CGPoint { x: 0.0, y: 0.0 },
size: CGSize {
width: width as f64,
height: height as f64,
},
};
CGContext::draw_image(Some(&context), rect, Some(cg_image));
Some(buffer)
}
#[must_use]
pub(crate) fn load_sf_icon_by_name(
name: &str,
size: Option<u32>,
fg_color: Option<[u8; 3]>,
) -> Option<IconData> {
let size = size.unwrap_or(DEFAULT_ICON_SIZE);
if !crate::icons::raster_size_in_bound(size) {
return None;
}
let image = load_symbol(name, f64::from(size))?;
let cg_image = extract_cgimage(&image)?;
let w = u32::try_from(CGImage::width(Some(&cg_image))).ok()?;
let h = u32::try_from(CGImage::height(Some(&cg_image))).ok()?;
let mut data = rasterize(&cg_image, w, h)?;
crate::color::unpremultiply_alpha(&mut data);
crate::color::tint_monochrome(&mut data, fg_color);
IconData::rgba(w, h, data)
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use crate::{IconRole, IconSet, icon_name};
fn load_role(role: IconRole) -> Option<IconData> {
load_sf_icon_by_name(icon_name(role, IconSet::SfSymbols)?, None, None)
}
#[test]
fn unpremultiply_correctness() {
let mut buf = [128u8, 0, 0, 128];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [255, 0, 0, 128]);
let mut buf = [100u8, 200, 50, 255];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [100, 200, 50, 255]);
let mut buf = [0u8, 0, 0, 0];
crate::color::unpremultiply_alpha(&mut buf);
assert_eq!(buf, [0, 0, 0, 0]);
}
#[cfg(target_os = "macos")]
#[test]
fn load_icon_returns_some() {
let result = load_role(IconRole::ActionCopy);
assert!(result.is_some(), "ActionCopy should resolve to an icon");
}
#[cfg(target_os = "macos")]
#[test]
fn unmapped_role_returns_none() {
let result = load_role(IconRole::FolderOpen);
assert!(
result.is_none(),
"FolderOpen should return None (no SF Symbol, no fallback)"
);
}
#[cfg(target_os = "macos")]
#[test]
fn rgba_dimensions_correct() {
if let Some(IconData::Rgba(rgba)) = load_role(IconRole::ActionCopy) {
assert_eq!(
(rgba.width() * rgba.height() * 4) as usize,
rgba.data().len(),
"RGBA buffer size must equal width * height * 4"
);
}
}
#[cfg(target_os = "macos")]
#[test]
fn load_sf_icon_by_name_returns_some() {
let result = load_sf_icon_by_name("doc.on.doc", None, None);
assert!(
result.is_some(),
"doc.on.doc should resolve to an SF Symbol"
);
}
#[cfg(target_os = "macos")]
#[test]
fn load_sf_icon_by_name_size_scales_the_raster() {
let small = load_sf_icon_by_name("doc.on.doc", Some(16), None);
let large = load_sf_icon_by_name("doc.on.doc", Some(64), None);
let (Some(IconData::Rgba(small)), Some(IconData::Rgba(large))) = (small, large) else {
panic!("doc.on.doc should load as RGBA at 16 and 64 points");
};
assert!(
large.height() > small.height(),
"64 pt ({}) should be taller than 16 pt ({})",
large.height(),
small.height()
);
}
#[cfg(target_os = "macos")]
#[test]
fn load_sf_icon_by_name_size_out_of_bound_returns_none() {
assert!(load_sf_icon_by_name("doc.on.doc", Some(0), None).is_none());
assert!(load_sf_icon_by_name("doc.on.doc", Some(u32::MAX), None).is_none());
}
#[cfg(target_os = "macos")]
#[test]
fn rasterize_over_the_decode_bound_returns_none() {
let image = load_symbol("doc.on.doc", f64::from(DEFAULT_ICON_SIZE)).unwrap();
let cg_image = extract_cgimage(&image).unwrap();
assert!(rasterize(&cg_image, 8192, 2049).is_none());
assert!(rasterize(&cg_image, 0, 16).is_none());
assert!(rasterize(&cg_image, 16, 16).is_some());
}
#[cfg(target_os = "macos")]
#[test]
fn load_sf_icon_by_name_nonexistent_returns_none() {
let result = load_sf_icon_by_name("zzz.nonexistent.symbol", None, None);
assert!(result.is_none(), "nonexistent symbol should return None");
}
}