#[cfg(target_os = "linux")]
use std::path::Path;
use std::sync::{LazyLock, OnceLock};
const ARTWORK_PNG: &[u8] = include_bytes!("../assets/mb-icon-256.png");
#[cfg(target_os = "linux")]
pub const LINUX_APP_ID: &str = "mahbot";
struct Artwork {
rgba: Vec<u8>,
width: u32,
height: u32,
}
fn artwork() -> &'static Artwork {
static ARTWORK: LazyLock<Artwork> = LazyLock::new(|| {
let decode = image::load_from_memory_with_format(ARTWORK_PNG, image::ImageFormat::Png)
.expect("the embedded product icon is a PNG");
let rgba = decode.into_rgba8();
Artwork {
width: rgba.width(),
height: rgba.height(),
rgba: rgba.into_raw(),
}
});
&ARTWORK
}
#[must_use]
pub fn window_icon() -> Option<iced::window::Icon> {
let artwork = artwork();
iced::window::icon::from_rgba(artwork.rgba.clone(), artwork.width, artwork.height)
.map_err(|e| not_placed("the window icon", &e.to_string()))
.ok()
}
#[must_use]
pub(crate) fn widget_image() -> iced::widget::image::Handle {
static HANDLE: OnceLock<iced::widget::image::Handle> = OnceLock::new();
HANDLE
.get_or_init(|| {
let artwork = artwork();
iced::widget::image::Handle::from_rgba(
artwork.width,
artwork.height,
artwork.rgba.clone(),
)
})
.clone()
}
pub fn install_desktop_integration() {
#[cfg(target_os = "macos")]
set_dock_icon();
#[cfg(target_os = "linux")]
install_launcher_entry();
}
#[cfg(target_os = "macos")]
const TRAY_STATUS_POINTS: u32 = 18;
#[cfg(target_os = "macos")]
const TRAY_MARK_SIDE: u32 = TRAY_STATUS_POINTS * 2;
#[cfg(target_os = "macos")]
fn tray_mark() -> Option<&'static [u8]> {
static MARK: LazyLock<Option<Vec<u8>>> = LazyLock::new(|| mark_pixels(TRAY_MARK_SIDE));
MARK.as_deref()
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
#[must_use]
pub(crate) fn tray_icon_image() -> Option<tray_icon::Icon> {
#[cfg(target_os = "macos")]
{
let pixels = downscaled(tray_mark()?, TRAY_MARK_SIDE, TRAY_STATUS_POINTS);
tray_icon::Icon::from_rgba(pixels, TRAY_STATUS_POINTS, TRAY_STATUS_POINTS).ok()
}
#[cfg(target_os = "windows")]
{
use windows_sys::Win32::UI::WindowsAndMessaging::{GetSystemMetrics, SM_CXSMICON};
let size = unsafe { GetSystemMetrics(SM_CXSMICON) };
let size = u32::try_from(size).unwrap_or(0);
tray_icon::Icon::from_resource(ICON_RESOURCE_ID, Some((size, size))).ok()
}
}
#[cfg(target_os = "macos")]
#[must_use]
pub(crate) fn tray_status_image() -> Option<objc2::rc::Retained<objc2_app_kit::NSImage>> {
let image = square_nsimage(tray_mark()?, TRAY_MARK_SIDE, f64::from(TRAY_STATUS_POINTS))?;
image.setTemplate(true);
Some(image)
}
#[cfg(target_os = "macos")]
fn downscaled(pixels: &[u8], from: u32, to: u32) -> Vec<u8> {
let image = image::RgbaImage::from_raw(from, from, pixels.to_vec())
.expect("a square RGBA image is as long as its side says");
image::imageops::resize(&image, to, to, image::imageops::FilterType::Triangle).into_raw()
}
#[cfg(target_os = "macos")]
fn mark_pixels(side: u32) -> Option<Vec<u8>> {
const CUTOFF: u8 = 8;
let artwork = artwork();
let tile = dominant_colour(artwork);
let mut pixels = image::RgbaImage::new(artwork.width, artwork.height);
let mut bounds: Option<(u32, u32, u32, u32)> = None;
let mut strongest = 0u8;
for (index, pixel) in artwork.rgba.as_chunks::<4>().0.iter().enumerate() {
let distance = (0..3)
.map(|channel| pixel[channel].abs_diff(tile[channel]))
.max()
.unwrap_or(0);
let opacity = if pixel[3] == 255 { distance } else { 0 };
strongest = strongest.max(opacity);
#[expect(clippy::cast_possible_truncation)]
let (x, y) = (index as u32 % artwork.width, index as u32 / artwork.width);
pixels.put_pixel(x, y, image::Rgba([0, 0, 0, opacity]));
if opacity > CUTOFF {
let (left, top, right, bottom) = bounds.unwrap_or((x, y, x, y));
bounds = Some((left.min(x), top.min(y), right.max(x), bottom.max(y)));
}
}
let (left, top, right, bottom) = bounds?;
let mut mark =
image::imageops::crop_imm(&pixels, left, top, right - left + 1, bottom - top + 1)
.to_image();
for pixel in mark.pixels_mut() {
let alpha = u16::from(pixel.0[3]) * 255 / u16::from(strongest);
pixel.0[3] = u8::try_from(alpha).unwrap_or(u8::MAX);
}
let inner = side.saturating_sub(2).max(1);
let scale = f64::from(inner) / f64::from(mark.width().max(mark.height()));
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let (width, height) = (
((f64::from(mark.width()) * scale).round() as u32).max(1),
((f64::from(mark.height()) * scale).round() as u32).max(1),
);
let scaled =
image::imageops::resize(&mark, width, height, image::imageops::FilterType::Lanczos3);
let mut square = image::RgbaImage::new(side, side);
image::imageops::overlay(
&mut square,
&scaled,
i64::from((side - width) / 2),
i64::from((side - height) / 2),
);
Some(square.into_raw())
}
#[cfg(target_os = "macos")]
fn dominant_colour(artwork: &Artwork) -> [u8; 3] {
const LEVELS: usize = 16;
let mut counts = vec![0u32; LEVELS * LEVELS * LEVELS];
for pixel in artwork
.rgba
.as_chunks::<4>()
.0
.iter()
.filter(|pixel| pixel[3] == 255)
{
let bucket = (usize::from(pixel[0] >> 4) << 8)
| (usize::from(pixel[1] >> 4) << 4)
| usize::from(pixel[2] >> 4);
counts[bucket] += 1;
}
let bucket = counts
.iter()
.enumerate()
.max_by_key(|(_, count)| **count)
.map_or(0, |(bucket, _)| bucket);
let middle = |shift: usize| {
#[expect(clippy::cast_possible_truncation)]
let level = ((bucket >> shift) & 0x0F) as u8;
(level << 4) | 0x08
};
[middle(8), middle(4), middle(0)]
}
fn not_placed(surface: &str, reason: &str) {
crate::boot::boot_diagnostic(format!("{surface} was not placed: {reason}"));
}
#[cfg(target_os = "macos")]
fn set_dock_icon() {
use objc2::MainThreadMarker;
use objc2_app_kit::NSApplication;
let Some(marker) = MainThreadMarker::new() else {
not_placed("the Dock icon", "it can only be set from the main thread");
return;
};
let artwork = artwork();
let Some(icon) = square_nsimage(&artwork.rgba, artwork.width, f64::from(artwork.width)) else {
not_placed("the Dock icon", "its bitmap could not be allocated");
return;
};
unsafe {
NSApplication::sharedApplication(marker).setApplicationIconImage(Some(&icon));
}
}
#[cfg(target_os = "macos")]
#[expect(clippy::cast_possible_wrap)]
fn square_nsimage(
pixels: &[u8],
side: u32,
points: f64,
) -> Option<objc2::rc::Retained<objc2_app_kit::NSImage>> {
use objc2::AllocAnyThread;
use objc2_app_kit::{NSBitmapImageRep, NSDeviceRGBColorSpace, NSImage};
use objc2_foundation::NSSize;
let side = side as isize;
let bitmap = unsafe {
NSBitmapImageRep::initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(
NSBitmapImageRep::alloc(),
std::ptr::null_mut(),
side,
side,
8,
4,
true,
false,
NSDeviceRGBColorSpace,
side * 4,
32,
)
};
let bitmap = bitmap?;
unsafe {
std::ptr::copy_nonoverlapping(pixels.as_ptr(), bitmap.bitmapData(), pixels.len());
}
bitmap.setSize(NSSize::new(points, points));
let icon = NSImage::initWithSize(NSImage::alloc(), NSSize::new(points, points));
icon.addRepresentation(&bitmap);
Some(icon)
}
#[cfg(target_os = "linux")]
fn install_launcher_entry() {
let Some(data_home) = directories::BaseDirs::new().map(|base| base.data_dir().to_path_buf())
else {
not_placed("the launcher entry", "this account has no data directory");
return;
};
let Ok(executable) = std::env::current_exe() else {
not_placed("the launcher entry", "the running file has no path");
return;
};
let entry = data_home
.join("applications")
.join(format!("{LINUX_APP_ID}.desktop"));
let content = launcher_entry_text(&executable);
if let Err(e) = write_if_changed(&entry, content.as_bytes()) {
not_placed(
&format!("the launcher entry at {}", entry.display()),
&e.to_string(),
);
}
for size in [256, 48] {
let Some(png) = scaled_png(artwork(), size) else {
continue;
};
let icon = data_home
.join("icons/hicolor")
.join(format!("{size}x{size}"))
.join("apps")
.join(format!("{LINUX_APP_ID}.png"));
if let Err(e) = write_if_changed(&icon, &png) {
not_placed(
&format!("the launcher's icon at {}", icon.display()),
&e.to_string(),
);
}
}
}
#[cfg(target_os = "linux")]
fn launcher_entry_text(executable: &Path) -> String {
format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=MahBot\n\
Comment={description}\n\
Exec={exec}\n\
Icon={LINUX_APP_ID}\n\
Terminal=false\n\
Categories=Development;\n\
StartupWMClass={LINUX_APP_ID}\n",
description = env!("CARGO_PKG_DESCRIPTION"),
exec = crate::util::desktop_entry::exec_argument(executable),
)
}
#[cfg(target_os = "linux")]
fn scaled_png(artwork: &Artwork, size: u32) -> Option<Vec<u8>> {
let source = image::RgbaImage::from_raw(artwork.width, artwork.height, artwork.rgba.clone())
.expect("the artwork's pixels match its own dimensions");
let scaled =
image::imageops::resize(&source, size, size, image::imageops::FilterType::Lanczos3);
let mut png = Vec::new();
let encoded = image::DynamicImage::ImageRgba8(scaled)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png);
match encoded {
Ok(()) => Some(png),
Err(e) => {
not_placed(
"the launcher's icon",
&format!("{size}x{size} could not be encoded: {e}"),
);
None
}
}
}
#[cfg(target_os = "linux")]
fn write_if_changed(path: &Path, content: &[u8]) -> std::io::Result<()> {
if std::fs::read(path).is_ok_and(|current| current == content) {
return Ok(());
}
let Some(parent) = path.parent() else {
return Err(std::io::Error::other("the target has no directory"));
};
std::fs::create_dir_all(parent)?;
let staged = path.with_extension("new");
std::fs::write(&staged, content)?;
if let Err(e) = std::fs::rename(&staged, path) {
let _ = std::fs::remove_file(&staged);
return Err(e);
}
Ok(())
}
#[cfg(target_os = "windows")]
const ICON_RESOURCE_ID: u16 = 1;
#[cfg(target_os = "windows")]
#[expect(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
pub(crate) fn apply_window_icons(raw_handle: u64) {
use windows_sys::Win32::System::LibraryLoader::GetModuleHandleW;
use windows_sys::Win32::UI::WindowsAndMessaging::{
GCLP_HICON, GCLP_HICONSM, GetSystemMetrics, ICON_BIG, ICON_SMALL, IMAGE_ICON, LR_SHARED,
LoadImageW, SM_CXICON, SM_CXSMICON, SM_CYICON, SM_CYSMICON, SendMessageW, SetClassLongPtrW,
WM_SETICON,
};
let window = raw_handle as isize;
unsafe {
let instance = GetModuleHandleW(std::ptr::null());
let resource = usize::from(ICON_RESOURCE_ID) as *const u16;
let big = LoadImageW(
instance,
resource,
IMAGE_ICON,
GetSystemMetrics(SM_CXICON),
GetSystemMetrics(SM_CYICON),
LR_SHARED,
);
let small = LoadImageW(
instance,
resource,
IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),
GetSystemMetrics(SM_CYSMICON),
LR_SHARED,
);
for (icon, kind, class_index, surface) in [
(big, ICON_BIG, GCLP_HICON, "the taskbar icon"),
(small, ICON_SMALL, GCLP_HICONSM, "the small icon"),
] {
if icon == 0 {
not_placed(surface, &std::io::Error::last_os_error().to_string());
continue;
}
SendMessageW(window, WM_SETICON, kind as usize, icon);
SetClassLongPtrW(window, class_index, icon);
}
}
}