Skip to content

armgit / WacOS

Public Imported from GitHub
0

A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.

Rust
5.6 KB
Raw Blame
//! thumbs.cpp: miniaturas e ícones em threads de fundo. Os pedidos mais recentes saem primeiro (o que acabou de
//! aparecer na tela tem prioridade).
use std::collections::VecDeque;
use std::sync::atomic::{AtomicIsize, AtomicU32, Ordering};
use std::sync::{Condvar, Mutex};

use comum::windows::core::*;
use comum::windows::Win32::Foundation::*;
use comum::windows::Win32::Graphics::Gdi::*;
use comum::windows::Win32::System::Com::*;
use comum::windows::Win32::UI::Shell::*;
use comum::windows::Win32::UI::WindowsAndMessaging::PostMessageW;
use comum::{pc, wz};

#[derive(Clone, Copy, PartialEq)]
pub enum Kind {
    Image,
    /// documento sem miniatura
    Document,
    /// atalho para pasta
    Folder,
}
pub struct Resultado {
    pub gen: u32,
    pub key: String,
    pub w: u32,
    pub h: u32,
    /// BGRA pré-multiplicado, de cima para baixo (só Image)
    pub bgra: Vec<u8>,
    pub kind: Kind,
}
struct Req {
    gen: u32,
    path: String,
    key: String,
    px: i32,
}
static Q: Mutex<VecDeque<Req>> = Mutex::new(VecDeque::new());
static CV: Condvar = Condvar::new();
static GEN: AtomicU32 = AtomicU32::new(0);
static NOTIFY: AtomicIsize = AtomicIsize::new(0);
static MSG: AtomicU32 = AtomicU32::new(0);

pub fn ext(path: &str) -> String {
    let name = path.rsplit('\\').next().unwrap_or(path);
    match name.rfind('.') {
        Some(i) => name[i + 1..].to_lowercase(),
        None => String::new(),
    }
}
/// o destino de um atalho .lnk (vazio se não der)
pub fn link_target(lnk: &str) -> String {
    unsafe {
        let Ok(sl) = CoCreateInstance::<_, IShellLinkW>(&ShellLink, None, CLSCTX_INPROC_SERVER) else { return String::new() };
        let Ok(pf) = sl.cast::<IPersistFile>() else { return String::new() };
        let l = wz(lnk);
        if pf.Load(pc(&l), STGM_READ).is_err() {
            return String::new();
        }
        let mut t = [0u16; 260];
        if sl.GetPath(&mut t, std::ptr::null_mut(), 0).is_err() {
            return String::new();
        }
        comum::from_w(&t)
    }
}
fn link_to_folder(lnk: &str) -> bool {
    let t = link_target(lnk);
    !t.is_empty() && std::path::Path::new(&t).is_dir()
}
/// Programas mostram o próprio ícone (como os apps no Mac); o resto só usa miniatura de verdade (foto, vídeo...).
/// Sem miniatura, quem desenha é o app: folha branca no estilo do Mac.
pub fn render(gen: u32, path: &str, key: &str, px: i32) -> Option<Resultado> {
    let e = ext(path);
    if e == "lnk" && link_to_folder(path) {
        return Some(Resultado { gen, key: key.into(), w: 0, h: 0, bgra: Vec::new(), kind: Kind::Folder });
    }
    let app = ["exe", "msi", "lnk", "url", "appref-ms", "scr", "com"].contains(&e.as_str());
    unsafe {
        let p = wz(path);
        let f: IShellItemImageFactory = SHCreateItemFromParsingName(pc(&p), None).ok()?;
        let hb = match f.GetImage(SIZE { cx: px, cy: px }, SIIGBF_RESIZETOFIT | if app { SIIGBF_ICONONLY } else { SIIGBF_THUMBNAILONLY }) {
            Ok(h) if !h.is_invalid() => h,
            _ => return Some(Resultado { gen, key: key.into(), w: 0, h: 0, bgra: Vec::new(), kind: Kind::Document }),
        };
        let mut bm = BITMAP::default();
        GetObjectW(hb, std::mem::size_of::<BITMAP>() as i32, Some(&mut bm as *mut _ as *mut _));
        let (w_, h_) = (bm.bmWidth as u32, bm.bmHeight.unsigned_abs());
        let mut bi = BITMAPINFO::default();
        bi.bmiHeader = BITMAPINFOHEADER { biSize: std::mem::size_of::<BITMAPINFOHEADER>() as u32, biWidth: w_ as i32, biHeight: -(h_ as i32), biPlanes: 1, biBitCount: 32, ..Default::default() };
        let mut px_ = vec![0u8; (w_ * h_ * 4) as usize];
        let dc = GetDC(None);
        GetDIBits(dc, hb, 0, h_, Some(px_.as_mut_ptr() as *mut _), &mut bi, DIB_RGB_COLORS);
        ReleaseDC(None, dc);
        let _ = DeleteObject(hb);
        // miniaturas de foto às vezes vêm com alfa zerado: nesse caso a imagem é opaca
        if !px_.iter().skip(3).step_by(4).any(|&a| a != 0) {
            px_.iter_mut().skip(3).step_by(4).for_each(|a| *a = 255);
        }
        Some(Resultado { gen, key: key.into(), w: w_, h: h_, bgra: px_, kind: Kind::Image })
    }
}
fn work() {
    unsafe {
        let _ = CoInitializeEx(None, COINIT_APARTMENTTHREADED);
    }
    loop {
        let r = {
            let mut q = Q.lock().unwrap();
            while q.is_empty() {
                q = CV.wait(q).unwrap();
            }
            q.pop_back().unwrap()
        };
        if r.gen != GEN.load(Ordering::Relaxed) {
            continue;
        }
        if let Some(res) = render(r.gen, &r.path, &r.key, r.px) {
            let raw = Box::into_raw(Box::new(res));
            unsafe {
                if PostMessageW(HWND(NOTIFY.load(Ordering::Relaxed) as *mut _), MSG.load(Ordering::Relaxed), WPARAM(0), LPARAM(raw as isize)).is_err() {
                    drop(Box::from_raw(raw));
                }
            }
        }
    }
}
/// resultados chegam como PostMessage(notify, msg, 0, Box<Resultado>)
pub fn start(notify: HWND, msg: u32) {
    NOTIFY.store(notify.0 as isize, Ordering::Relaxed);
    MSG.store(msg, Ordering::Relaxed);
    // 2 a 4 threads (metade dos núcleos): pastas de fotos e vídeos se enchem mais rápido
    let n = (std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4) / 2).clamp(2, 4);
    for _ in 0..n {
        std::thread::spawn(work);
    }
}
/// descarta pedidos de pastas anteriores
pub fn set_generation(gen: u32) {
    let mut q = Q.lock().unwrap();
    GEN.store(gen, Ordering::Relaxed);
    q.clear();
}
pub fn request(gen: u32, path: &str, key: &str, px: i32) {
    Q.lock().unwrap().push_back(Req { gen, path: path.into(), key: key.into(), px });
    CV.notify_one();
}