A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
fix: show the real icon of LibreOffice and of PNG-only program icons
AzureAD\davidlamad8830d66e503
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3aaedaa..139ab10 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,12 @@ copia la sección de la versión que se publica a la release de GitHub.it in Settings → System, or leave Automatic to follow Windows. A languageMuelle does not know in the settings file now reads as Automatic instead ofmaking the file invalid.+- Apps that showed a blank page instead of their icon now show it, as on the+ taskbar: LibreOffice (its windows belong to `soffice.bin`; the dock now+ shows LibreOffice Calc, Writer… with their names and icons), and programs+ whose icon the Windows shell cannot draw although it is valid (one made+ only of PNG images, as some Electron tools write). Icons are read again+ once after updating.### Español@@ -35,6 +41,13 @@ copia la sección de la versión que se publica a la release de GitHub.Elígelo en Ajustes → Sistema, o deja Automático para seguir a Windows. Unidioma que Muelle no conoce en el archivo de ajustes ahora se lee comoAutomático en lugar de invalidar el archivo.+- Las apps que mostraban una página en blanco en lugar de su icono ahora lo+ muestran, como en la barra de tareas: LibreOffice (sus ventanas pertenecen+ a `soffice.bin`; el dock ahora muestra LibreOffice Calc, Writer… con sus+ nombres e iconos) y los programas cuyo icono el shell de Windows no sabe+ dibujar aunque sea válido (uno hecho solo de imágenes PNG, como escriben+ algunas herramientas de Electron). Los iconos se vuelven a leer una vez+ tras actualizar.## [0.1.12]diff --git a/crates/muelle-shell/src/icon_cache.rs b/crates/muelle-shell/src/icon_cache.rsindex 061b69e..c5d3b9e 100644--- a/crates/muelle-shell/src/icon_cache.rs+++ b/crates/muelle-shell/src/icon_cache.rs@@ -20,7 +20,9 @@ use crate::{names::display_name,};-const MAGIC: &[u8; 4] = b"WDI1";+/// Changed when icons are read differently, so entries from before are read+/// again (2: programs' icons come from their own resources).+const MAGIC: &[u8; 4] = b"WDI2";const HEADER_LEN: usize = 4 + 8 + 4 + 4 + 4;const SECONDS_PER_DAY: u64 = 86_400;diff --git a/crates/muelle-shell/src/icons.rs b/crates/muelle-shell/src/icons.rsindex 4483378..a93d653 100644--- a/crates/muelle-shell/src/icons.rs+++ b/crates/muelle-shell/src/icons.rs@@ -3,12 +3,18 @@ use std::mem::size_of;use thiserror::Error;use windows::{Win32::{- Foundation::SIZE,+ Foundation::{S_OK, SIZE},Graphics::Gdi::{BI_RGB, BITMAP, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, DeleteObject, GetDC,GetDIBits, GetObjectW, HBITMAP, ReleaseDC,},- UI::Shell::{IShellItemImageFactory, SHCreateItemFromParsingName, SIIGBF_ICONONLY},+ UI::{+ Shell::{+ IShellItemImageFactory, SHCreateItemFromParsingName, SHDefExtractIconW,+ SIIGBF_ICONONLY,+ },+ WindowsAndMessaging::{DestroyIcon, GetIconInfo, HICON, ICONINFO},+ },},core::HSTRING,};@@ -37,14 +43,35 @@ struct OwnedBitmap(HBITMAP);impl Drop for OwnedBitmap {fn drop(&mut self) {- // SAFETY: This HBITMAP is owned by us (returned by GetImage) and is not used afterward.+ // SAFETY: This HBITMAP is owned by us (returned by GetImage or+ // GetIconInfo) and is not used afterward.unsafe {let _ = DeleteObject(self.0.into());}}}+struct OwnedIcon(HICON);++impl Drop for OwnedIcon {+ fn drop(&mut self) {+ // SAFETY: This HICON is owned by us (extracted from a file) and is not used afterward.+ unsafe {+ let _ = DestroyIcon(self.0);+ }+ }+}+pub fn load_icon(parsing_name: &str, size: u32) -> Result<IconImage, IconError> {+ // A program's icon comes from its own resources, as on the taskbar. The+ // shell's image factory gives a blank page instead for some valid icons:+ // one whose small sizes are PNG images, as some Electron tools write.+ if crate::tracker::is_program(parsing_name)+ && let Some(icon) = program_icon(parsing_name, size)+ {+ return Ok(icon);+ }+let shell_error = |source| IconError::Shell {name: parsing_name.to_owned(),source,@@ -65,7 +92,83 @@ pub fn load_icon(parsing_name: &str, size: u32) -> Result<IconImage, IconError>read_pixels(&bitmap).ok_or_else(|| IconError::Pixels(parsing_name.to_owned()))}+/// The first icon in a program's resources at `size` pixels; `None` when the+/// program has none, and the shell gives Windows' generic program icon.+fn program_icon(path: &str, size: u32) -> Option<IconImage> {+ let mut icon = HICON::default();+ // SAFETY: The path lives for the call, which writes one icon handle we own.+ let result =+ unsafe { SHDefExtractIconW(&HSTRING::from(path), 0, 0, Some(&mut icon), None, size) };+ // S_FALSE: the file has no icon.+ if result != S_OK || icon.is_invalid() {+ return None;+ }+ let icon = OwnedIcon(icon);+ let mut info = ICONINFO::default();+ // SAFETY: `icon` is valid; GetIconInfo creates two bitmaps, owned below.+ unsafe { GetIconInfo(icon.0, &mut info) }.ok()?;+ let (color, mask) = (OwnedBitmap(info.hbmColor), OwnedBitmap(info.hbmMask));+ // A monochrome icon has no color bitmap: left to the shell.+ if color.0.is_invalid() {+ return None;+ }+ let (width, height, mut bgra) = read_bits(&color)?;+ if bgra.as_chunks::<4>().0.iter().any(|px| px[3] != 0) {+ premultiply(&mut bgra);+ } else {+ // An icon without alpha: its mask tells which pixels are transparent.+ let (_, _, mask) = read_bits(&mask)?;+ if mask.len() != bgra.len() {+ return None;+ }+ for (px, bit) in bgra+ .as_chunks_mut::<4>()+ .0+ .iter_mut()+ .zip(mask.as_chunks::<4>().0)+ {+ if bit[0] == 0 {+ px[3] = 255;+ } else {+ *px = [0; 4];+ }+ }+ }+ Some(IconImage {+ width,+ height,+ bgra,+ })+}++/// Icons keep straight alpha; the dock draws premultiplied pixels.+fn premultiply(bgra: &mut [u8]) {+ for px in bgra.as_chunks_mut::<4>().0 {+ let alpha = u16::from(px[3]);+ for channel in &mut px[..3] {+ *channel = ((u16::from(*channel) * alpha + 127) / 255) as u8;+ }+ }+}+fn read_pixels(bitmap: &OwnedBitmap) -> Option<IconImage> {+ let (width, height, mut bgra) = read_bits(bitmap)?;+ // Legacy icons without an alpha channel have an alpha value of 0 for every pixel.+ if bgra.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {+ bgra.as_chunks_mut::<4>()+ .0+ .iter_mut()+ .for_each(|px| px[3] = 255);+ }+ Some(IconImage {+ width,+ height,+ bgra,+ })+}++/// The bitmap's pixels as 32-bit BGRA, rows from top to bottom.+fn read_bits(bitmap: &OwnedBitmap) -> Option<(u32, u32, Vec<u8>)> {let mut desc = BITMAP::default();// SAFETY: `desc` has the size specified in its size field.let written = unsafe {@@ -109,20 +212,32 @@ fn read_pixels(bitmap: &OwnedBitmap) -> Option<IconImage> {ReleaseDC(None, dc);lines};- if lines == 0 {- return None;+ (lines != 0).then_some((width, height, bgra))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn premultiply_should_scale_colors_by_alpha() {+ let mut bgra = [200, 100, 50, 128, 10, 20, 30, 255, 90, 90, 90, 0];+ premultiply(&mut bgra);+ assert_eq!(bgra, [100, 50, 25, 128, 10, 20, 30, 255, 0, 0, 0, 0]);}- // Legacy icons without an alpha channel have an alpha value of 0 for every pixel.- if bgra.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {- bgra.as_chunks_mut::<4>()- .0- .iter_mut()- .for_each(|px| px[3] = 255);+ #[test]+ #[ignore = "Reads a real program's icon; run explicitly"]+ fn program_icon_should_read_an_exe_icon_with_alpha() {+ let notepad = format!(+ r"{}\System32\notepad.exe",+ std::env::var("WINDIR").unwrap_or_default()+ );+ let icon = program_icon(¬epad, 256);+ assert_eq!(+ icon.as_ref().map(|icon| (icon.width, icon.height)),+ Some((256, 256))+ );+ assert!(icon.is_some_and(|icon| icon.bgra.as_chunks::<4>().0.iter().any(|px| px[3] == 0)));}- Some(IconImage {- width,- height,- bgra,- })}diff --git a/crates/muelle-shell/src/pins.rs b/crates/muelle-shell/src/pins.rsindex 5cd3d7f..08e8c66 100644--- a/crates/muelle-shell/src/pins.rs+++ b/crates/muelle-shell/src/pins.rs@@ -25,7 +25,10 @@ use windows::{const TASKBAND: PCWSTR = w!(r"Software\Microsoft\Windows\CurrentVersion\Explorer\Taskband");-use crate::{tracker::normalize_id, watch::RegistryWatch};+use crate::{+ tracker::{is_program, normalize_id},+ watch::RegistryWatch,+};/// The apps pinned to the Windows taskbar, in the taskbar's order: desktop/// apps by the program their shortcut opens, Store apps (Media Player, Phone@@ -391,10 +394,6 @@ pub fn kept_shortcut_for(id: &str) -> Option<String> {.map(|link| link.to_string_lossy().into_owned())}-fn is_program(path: &str) -> bool {- path.len() > 4 && path[path.len() - 4..].eq_ignore_ascii_case(".exe")-}-/// The folder where Muelle keeps its own copy of shortcuts pinned from/// elsewhere (the desktop, Downloads), as the taskbar keeps `User Pinned`:/// the pin keeps working if the original is moved or deleted.diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rsindex 3735cf9..0a410d7 100644--- a/crates/muelle-shell/src/tracker.rs+++ b/crates/muelle-shell/src/tracker.rs@@ -449,7 +449,21 @@ fn app_id(hwnd: HWND) -> Option<String> {&mut len,).ok()- .map(|()| normalize_id(&String::from_utf16_lossy(&buffer[..len as usize])))+ .map(|()| {+ let image = String::from_utf16_lossy(&buffer[..len as usize]);+ // A program whose windows belong to a host that is no .exe+ // (LibreOffice's soffice.bin) has no icon or name of its own+ // there; its windows say which app they are (Calc, Writer),+ // and the taskbar shows that app.+ if is_program(&image) {+ normalize_id(&image)+ } else {+ window_aumid(hwnd).map_or_else(+ || normalize_id(&image),+ |aumid| format!("{APPS_FOLDER}{aumid}"),+ )+ }+ })};let _ = CloseHandle(process);id@@ -462,6 +476,15 @@ pub fn is_shortcut(id: &str) -> bool {id.len() > 4 && id[id.len() - 4..].eq_ignore_ascii_case(".lnk")}+/// `true` for the path of a program (`.exe`).+#[must_use]+pub fn is_program(path: &str) -> bool {+ path.len() > 4+ && path+ .get(path.len() - 4..)+ .is_some_and(|extension| extension.eq_ignore_ascii_case(".exe"))+}+/// The class of the window in front, to tell in the log what was there.pub fn foreground_class() -> String {// SAFETY: Reads the foreground window handle.@@ -522,6 +545,17 @@ mod tests {);}+ #[test]+ fn is_program_should_accept_only_exe_files() {+ assert!(is_program(r"C:\Program Files\App\App.EXE"));+ assert!(!is_program(+ r"C:\Program Files\LibreOffice\program\soffice.bin"+ ));+ assert!(!is_program(".exe"));+ // A name ending inside a multi-byte character is no program, never a panic.+ assert!(!is_program(r"C:\app\x€ab"));+ }+#[test]fn normalize_id_should_keep_packaged_app_ids_untouched() {let id = "shell:AppsFolder\\Microsoft.WindowsTerminal_8wekyb3d8bbwe!App";