A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! Pequenas ajudas que o C++ tinha de graça: D2D1::RectF, D2D1::ColorF, GET_X_LPARAM, wstring <-> String...
use windows::core::PCWSTR;
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::System::LibraryLoader::GetModuleFileNameW;
pub type RectF = D2D_RECT_F;
pub type Cor = D2D1_COLOR_F;
pub type Ponto = D2D_POINT_2F;
#[inline]
pub const fn rf(l: f32, t: f32, r: f32, b: f32) -> RectF {
D2D_RECT_F { left: l, top: t, right: r, bottom: b }
}
#[inline]
pub const fn col(r: f32, g: f32, b: f32, a: f32) -> Cor {
D2D1_COLOR_F { r, g, b, a }
}
/// app2d::Rgb(r, g, b, a)
#[inline]
pub fn rgb(r: i32, g: i32, b: i32, a: f32) -> Cor {
col(r as f32 / 255.0, g as f32 / 255.0, b as f32 / 255.0, a)
}
#[inline]
pub const fn pt(x: f32, y: f32) -> Ponto {
D2D_POINT_2F { x, y }
}
#[inline]
pub fn in_rect(r: &RectF, x: f32, y: f32) -> bool {
x >= r.left && x < r.right && y >= r.top && y < r.bottom
}
#[inline]
pub fn rr(r: RectF, rx: f32, ry: f32) -> D2D1_ROUNDED_RECT {
D2D1_ROUNDED_RECT { rect: r, radiusX: rx, radiusY: ry }
}
#[inline]
pub fn ell(c: Ponto, rx: f32, ry: f32) -> D2D1_ELLIPSE {
D2D1_ELLIPSE { point: c, radiusX: rx, radiusY: ry }
}
pub fn inflate(r: RectF, d: f32) -> RectF {
rf(r.left - d, r.top - d, r.right + d, r.bottom + d)
}
/// texto para UTF-16 sem o zero do fim (DrawText, CreateTextLayout)
pub fn w(s: &str) -> Vec<u16> {
s.encode_utf16().collect()
}
/// texto para UTF-16 com o zero do fim (PCWSTR)
pub fn wz(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
/// UTF-16 (até o primeiro zero) para String
pub fn from_w(v: &[u16]) -> String {
let n = v.iter().position(|&c| c == 0).unwrap_or(v.len());
String::from_utf16_lossy(&v[..n])
}
pub unsafe fn from_pcwstr(p: PCWSTR) -> String {
if p.is_null() {
return String::new();
}
String::from_utf16_lossy(p.as_wide())
}
/// Um PCWSTR que vive enquanto o Vec viver: `let t = wz("x"); f(pc(&t))`
#[inline]
pub fn pc(v: &[u16]) -> PCWSTR {
PCWSTR(v.as_ptr())
}
#[inline]
pub fn get_x_lparam(l: LPARAM) -> i32 {
(l.0 & 0xFFFF) as i16 as i32
}
#[inline]
pub fn get_y_lparam(l: LPARAM) -> i32 {
((l.0 >> 16) & 0xFFFF) as i16 as i32
}
#[inline]
pub fn loword(v: usize) -> u32 {
(v & 0xFFFF) as u32
}
#[inline]
pub fn hiword(v: usize) -> u32 {
((v >> 16) & 0xFFFF) as u32
}
#[inline]
pub fn makelparam(lo: i32, hi: i32) -> LPARAM {
LPARAM(((lo as u16 as u32) | ((hi as u16 as u32) << 16)) as i32 as isize)
}
/// pasta do executável (bin\)
pub fn exe_dir() -> std::path::PathBuf {
let mut b = [0u16; 1024];
let n = unsafe { GetModuleFileNameW(None, &mut b) } as usize;
let p = std::path::PathBuf::from(String::from_utf16_lossy(&b[..n]));
p.parent().map(|p| p.to_path_buf()).unwrap_or_default()
}
/// pasta da instalação (a de cima do bin\): onde ficam icones\, docs\...
/// No teste em Rust (target\release) não existe icones\: cai na instalação do WacOS, se houver.
pub fn install_dir() -> std::path::PathBuf {
let d = exe_dir();
if let Some(p) = d.parent() {
if p.join("icones").exists() {
return p.to_path_buf();
}
}
if let Some(la) = std::env::var_os("LOCALAPPDATA") {
let p = std::path::PathBuf::from(la).join("Programs").join(crate::edicao::PASTA);
if p.join("icones").exists() {
return p;
}
}
d.parent().map(|p| p.to_path_buf()).unwrap_or(d)
}
/// %APPDATA%\Shell\<nome> (cria a pasta)
pub fn data_path(nome: &str) -> std::path::PathBuf {
let ad = std::env::var_os("APPDATA").unwrap_or_default();
let d = std::path::PathBuf::from(ad).join("Shell");
let _ = std::fs::create_dir_all(&d);
d.join(nome)
}
/// Pincel sólido temporário (o C++ fazia CreateSolidColorBrush + Release)
pub unsafe fn brush(rt: &ID2D1RenderTarget, c: Cor) -> Option<ID2D1SolidColorBrush> {
rt.CreateSolidColorBrush(&c, None).ok()
}
pub unsafe fn linear(rt: &ID2D1RenderTarget, stops: &[(f32, Cor)], a: Ponto, b: Ponto) -> Option<ID2D1LinearGradientBrush> {
let st: Vec<D2D1_GRADIENT_STOP> = stops.iter().map(|(p, c)| D2D1_GRADIENT_STOP { position: *p, color: *c }).collect();
let gs = rt.CreateGradientStopCollection(&st, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP).ok()?;
let props = D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES { startPoint: a, endPoint: b };
rt.CreateLinearGradientBrush(&props, None, &gs).ok()
}
pub unsafe fn radial(rt: &ID2D1RenderTarget, stops: &[(f32, Cor)], centro: Ponto, ofs: Ponto, rx: f32, ry: f32) -> Option<ID2D1RadialGradientBrush> {
let st: Vec<D2D1_GRADIENT_STOP> = stops.iter().map(|(p, c)| D2D1_GRADIENT_STOP { position: *p, color: *c }).collect();
let gs = rt.CreateGradientStopCollection(&st, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP).ok()?;
let props = D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES { center: centro, gradientOriginOffset: ofs, radiusX: rx, radiusY: ry };
rt.CreateRadialGradientBrush(&props, None, &gs).ok()
}
/// Matrix3x2 (D2D1::Matrix3x2F)
pub mod mat {
use windows::Foundation::Numerics::Matrix3x2;
pub fn ident() -> Matrix3x2 {
Matrix3x2 { M11: 1.0, M12: 0.0, M21: 0.0, M22: 1.0, M31: 0.0, M32: 0.0 }
}
pub fn trans(x: f32, y: f32) -> Matrix3x2 {
Matrix3x2 { M11: 1.0, M12: 0.0, M21: 0.0, M22: 1.0, M31: x, M32: y }
}
pub fn scale(sx: f32, sy: f32, cx: f32, cy: f32) -> Matrix3x2 {
Matrix3x2 { M11: sx, M12: 0.0, M21: 0.0, M22: sy, M31: cx - sx * cx, M32: cy - sy * cy }
}
pub fn rot(graus: f32, cx: f32, cy: f32) -> Matrix3x2 {
let a = graus.to_radians();
let (s, c) = a.sin_cos();
Matrix3x2 { M11: c, M12: s, M21: -s, M22: c, M31: cx - c * cx + s * cy, M32: cy - s * cx - c * cy }
}
/// a * b (primeiro a, depois b), como D2D1::Matrix3x2F
pub fn mul(a: &Matrix3x2, b: &Matrix3x2) -> Matrix3x2 {
Matrix3x2 {
M11: a.M11 * b.M11 + a.M12 * b.M21,
M12: a.M11 * b.M12 + a.M12 * b.M22,
M21: a.M21 * b.M11 + a.M22 * b.M21,
M22: a.M21 * b.M12 + a.M22 * b.M22,
M31: a.M31 * b.M11 + a.M32 * b.M21 + b.M31,
M32: a.M31 * b.M12 + a.M32 * b.M22 + b.M32,
}
}
}
/// RegisterWindowMessageW com cache por nome
pub fn reg_msg(nome: &str) -> u32 {
use std::collections::HashMap;
static CACHE: crate::Global<Option<HashMap<String, u32>>> = crate::Global::new(None);
let m = CACHE.get().get_or_insert_with(HashMap::new);
if let Some(v) = m.get(nome) {
return *v;
}
let t = wz(nome);
let v = unsafe { windows::Win32::UI::WindowsAndMessaging::RegisterWindowMessageW(pc(&t)) };
m.insert(nome.to_string(), v);
v
}
/// FindWindowW(classe, NULL)
pub fn find_window(classe: &str) -> Option<HWND> {
let t = wz(classe);
unsafe { windows::Win32::UI::WindowsAndMessaging::FindWindowW(pc(&t), PCWSTR::null()).ok().filter(|h| !h.0.is_null()) }
}
/// Valor do argumento `--nome valor` na linha de comando
pub fn arg_valor(nome: &str) -> Option<String> {
let a: Vec<String> = std::env::args().collect();
a.iter().position(|x| x == nome).and_then(|i| a.get(i + 1).cloned())
}
pub fn tem_arg(nome: &str) -> bool {
std::env::args().any(|x| x == nome)
}
/// ShellExecuteW(nullptr, "open", arquivo, params, nullptr, SW_SHOWNORMAL)
pub fn shell_open(arquivo: &str, params: Option<&str>) -> bool {
use windows::Win32::UI::Shell::ShellExecuteW;
use windows::Win32::UI::WindowsAndMessaging::SW_SHOWNORMAL;
let f = wz(arquivo);
let p = params.map(wz);
let op = wz("open");
let r = unsafe { ShellExecuteW(None, pc(&op), pc(&f), p.as_ref().map(|v| pc(v)).unwrap_or(PCWSTR::null()), PCWSTR::null(), SW_SHOWNORMAL) };
r.0 as isize > 32
}
/// Texto na área de transferência (CF_UNICODETEXT)
pub fn clipboard_set_text(owner: HWND, s: &str) -> bool {
use windows::Win32::System::DataExchange::*;
use windows::Win32::System::Memory::*;
let v = wz(s);
unsafe {
if OpenClipboard(owner).is_err() {
return false;
}
let _ = EmptyClipboard();
let mut ok = false;
if let Ok(g) = GlobalAlloc(GMEM_MOVEABLE, v.len() * 2) {
let p = GlobalLock(g) as *mut u16;
if !p.is_null() {
std::ptr::copy_nonoverlapping(v.as_ptr(), p, v.len());
let _ = GlobalUnlock(g);
ok = SetClipboardData(13 /* CF_UNICODETEXT */, HANDLE(g.0)).is_ok();
}
}
let _ = CloseClipboard();
ok
}
}
/// Texto da área de transferência
pub fn clipboard_get_text(owner: HWND) -> Option<String> {
use windows::Win32::System::DataExchange::*;
use windows::Win32::System::Memory::*;
unsafe {
OpenClipboard(owner).ok()?;
let r = (|| {
let h = GetClipboardData(13).ok()?;
let p = GlobalLock(HGLOBAL(h.0)) as *const u16;
if p.is_null() {
return None;
}
let mut n = 0;
while *p.add(n) != 0 {
n += 1;
}
let s = String::from_utf16_lossy(std::slice::from_raw_parts(p, n));
let _ = GlobalUnlock(HGLOBAL(h.0));
Some(s)
})();
let _ = CloseClipboard();
r
}
}
/// Miniatura do Shell (IShellItemImageFactory) em BGRA (alfa 255): a capa de um .mp3, a foto, o ícone
pub fn shell_thumbnail(path: &str, size: i32, flags: windows::Win32::UI::Shell::SIIGBF) -> Option<(u32, u32, Vec<u8>)> {
use windows::Win32::Foundation::SIZE;
use windows::Win32::Graphics::Gdi::*;
use windows::Win32::UI::Shell::*;
unsafe {
let p = wz(path);
let f: IShellItemImageFactory = SHCreateItemFromParsingName(pc(&p), None).ok()?;
let hb = f.GetImage(SIZE { cx: size, cy: size }, flags).ok()?;
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);
Some((w_, h_, px))
}
}
/// Bitmap do Direct2D a partir de BGRA pré-multiplicado
pub unsafe fn bitmap_bgra(rt: &ID2D1RenderTarget, w_: u32, h_: u32, px: &[u8]) -> Option<ID2D1Bitmap> {
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
let bp = D2D1_BITMAP_PROPERTIES { pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED }, dpiX: 0.0, dpiY: 0.0 };
rt.CreateBitmap(D2D_SIZE_U { width: w_, height: h_ }, Some(px.as_ptr() as *const _), w_ * 4, &bp).ok()
}
/// Uma propriedade de texto do Shell (PKEY_Title...) de um arquivo
pub fn prop_text(ps: &windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore, k: &windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY) -> String {
unsafe {
let Ok(v) = ps.GetValue(k) else { return String::new() };
match windows::Win32::System::Com::StructuredStorage::PropVariantToStringAlloc(&v) {
Ok(p) => {
let s = from_pcwstr(PCWSTR(p.0));
windows::Win32::System::Com::CoTaskMemFree(Some(p.0 as *const _));
s.split("; ").next().unwrap_or("").to_string()
}
Err(_) => String::new(),
}
}
}
pub fn prop_u64(ps: &windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore, k: &windows::Win32::UI::Shell::PropertiesSystem::PROPERTYKEY) -> u64 {
unsafe { ps.GetValue(k).ok().and_then(|v| windows::Win32::System::Com::StructuredStorage::PropVariantToUInt64(&v).ok()).unwrap_or(0) }
}
pub fn property_store(path: &str) -> Option<windows::Win32::UI::Shell::PropertiesSystem::IPropertyStore> {
use windows::Win32::UI::Shell::PropertiesSystem::*;
let p = wz(path);
unsafe { SHGetPropertyStoreFromParsingName(pc(&p), None, GPS_DEFAULT).ok() }
}
/// SetWindowLongPtrW que compila nos dois tamanhos (em 32 bits o Windows só tem o SetWindowLongW, de i32): a
/// WacOSWindow.dll sai também em 32 bits, para o rundll32 de 32 bits
pub unsafe fn set_wlp(h: HWND, i: windows::Win32::UI::WindowsAndMessaging::WINDOW_LONG_PTR_INDEX, v: isize) -> isize {
#[cfg(target_pointer_width = "64")]
return windows::Win32::UI::WindowsAndMessaging::SetWindowLongPtrW(h, i, v);
#[cfg(target_pointer_width = "32")]
return windows::Win32::UI::WindowsAndMessaging::SetWindowLongW(h, i, v as i32) as isize;
}
/// GetWindowLongPtrW nos dois tamanhos (ver `set_wlp`)
pub unsafe fn get_wlp(h: HWND, i: windows::Win32::UI::WindowsAndMessaging::WINDOW_LONG_PTR_INDEX) -> isize {
#[cfg(target_pointer_width = "64")]
return windows::Win32::UI::WindowsAndMessaging::GetWindowLongPtrW(h, i);
#[cfg(target_pointer_width = "32")]
return windows::Win32::UI::WindowsAndMessaging::GetWindowLongW(h, i) as isize;
}
/// GetClassLongPtrW nos dois tamanhos (ver `set_wlp`)
pub unsafe fn get_clp(h: HWND, i: windows::Win32::UI::WindowsAndMessaging::GET_CLASS_LONG_INDEX) -> usize {
#[cfg(target_pointer_width = "64")]
return windows::Win32::UI::WindowsAndMessaging::GetClassLongPtrW(h, i);
#[cfg(target_pointer_width = "32")]
return windows::Win32::UI::WindowsAndMessaging::GetClassLongW(h, i) as usize;
}
/// SetClassLongPtrW nos dois tamanhos (ver `set_wlp`)
pub unsafe fn set_clp(h: HWND, i: windows::Win32::UI::WindowsAndMessaging::GET_CLASS_LONG_INDEX, v: isize) -> usize {
#[cfg(target_pointer_width = "64")]
return windows::Win32::UI::WindowsAndMessaging::SetClassLongPtrW(h, i, v);
#[cfg(target_pointer_width = "32")]
return windows::Win32::UI::WindowsAndMessaging::SetClassLongW(h, i, v as i32) as usize;
}