A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! pastacor.cpp: cor e símbolo nas pastas (macOS 26 Tahoe: "Personalizar Pasta"). Uma cor (a pasta do tema é
//! retingida: mantém a luz e a sombra do desenho e troca o matiz) e um emoji no meio. O Finder desenha na hora; para a
//! mesa, o Explorador e as janelas de abrir/salvar também mostrarem, é gerado um .ico em %APPDATA%\Shell\pastas e
//! gravado como ícone da pasta (desktop.ini). Escolhas em %APPDATA%\Shell\pastas-cor.txt (caminho TAB cor TAB emoji).
#![allow(dead_code)]
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use comum::windows::Win32::Foundation::{E_FAIL, GENERIC_READ};
use comum::windows::core::*;
use comum::windows::Win32::Graphics::Direct2D::Common::*;
use comum::windows::Win32::Graphics::Direct2D::*;
use comum::windows::Win32::Graphics::DirectWrite::*;
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::*;
pub const COUNT: usize = 9;
pub const COLORS: [(u8, u8, u8); COUNT] = [(255, 69, 58), (255, 159, 10), (255, 214, 10), (48, 209, 88), (100, 210, 255), (10, 132, 255), (191, 90, 242), (255, 55, 95), (142, 142, 147)];
pub const NAMES: [&str; COUNT] = ["Vermelho", "Laranja", "Amarelo", "Verde", "Menta", "Azul", "Roxo", "Rosa", "Cinza"];
#[derive(Clone, Default)]
pub struct Info {
pub color: i32,
pub emoji: String,
}
static MAP: Global<Option<BTreeMap<String, Info>>> = Global::new(None);
static BMPS: Global<Option<(isize, HashMap<String, Option<ID2D1Bitmap>>)>> = Global::new(None);
fn data_dir() -> std::path::PathBuf {
std::path::PathBuf::from(std::env::var("APPDATA").unwrap_or_default()).join("Shell")
}
fn map() -> &'static mut BTreeMap<String, Info> {
MAP.get().get_or_insert_with(|| {
let mut m = BTreeMap::new();
for s in app2d::read_lines(&data_dir().join("pastas-cor.txt")) {
let p: Vec<&str> = s.splitn(3, '\t').collect();
if p.len() < 2 {
continue;
}
m.insert(p[0].to_lowercase(), Info { color: p[1].trim().parse().unwrap_or(-1), emoji: p.get(2).unwrap_or(&"").to_string() });
}
m
})
}
fn save_map() {
let _ = std::fs::create_dir_all(data_dir());
let l: Vec<String> = map().iter().map(|(k, v)| format!("{k}\t{}\t{}", v.color, v.emoji)).collect();
app2d::write_lines(&data_dir().join("pastas-cor.txt"), &l);
}
fn pack_dir(tahoe: bool) -> std::path::PathBuf {
install_dir().join(if tahoe { "icones\\tahoe" } else { "icones\\sequoia" })
}
fn load_png(file: &std::path::Path) -> Option<(u32, u32, Vec<u8>)> {
unsafe {
let f: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).ok()?;
let p = wz(&file.to_string_lossy());
let dec = f.CreateDecoderFromFilename(pc(&p), None, GENERIC_READ, WICDecodeMetadataCacheOnDemand).ok()?;
let fr = dec.GetFrame(0).ok()?;
let cv = f.CreateFormatConverter().ok()?;
cv.Initialize(&fr, &GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).ok()?;
let (mut w_, mut h) = (0, 0);
cv.GetSize(&mut w_, &mut h).ok()?;
let mut px = vec![0u8; (w_ * h * 4) as usize];
cv.CopyPixels(std::ptr::null(), w_ * 4, &mut px).ok()?;
Some((w_, h, px))
}
}
fn to_hsl(r: f32, g: f32, b: f32) -> (f32, f32, f32) {
let (mx, mn) = (r.max(g).max(b), r.min(g).min(b));
let l = (mx + mn) / 2.0;
if mx == mn {
return (0.0, 0.0, l);
}
let d = mx - mn;
let s = if l > 0.5 { d / (2.0 - mx - mn) } else { d / (mx + mn) };
let h = if mx == r {
(g - b) / d + if g < b { 6.0 } else { 0.0 }
} else if mx == g {
(b - r) / d + 2.0
} else {
(r - g) / d + 4.0
};
(h / 6.0, s, l)
}
fn hue(p: f32, q: f32, mut t: f32) -> f32 {
if t < 0.0 {
t += 1.0;
}
if t > 1.0 {
t -= 1.0;
}
if t < 1.0 / 6.0 {
p + (q - p) * 6.0 * t
} else if t < 0.5 {
q
} else if t < 2.0 / 3.0 {
p + (q - p) * (2.0 / 3.0 - t) * 6.0
} else {
p
}
}
/// troca o matiz e a saturação de cada pixel pelos da cor, mantendo a claridade (luz, sombra e dobra da pasta)
fn tint(px: &mut [u8], c: (u8, u8, u8)) {
let (th, ts, tl) = to_hsl(c.0 as f32 / 255.0, c.1 as f32 / 255.0, c.2 as f32 / 255.0);
let gray = ts < 0.05;
for p in px.chunks_exact_mut(4) {
let a = p[3] as f32 / 255.0;
if a <= 0.0 {
continue;
}
let (b, g, r) = (p[0] as f32 / 255.0 / a, p[1] as f32 / 255.0 / a, p[2] as f32 / 255.0 / a);
let (_, s, l) = to_hsl(r, g, b);
if s < 0.12 {
continue; // partes cinzas/brancas do desenho (papel, brilho) ficam
}
let s2 = if gray { 0.04 } else { (ts * (0.6 + s * 0.5)).min(1.0) };
let l2 = (l + (tl - 0.55) * 0.35).clamp(0.0, 1.0);
let q = if l2 < 0.5 { l2 * (1.0 + s2) } else { l2 + s2 - l2 * s2 };
let pp = 2.0 * l2 - q;
let (rr_, gg, bb) = (hue(pp, q, th + 1.0 / 3.0), hue(pp, q, th), hue(pp, q, th - 1.0 / 3.0));
p[0] = (bb.clamp(0.0, 1.0) * a * 255.0).round() as u8;
p[1] = (gg.clamp(0.0, 1.0) * a * 255.0).round() as u8;
p[2] = (rr_.clamp(0.0, 1.0) * a * 255.0).round() as u8;
}
}
fn tinted_pixels(tahoe: bool, color: i32) -> Option<(u32, u32, Vec<u8>)> {
let (w_, h, mut px) = load_png(&pack_dir(tahoe).join("folder default.png"))?;
if color >= 0 && (color as usize) < COUNT {
tint(&mut px, COLORS[color as usize]);
}
Some((w_, h, px))
}
fn emoji_format(size: f32) -> Option<IDWriteTextFormat> {
let f = cjk::format(app2d::dw(), "Segoe UI Emoji", DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, size, "")?;
unsafe {
let _ = f.SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
let _ = f.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
}
Some(f)
}
/// o emoji fica no meio do corpo da pasta (um pouco abaixo do centro: a aba fica em cima)
fn emoji_box(b: RectF) -> RectF {
let s = b.right - b.left;
let (cx, cy, e) = ((b.left + b.right) / 2.0, b.top + s * 0.56, s * 0.4);
rf(cx - e, cy - e / 2.0 - s * 0.05, cx + e, cy + e / 2.0 + s * 0.05)
}
/// .ico de 256 px (PNG dentro) com a pasta retingida e o emoji
fn write_ico(ico: &std::path::Path, tahoe: bool, inf: &Info) -> bool {
let Some((w_, h, px)) = tinted_pixels(tahoe, inf.color) else { return false };
let r = (|| -> Result<()> {
unsafe {
let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
let s = 256u32;
let bmp = wic.CreateBitmap(s, s, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
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 = app2d::d2d().CreateWicBitmapRenderTarget(&bmp, &props)?;
rt.BeginDraw();
rt.Clear(Some(&col(0.0, 0.0, 0.0, 0.0)));
if let Some(b) = bitmap_bgra(&rt, w_, h, &px) {
rt.DrawBitmap(&b, Some(&rf(0.0, 0.0, s as f32, s as f32)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
}
if !inf.emoji.is_empty() {
if let Some(tf) = emoji_format(s as f32 * 0.3) {
let br = rt.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None)?;
rt.DrawText(&w(&inf.emoji), &tf, &emoji_box(rf(0.0, 0.0, s as f32, s as f32)), &br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
}
}
rt.EndDraw(None, None)?;
// PNG num arquivo temporário e o .ico (uma imagem só, 256 x 256, PNG dentro) em volta dele
let tmp = ico.with_extension("png");
app2d::salvar_png(&bmp, &tmp.to_string_lossy())?;
let png = std::fs::read(&tmp).map_err(|_| Error::from(E_FAIL))?;
let _ = std::fs::remove_file(&tmp);
let mut head = vec![0u8, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 32, 0];
head.extend((png.len() as u32).to_le_bytes());
head.extend(22u32.to_le_bytes());
head.extend(png);
std::fs::write(ico, head).map_err(|_| Error::from(E_FAIL))?;
Ok(())
}
})();
r.is_ok()
}
fn apply_system_icon(folder: &str, inf: Option<&Info>, tahoe: bool) {
let mut fcs = SHFOLDERCUSTOMSETTINGS { dwSize: std::mem::size_of::<SHFOLDERCUSTOMSETTINGS>() as u32, dwMask: FCSM_ICONFILE, ..Default::default() };
let mut ico_w;
if let Some(inf) = inf {
let dir = data_dir().join("pastas");
let _ = std::fs::create_dir_all(&dir);
use std::hash::{Hash, Hasher};
let mut hs = std::collections::hash_map::DefaultHasher::new();
format!("{}|{}|{}", folder.to_lowercase(), inf.color, inf.emoji).hash(&mut hs);
let ico = dir.join(format!("{:08x}.ico", hs.finish() as u32));
if !write_ico(&ico, tahoe, inf) {
return;
}
ico_w = wz(&ico.to_string_lossy());
fcs.pszIconFile = PWSTR(ico_w.as_mut_ptr());
}
let f = wz(folder);
unsafe {
let _ = SHGetSetFolderCustomSettings(&mut fcs, pc(&f), FCS_FORCEWRITE);
SHChangeNotify(SHCNE_UPDATEITEM, SHCNF_PATHW, Some(f.as_ptr() as *const c_void), None);
}
}
pub fn get(path: &str) -> Option<Info> {
map().get(&path.to_lowercase()).cloned()
}
/// color -1 e emoji vazio = volta ao normal. tahoe: qual desenho de pasta usar no ícone do sistema
pub fn set(path: &str, color: i32, emoji: &str, tahoe: bool) {
let k = path.to_lowercase();
if color < 0 && emoji.is_empty() {
map().remove(&k);
save_map();
apply_system_icon(path, None, tahoe);
return;
}
let inf = Info { color, emoji: emoji.into() };
map().insert(k, inf.clone());
save_map();
apply_system_icon(path, Some(&inf), tahoe);
}
/// pasta comum retingida numa das cores (Aparência > Cor das pastas, macOS 27)
pub fn draw_color(rt: &ID2D1RenderTarget, color: i32, b: RectF, tahoe: bool) -> bool {
if color < 0 || color as usize >= COUNT {
return false;
}
draw_info(rt, &Info { color, emoji: String::new() }, b, tahoe)
}
/// desenha a pasta personalizada (false: a pasta não tem personalização)
pub fn draw(rt: &ID2D1RenderTarget, path: &str, b: RectF, tahoe: bool) -> bool {
match get(path) {
Some(inf) => draw_info(rt, &inf, b, tahoe),
None => false,
}
}
pub fn draw_info(rt: &ID2D1RenderTarget, inf: &Info, bx: RectF, tahoe: bool) -> bool {
let id = rt.as_raw() as isize;
let cache = BMPS.get();
if cache.as_ref().map(|c| c.0) != Some(id) {
*cache = Some((id, HashMap::new()));
}
let m = &mut cache.as_mut().unwrap().1;
let key = format!("{}|{}", if tahoe { "t" } else { "s" }, inf.color);
let b = m.entry(key).or_insert_with(|| tinted_pixels(tahoe, inf.color).and_then(|(w_, h, px)| unsafe { bitmap_bgra(rt, w_, h, &px) })).clone();
let Some(b) = b else { return false };
let s = bx.right - bx.left;
let g = if tahoe { s * 0.05 } else { 0.0 };
unsafe {
rt.DrawBitmap(&b, Some(&rf(bx.left - g, bx.top - g, bx.right + g, bx.bottom + g)), 1.0, D2D1_BITMAP_INTERPOLATION_MODE_LINEAR, None);
if !inf.emoji.is_empty() && s >= 14.0 {
if let Some(tf) = emoji_format((s * 0.3).round().max(6.0)) {
if let Ok(br) = rt.CreateSolidColorBrush(&col(1.0, 1.0, 1.0, 1.0), None) {
rt.DrawText(&w(&inf.emoji), &tf, &emoji_box(bx), &br, D2D1_DRAW_TEXT_OPTIONS_ENABLE_COLOR_FONT, DWRITE_MEASURING_MODE_NATURAL);
}
}
}
}
true
}
pub const EMOJIS: [&str; 20] = ["⭐", "❤️", "🎵", "🎧", "🎬", "📷", "💼", "📚", "📝", "💻", "🎮", "🏠", "✈️", "💡", "🔒", "🎨", "💰", "🧾", "📦", "⚙️"];