A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! PR #358 (menubar.cpp): os ícones da bandeja na barra de menus. Ícones mínimos embutidos (SVG monocromáticos em
//! icones\menubar, um por app conhecido), ícone próprio escolhido pela pessoa (%APPDATA%\Shell\icones-menubar),
//! o estilo Original/Minimal por app, o filtro em tons de cinza dos originais e a ordem (Ctrl + arrastar).
use std::collections::HashMap;
use std::sync::atomic::{AtomicI32, Ordering};
use comum::windows::core::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use comum::windows::Win32::Graphics::Imaging::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::UI::Shell::*;
use comum::*;
use crate::tray::TrayIcon;
use crate::{log, menubar, shell, ui};
static REV: AtomicI32 = AtomicI32::new(0);
static CACHE: Global<Option<HashMap<(String, u32, bool, bool, i32), Vec<u8>>>> = Global::new(None);
fn sanitize(s: &str) -> String {
let r: String = s.to_lowercase().chars().map(|c| if (c as u32) < 32 || "\\/:*?\"<>|".contains(c) { '_' } else { c }).collect();
r.trim_end_matches([' ', '.']).trim_start_matches(' ').to_string()
}
/// a chave dos arquivos e dos ajustes de um ícone: o programa (ou, sem ele, o nome)
pub fn file_key(t: &TrayIcon) -> String {
let p = sanitize(&menubar::programa_do_icone(t.hwnd));
if p.is_empty() { sanitize(&menubar::tray_key(t)) } else { p }
}
fn builtin_dir() -> String {
let d = shell::dir();
d.rfind('\\').map(|i| format!("{}\\icones\\menubar\\", &d[..i])).unwrap_or_default()
}
fn custom_dir() -> String {
std::env::var("APPDATA").map(|a| format!("{a}\\Shell\\icones-menubar\\")).unwrap_or_default()
}
/// o ícone embutido do app (pelo programa e pela dica)
fn builtin_slug(t: &TrayIcon) -> &'static str {
let exe = menubar::programa_do_icone(t.hwnd).to_lowercase();
let tip = menubar::tray_key(t).to_lowercase();
let full = t.tip.to_lowercase();
let has = |k: &str| exe.contains(k) || tip.contains(k) || full.contains(k);
let eq = |k: &str| exe == k || tip == k;
let starts = |p: &str| tip.starts_with(p);
let tabela: [(bool, &'static str); 46] = [
(has("clash-verge") || has("clash verge") || has("verge-mihomo"), "clash-verge"),
(has("clash") || has("mihomo") || has("flclash"), "clash"),
(has("claude"), "claude"),
(has("codex") || has("chatgpt") || has("openai"), "codex"),
(has("antigravity"), "antigravity"),
(has("figma"), "figma"),
(has("notion"), "notion"),
(has("eagle"), "eagle"),
(has("wechat") || has("weixin") || has("微信"), "wechat"),
(has("youdaodict") || has("youdao") || has("有道"), "youdaodict"),
(has("onedrive"), "onedrive"),
(has("googledrive") || has("google drive"), "googledrive"),
(has("icloud"), "icloud"),
(has("dropbox"), "dropbox"),
(has("discord"), "discord"),
(has("telegram"), "telegram"),
(has("whatsapp"), "whatsapp"),
(has("qqmusic") || has("qq music") || has("qq音乐"), "qqmusic"),
(eq("qq") || eq("tim") || has("tencent qq") || starts("qq ") || starts("qq("), "qq"),
(eq("line") || starts("line "), "line"),
(has("outlook") || eq("olk"), "outlook"),
(has("docker"), "docker"),
(has("nvidia") || has("nvcontainer") || has("nvtray") || has("geforce"), "nvidia"),
(has("cloudflare") || has("warp-cli"), "cloudflare"),
(has("sunshine"), "sunshine"),
(has("streamdeck") || has("stream deck"), "streamdeck"),
(has("logioptions") || has("logi options") || has("logitech"), "logioptions"),
(has("flexdesigner") || has("flex designer"), "flexdesigner"),
(has("grammarly"), "grammarly"),
(has("spotify"), "spotify"),
(has("cloudmusic") || has("netease") || has("网易云"), "neteasemusic"),
(has("steam"), "steam"),
(has("epicgames") || has("epic games"), "epicgames"),
(has("battle.net") || has("battlenet"), "battlenet"),
(has("ubisoft") || eq("upc"), "ubisoft"),
(has("powertoys awake") || (has("awake") && (exe.contains("powertoys") || full.contains("powertoys"))), "powertoys-awake"),
(has("powertoys"), "powertoys"),
(has("asus"), "asus"),
(has("bluetooth"), "bluetooth"),
(has("phone link") || has("yourphone") || has("phoneexperiencehost"), "iphone"),
(has("xunlei") || has("thunder") || has("迅雷"), "xunlei"),
(has("baidunetdisk") || has("baidu netdisk") || has("百度网盘"), "baidunetdisk"),
(has("aliyundrive") || has("aliyun drive") || has("adrive") || has("阿里云盘"), "aliyundrive"),
(has("quarkclouddrive") || has("quark drive") || has("quark") || has("夸克网盘"), "quarkdrive"),
(has("uu_agent") || has("uubooster") || has("uu booster") || has("uu加速器"), "uu"),
(has("vortex"), "vortex"),
];
tabela.iter().find(|(ok, _)| *ok).map(|x| x.1).unwrap_or("")
}
fn builtin_svg(t: &TrayIcon) -> String {
let slug = builtin_slug(t);
if slug.is_empty() {
return String::new();
}
let f = format!("{}{slug}.svg", builtin_dir());
if std::path::Path::new(&f).exists() { f } else { String::new() }
}
fn custom_path(key: &str) -> String {
let d = custom_dir();
if key.is_empty() || d.is_empty() {
return String::new();
}
for ext in ["svg", "png"] {
let f = format!("{d}{key}.{ext}");
if std::path::Path::new(&f).exists() {
return f;
}
}
String::new()
}
fn delete_custom(key: &str) -> bool {
let d = custom_dir();
if key.is_empty() || d.is_empty() {
return false;
}
let a = std::fs::remove_file(format!("{d}{key}.svg")).is_ok();
let b = std::fs::remove_file(format!("{d}{key}.png")).is_ok();
a || b
}
fn modes() -> Vec<(String, String)> {
shell::setting("barra_icone_modos", "")
.split('|')
.filter_map(|t| t.split_once('=').filter(|(k, v)| !k.is_empty() && !v.is_empty()).map(|(k, v)| (k.to_lowercase(), v.to_lowercase())))
.collect()
}
fn mode_of(key: &str) -> String {
let k = key.to_lowercase();
modes().into_iter().find(|(a, _)| *a == k).map(|x| x.1).unwrap_or_default()
}
fn set_mode(key: &str, mode: &str) {
if key.is_empty() {
return;
}
let k = key.to_lowercase();
let mut m: Vec<(String, String)> = modes().into_iter().filter(|(a, _)| *a != k).collect();
if !mode.is_empty() {
m.push((k, mode.to_lowercase()));
}
m.sort();
shell::set_setting("barra_icone_modos", &m.iter().map(|(a, b)| format!("{a}={b}")).collect::<Vec<_>>().join("|"));
}
fn style_minimal() -> bool {
shell::setting("barra_icone_estilo", "minimal") == "minimal"
}
fn original_gray() -> bool {
shell::setting("barra_icone_cinza", "1") != "0"
}
#[derive(PartialEq, Clone, Copy)]
enum Visual {
Original,
Stylized,
Custom,
}
fn effective(t: &TrayIcon) -> (Visual, String) {
let key = file_key(t);
let c = custom_path(&key);
if !c.is_empty() {
return (Visual::Custom, c);
}
let b = builtin_svg(t);
if !b.is_empty() {
let ov = mode_of(&key);
if if ov.is_empty() { style_minimal() } else { ov == "minimal" } {
return (Visual::Stylized, b);
}
}
(Visual::Original, String::new())
}
/// reduz a imagem quadrada para px × px, ocupando `fill` do quadrado (média por área)
fn resample_square(src: &[u8], sw: u32, sh: u32, px: u32, fill: f32) -> Vec<u8> {
let mut out = vec![0u8; (px * px * 4) as usize];
if sw == 0 || sh == 0 || px == 0 {
return out;
}
// PR #459 (Enesuygurs): tamanho e margem em pixels inteiros. Com 17 × 0,94 = 15,98 a margem era 0,51 px e toda
// borda caía no meio de um pixel
let target = (px as f32 * fill).round().max(1.0);
let o = ((px as f32 - target) * 0.5).floor();
for y in 0..px {
let ny = (y as f32 + 0.5 - o) / target;
if !(0.0..1.0).contains(&ny) {
continue;
}
let sy0 = ((y as f32 - o) / target * sh as f32).max(0.0);
let sy1 = ((y as f32 + 1.0 - o) / target * sh as f32).min(sh as f32);
let iy0 = (sy0.floor() as i32).clamp(0, sh as i32 - 1);
let iy1 = (sy1.ceil() as i32 - 1).clamp(iy0, sh as i32 - 1);
for x in 0..px {
let nx = (x as f32 + 0.5 - o) / target;
if !(0.0..1.0).contains(&nx) {
continue;
}
let sx0 = ((x as f32 - o) / target * sw as f32).max(0.0);
let sx1 = ((x as f32 + 1.0 - o) / target * sw as f32).min(sw as f32);
let ix0 = (sx0.floor() as i32).clamp(0, sw as i32 - 1);
let ix1 = (sx1.ceil() as i32 - 1).clamp(ix0, sw as i32 - 1);
let (mut acc, mut ws) = ([0f32; 4], 0f32);
for yy in iy0..=iy1 {
let wy = sy1.min((yy + 1) as f32) - sy0.max(yy as f32);
if wy <= 0.0 {
continue;
}
for xx in ix0..=ix1 {
let wx = sx1.min((xx + 1) as f32) - sx0.max(xx as f32);
if wx <= 0.0 {
continue;
}
let w = wx * wy;
let i = ((yy as u32 * sw + xx as u32) * 4) as usize;
for c in 0..4 {
acc[c] += src[i + c] as f32 * w;
}
ws += w;
}
}
if ws > 0.0 {
let oi = ((y * px + x) * 4) as usize;
for c in 0..4 {
out[oi + c] = (acc[c] / ws).round().clamp(0.0, 255.0) as u8;
}
}
}
}
out
}
fn rasterize_svg(path: &str, px: u32) -> Option<Vec<u8>> {
let r = (px * 4).max(128);
unsafe {
let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
let f: ID2D1Factory1 = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, None).ok()?;
let bmp = wic.CreateBitmap(r, r, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad).ok()?;
let props = D2D1_RENDER_TARGET_PROPERTIES {
r#type: D2D1_RENDER_TARGET_TYPE_SOFTWARE,
pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
..Default::default()
};
let rt = f.CreateWicBitmapRenderTarget(&bmp, &props).ok()?;
let dc: ID2D1DeviceContext5 = rt.cast().ok()?;
let pw = wz(path);
let stream = SHCreateStreamOnFileEx(pc(&pw), (STGM_READ | STGM_SHARE_DENY_NONE).0, 0, false, None).ok()?;
let svg = dc.CreateSvgDocument(&stream, D2D_SIZE_F { width: r as f32, height: r as f32 }).ok()?;
if let Ok(root) = svg.GetRoot() {
// os embutidos têm viewBox; o desenho ocupa o quadrado inteiro
let len = D2D1_SVG_LENGTH { value: r as f32, units: D2D1_SVG_LENGTH_UNITS_NUMBER };
let _ = root.SetAttributeValue2(w!("width"), D2D1_SVG_ATTRIBUTE_POD_TYPE_LENGTH, &len as *const _ as *const _, std::mem::size_of::<D2D1_SVG_LENGTH>() as u32);
let _ = root.SetAttributeValue2(w!("height"), D2D1_SVG_ATTRIBUTE_POD_TYPE_LENGTH, &len as *const _ as *const _, std::mem::size_of::<D2D1_SVG_LENGTH>() as u32);
}
dc.BeginDraw();
dc.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
dc.DrawSvgDocument(&svg);
dc.EndDraw(None, None).ok()?;
let mut hi = vec![0u8; (r * r * 4) as usize];
bmp.CopyPixels(std::ptr::null(), r * 4, &mut hi).ok()?;
let mut img = ui::Img { w: r, h: r, px: hi };
ui::trim_to_square(&mut img);
Some(resample_square(&img.px, img.w, img.h, px, 0.94))
}
}
fn load_raster(path: &str, px: u32) -> Option<Vec<u8>> {
let img = ui::load_photo(path, 256).filter(|i| i.w > 0 && i.h > 0)?;
let s = img.w.max(img.h);
let mut sq = vec![0u8; (s * s * 4) as usize];
let (ox, oy) = ((s - img.w) / 2, (s - img.h) / 2);
for y in 0..img.h {
let d = (((y + oy) * s + ox) * 4) as usize;
let o = (y * img.w * 4) as usize;
sq[d..d + (img.w * 4) as usize].copy_from_slice(&img.px[o..o + (img.w * 4) as usize]);
}
Some(resample_square(&sq, s, s, px, 1.0))
}
fn is_mono(p: &[u8]) -> bool {
let (mut white, mut black, mut any) = (true, true, false);
for q in p.chunks_exact(4) {
if q[3] < 64 {
continue;
}
any = true;
for c in 0..3 {
white &= q[c] as f32 >= q[3] as f32 * 0.85;
black &= q[c] as f32 <= q[3] as f32 * 0.15;
}
}
any && (white || black)
}
fn tint_mono(p: &mut [u8], dark: bool, da: f32, la: f32) {
let ink = if dark { 255.0 } else { 0.0 };
let mul = if dark { da } else { la };
for q in p.chunks_exact_mut(4) {
let a = q[3] as f32 / 255.0 * mul;
let c = (ink * a).round() as u8;
q.copy_from_slice(&[c, c, c, (a * 255.0).round() as u8]);
}
}
/// como os ícones-modelo do Mac: uma cor só, a do texto da barra; o desenho de dentro sai pela transparência
pub fn gray_filter(mono: &mut [u8], dark: bool) {
let (mut lmin, mut lmax) = (1f32, 0f32);
for p in mono.chunks_exact(4) {
let a = p[3] as f32 / 255.0;
if a < 0.5 {
continue;
}
let l = ((0.2126 * p[2] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[0] as f32) / 255.0 / a).clamp(0.0, 1.0);
lmin = lmin.min(l);
lmax = lmax.max(l);
}
let detail = lmax - lmin > 0.25;
let ink = if dark { 255.0 } else { 0.0 };
for p in mono.chunks_exact_mut(4) {
let a = p[3] as f32 / 255.0;
if a <= 0.004 {
p.copy_from_slice(&[0, 0, 0, 0]);
continue;
}
let mut oa = a;
if detail {
let l = ((0.2126 * p[2] as f32 + 0.7152 * p[1] as f32 + 0.0722 * p[0] as f32) / 255.0 / a).clamp(0.0, 1.0);
let t = ((l - lmin) / (lmax - lmin)).clamp(0.0, 1.0);
oa = a * if dark { 0.30 + 0.70 * t } else { 1.0 - 0.70 * t };
}
oa *= if dark { 0.96 } else { 0.88 };
let c = (ink * oa).round() as u8;
p.copy_from_slice(&[c, c, c, (oa * 255.0).round() as u8]);
}
}
/// os pixels do ícone na barra (for_menu = false) ou na lista » (for_menu = true)
pub fn resolve(t: &TrayIcon, px: u32, dark: bool, for_menu: bool) -> Vec<u8> {
let (vis, path) = effective(t);
if vis != Visual::Original {
let k = (path.clone(), px, dark, for_menu, REV.load(Ordering::Relaxed));
let cache = CACHE.get().get_or_insert_with(HashMap::new);
if let Some(v) = cache.get(&k) {
return v.clone();
}
if cache.len() > 128 {
cache.clear();
}
let p = if path.to_lowercase().ends_with(".svg") { rasterize_svg(&path, px) } else { load_raster(&path, px) };
if let Some(mut p) = p.filter(|p| p.len() == (px * px * 4) as usize) {
if vis == Visual::Stylized || is_mono(&p) {
tint_mono(&mut p, dark, if for_menu { 1.0 } else { 0.96 }, if for_menu { 1.0 } else { 0.88 });
}
cache.insert(k, p.clone());
return p;
}
}
let mut p = menubar::icon_pixels(t.icon, px);
if for_menu {
if is_mono(&p) {
tint_mono(&mut p, dark, 1.0, 1.0);
}
} else if original_gray() {
gray_filter(&mut p, dark);
}
p
}
// ---- a ordem (Ctrl + arrastar): barra_icones_ordem = chave|chave|...
fn load_order() -> Vec<String> {
shell::setting("barra_icones_ordem", "").split('|').filter(|s| !s.is_empty()).map(String::from).collect()
}
pub fn save_order(order: &[String]) {
shell::set_setting("barra_icones_ordem", &order.iter().filter(|k| !k.is_empty()).cloned().collect::<Vec<_>>().join("|"));
}
/// os índices dos ícones visíveis na ordem escolhida (os que não estão na lista vêm depois, na ordem de chegada)
pub fn ordered_visible(icons: &[TrayIcon]) -> Vec<usize> {
let vis: Vec<usize> = (0..icons.len())
.filter(|&i| {
let t = &icons[i];
!t.hidden && !t.icon.0.is_null() && menubar::is_shown(t) && !crate::tray::is_privacy(t)
})
.collect();
let saved = load_order();
if saved.is_empty() {
return vis;
}
let mut used = vec![false; vis.len()];
let mut out = Vec::new();
for sk in &saved {
for (j, &i) in vis.iter().enumerate() {
if !used[j] && file_key(&icons[i]).eq_ignore_ascii_case(sk) {
out.push(i);
used[j] = true;
}
}
}
out.extend(vis.iter().enumerate().filter(|(j, _)| !used[*j]).map(|(_, &i)| i));
out
}
/// os itens do menu » de um ícone: usar o estilizado, alterar e restaurar (ids base + 3, + 4, + 5)
pub fn menu_flags(t: &TrayIcon) -> (bool, bool, bool) {
let key = file_key(t);
let has_builtin = !builtin_svg(t).is_empty();
let reset_ok = !custom_path(&key).is_empty() || !mode_of(&key).is_empty();
(has_builtin, effective(t).0 == Visual::Stylized, reset_ok)
}
pub fn toggle_stylized(t: &TrayIcon) {
let key = file_key(t);
if effective(t).0 == Visual::Stylized {
set_mode(&key, "original");
} else {
delete_custom(&key);
set_mode(&key, "minimal");
}
icons_changed();
}
pub fn restore(t: &TrayIcon) {
let key = file_key(t);
delete_custom(&key);
set_mode(&key, "");
icons_changed();
}
fn save_custom(key: &str, src: &str) -> bool {
let d = custom_dir();
if key.is_empty() || d.is_empty() {
return false;
}
let _ = std::fs::create_dir_all(&d);
let low = src.to_lowercase();
if low.ends_with(".svg") {
if rasterize_svg(src, 32).is_none() || std::fs::copy(src, format!("{d}{key}.svg")).is_err() {
return false;
}
let _ = std::fs::remove_file(format!("{d}{key}.png"));
return true;
}
let icon = [".ico", ".exe", ".dll", ".lnk"].iter().any(|e| low.ends_with(e));
let mut img = if icon { ui::shell_image(src, 256, true) } else { ui::load_photo(src, 256) };
if img.is_none() && !icon {
img = ui::shell_image(src, 256, true);
}
let Some(mut img) = img.filter(|i| i.w > 0 && i.h > 0 && i.px.len() >= (i.w * i.h * 4) as usize) else { return false };
if icon {
ui::trim_to_square(&mut img);
}
if img.w != img.h {
let s_ = img.w.max(img.h);
let mut sq = vec![0u8; (s_ * s_ * 4) as usize];
let (ox, oy) = ((s_ - img.w) / 2, (s_ - img.h) / 2);
for y in 0..img.h {
let dd = (((y + oy) * s_ + ox) * 4) as usize;
let o = (y * img.w * 4) as usize;
sq[dd..dd + (img.w * 4) as usize].copy_from_slice(&img.px[o..o + (img.w * 4) as usize]);
}
img = ui::Img { w: s_, h: s_, px: sq };
}
ui::downscale(&mut img, 256);
if !crate::apps::save_png(&format!("{d}{key}.png"), img.w, img.h, &img.px) {
return false;
}
let _ = std::fs::remove_file(format!("{d}{key}.svg"));
true
}
/// Alterar Ícone…: o Finder em modo escolher (com SVG), ou a janela de Abrir do Windows
pub fn choose(name: &str, key: &str) {
if shell::foto() {
return;
}
let (name, key) = (name.to_string(), key.to_string());
std::thread::spawn(move || {
let tipos = format!("{}|*.svg;*.png;*.ico;*.jpg;*.jpeg;*.webp;*.bmp;*.gif;*.tif;*.tiff;*.heic||{}|*.ico;*.exe;*.dll", tr("Imagens"), tr("Ícones e programas"));
if let Some(p) = crate::apps::pick_file(&name, &tipos) {
if save_custom(&key, &p) {
set_mode(&key, "");
log!("barra de menus: ícone próprio de {name} <- {p}");
crate::apps::avisar_icone_mudou();
}
}
});
}
/// ícones da bandeja / estilo mudaram
pub fn icons_changed() {
if let Some(c) = CACHE.get().as_mut() {
c.clear();
}
REV.fetch_add(1, Ordering::Relaxed);
menubar::render_all();
}
/// entra na assinatura do desenho da barra (muda = redesenha)
pub fn assinatura() -> String {
format!(
"{}|{}|{}|{}|{}",
shell::setting("barra_icone_estilo", "minimal"),
shell::setting("barra_icone_cinza", "1"),
shell::setting("barra_icone_modos", ""),
shell::setting("barra_icones_ordem", ""),
REV.load(Ordering::Relaxed)
)
}