const PLACEHOLDER: &[u8] = include_bytes!("../assets/icon-512.png");
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AppIcon {
png: &'static [u8],
}
impl Default for AppIcon {
fn default() -> Self {
Self::default_icon()
}
}
impl AppIcon {
pub const fn default_icon() -> Self {
Self::png(PLACEHOLDER)
}
pub const fn png(png: &'static [u8]) -> Self {
Self { png }
}
pub const fn bytes(self) -> &'static [u8] {
self.png
}
#[allow(unused_variables)]
pub fn install(self, cx: &gpui::App) {
#[cfg(target_os = "macos")]
install_macos(self.png);
}
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
pub fn window_icon(self) -> Option<std::sync::Arc<image::RgbaImage>> {
let decoded =
image::load_from_memory_with_format(self.png, image::ImageFormat::Png).ok()?;
Some(std::sync::Arc::new(decoded.into_rgba8()))
}
}
#[cfg(target_os = "macos")]
const MACOS_BODY_FRACTION: f64 = 824.0 / 1024.0;
#[cfg(target_os = "macos")]
fn install_macos(png: &[u8]) {
use objc2::AnyThread;
use objc2_app_kit::{NSApplication, NSCompositingOperation, NSImage};
use objc2_foundation::{MainThreadMarker, NSData, NSPoint, NSRect, NSSize};
let Some(mtm) = MainThreadMarker::new() else {
return;
};
let data = NSData::with_bytes(png);
let Some(art) = NSImage::initWithData(NSImage::alloc(), &data) else {
return;
};
const CANVAS: f64 = 512.0;
let body = CANVAS * MACOS_BODY_FRACTION;
let inset = (CANVAS - body) / 2.0;
let canvas = NSImage::initWithSize(NSImage::alloc(), NSSize::new(CANVAS, CANVAS));
let whole = NSRect::new(NSPoint::new(0.0, 0.0), NSSize::new(0.0, 0.0));
let into = NSRect::new(NSPoint::new(inset, inset), NSSize::new(body, body));
#[allow(deprecated)]
{
canvas.lockFocus();
art.drawInRect_fromRect_operation_fraction(
into,
whole,
NSCompositingOperation::SourceOver,
1.0,
);
canvas.unlockFocus();
}
unsafe {
NSApplication::sharedApplication(mtm).setApplicationIconImage(Some(&canvas));
}
}
#[cfg(test)]
mod tests {
use super::{AppIcon, PLACEHOLDER};
#[test]
fn the_placeholder_is_a_png() {
assert_eq!(&PLACEHOLDER[..8], b"\x89PNG\r\n\x1a\n");
}
#[test]
fn an_icon_carries_the_bytes_it_was_given() {
const MINE: &[u8] = b"\x89PNG\r\n\x1a\nnot really";
assert_eq!(AppIcon::png(MINE).bytes(), MINE);
assert_eq!(AppIcon::default().bytes(), PLACEHOLDER);
assert_ne!(AppIcon::png(MINE), AppIcon::default());
}
}