A new style desktop shell for Windows 11: menu bar, Dock, Finder, Spotlight, Control Center and Liquid Glass, in native C++.
Rust
//! barra-teste: prova de conceito do porte do WacOS para Rust.
//!
//! barra-teste mostra os ajustes lidos e a ajuda
//! barra-teste --foto saida.bmp desenha a barra fora da tela (WIC) e grava a imagem; não abre janela nenhuma
//! barra-teste --janela abre uma janela comum (não é barra do sistema, não reserva espaço na tela)
//! Opções: --largura 1512 --escala 2 --escuro | --claro --ajustes caminho\ajustes.txt --app Finder
//!
//! Só LÊ o %APPDATA%\Shell\ajustes.txt. Não fala com o WacOS Shell, não põe ganchos, não simula teclado nem mouse.
mod ajustes;
mod desenho;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::time::Instant;
use windows::core::{w, Result};
use windows::Win32::Foundation::*;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
use windows::Win32::Graphics::Gdi::ValidateRect;
use windows::Win32::Graphics::Imaging::*;
use windows::Win32::System::Com::*;
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::System::Registry::*;
use windows::Win32::UI::HiDpi::*;
use windows::Win32::UI::WindowsAndMessaging::*;
const MENUS: [&str; 6] = ["Arquivo", "Editar", "Visualizar", "Ir", "Janela", "Ajuda"];
struct Opcoes {
foto: Option<PathBuf>,
janela: bool,
largura: f32,
escala: f32,
escuro: Option<bool>,
ajustes: Option<PathBuf>,
app: String,
}
fn opcoes() -> Opcoes {
let mut o = Opcoes { foto: None, janela: false, largura: 1512.0, escala: 1.0, escuro: None, ajustes: None, app: "Finder".into() };
let mut a = std::env::args().skip(1);
while let Some(x) = a.next() {
match x.as_str() {
"--foto" => o.foto = a.next().map(PathBuf::from),
"--janela" => o.janela = true,
"--largura" => o.largura = a.next().and_then(|v| v.parse().ok()).unwrap_or(o.largura),
"--escala" => o.escala = a.next().and_then(|v| v.parse().ok()).unwrap_or(o.escala),
"--escuro" => o.escuro = Some(true),
"--claro" => o.escuro = Some(false),
"--ajustes" => o.ajustes = a.next().map(PathBuf::from),
"--app" => o.app = a.next().unwrap_or(o.app),
_ => eprintln!("opção desconhecida: {x}"),
}
}
o
}
/// Tema do Windows (o mesmo registro que o Shell olha): SystemUsesLightTheme = 0 -> escuro. Só leitura.
fn escuro_do_sistema() -> bool {
let mut v: u32 = 1;
let mut tam = std::mem::size_of::<u32>() as u32;
let r = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),
w!("SystemUsesLightTheme"),
RRF_RT_REG_DWORD,
None,
Some(&mut v as *mut u32 as *mut _),
Some(&mut tam),
)
};
r == ERROR_SUCCESS && v == 0
}
fn props_rt(escala: f32) -> D2D1_RENDER_TARGET_PROPERTIES {
D2D1_RENDER_TARGET_PROPERTIES {
r#type: D2D1_RENDER_TARGET_TYPE_DEFAULT,
pixelFormat: D2D1_PIXEL_FORMAT { format: DXGI_FORMAT_B8G8R8A8_UNORM, alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED },
dpiX: 96.0 * escala,
dpiY: 96.0 * escala,
usage: D2D1_RENDER_TARGET_USAGE_NONE,
minLevel: D2D1_FEATURE_LEVEL_DEFAULT,
}
}
/// BMP de 32 bits de cima para baixo (sem depender de codificador nenhum)
fn gravar_bmp(caminho: &PathBuf, w: u32, h: u32, bgra: &[u8]) -> std::io::Result<()> {
let tam_img = w * h * 4;
let mut f = Vec::with_capacity(54 + tam_img as usize);
f.extend_from_slice(b"BM");
f.extend_from_slice(&(54 + tam_img).to_le_bytes());
f.extend_from_slice(&0u32.to_le_bytes());
f.extend_from_slice(&54u32.to_le_bytes());
f.extend_from_slice(&40u32.to_le_bytes());
f.extend_from_slice(&(w as i32).to_le_bytes());
f.extend_from_slice(&(-(h as i32)).to_le_bytes()); // negativo = de cima para baixo
f.extend_from_slice(&1u16.to_le_bytes());
f.extend_from_slice(&32u16.to_le_bytes());
f.extend_from_slice(&0u32.to_le_bytes()); // BI_RGB
f.extend_from_slice(&tam_img.to_le_bytes());
f.extend_from_slice(&2835i32.to_le_bytes());
f.extend_from_slice(&2835i32.to_le_bytes());
f.extend_from_slice(&0u32.to_le_bytes());
f.extend_from_slice(&0u32.to_le_bytes());
f.extend_from_slice(bgra);
std::fs::write(caminho, f)
}
/// --foto: desenha num bitmap WIC (fora da tela) e grava. Nenhuma janela aparece.
fn foto(o: &Opcoes, rec: &desenho::Recursos, e: &desenho::Estilo, saida: &PathBuf) -> Result<()> {
unsafe {
CoInitializeEx(None, COINIT_MULTITHREADED).ok()?;
let wic: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER)?;
let altura = desenho::ALTURA_PT * 3.0; // a barra e um pedaço do "papel de parede" embaixo
let (pw, ph) = ((o.largura * o.escala).round() as u32, (altura * o.escala).round() as u32);
let bmp = wic.CreateBitmap(pw, ph, &GUID_WICPixelFormat32bppPBGRA, WICBitmapCacheOnLoad)?;
let rt = rec.d2d.CreateWicBitmapRenderTarget(&bmp, &props_rt(o.escala))?;
rt.SetTextAntialiasMode(D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE);
let t0 = Instant::now();
rt.BeginDraw();
desenho::papel_de_parede(&rt, o.largura, altura, e.escuro)?;
desenho::barra(&rt, rec, e, o.largura, &o.app, &MENUS)?;
rt.EndDraw(None, None)?;
println!("desenho: {:.2} ms", t0.elapsed().as_secs_f64() * 1000.0);
let mut px = vec![0u8; (pw * ph * 4) as usize];
let r = WICRect { X: 0, Y: 0, Width: pw as i32, Height: ph as i32 };
bmp.CopyPixels(&r, pw * 4, &mut px)?;
gravar_bmp(saida, pw, ph, &px).map_err(|err| windows::core::Error::new(E_FAIL, err.to_string()))?;
println!("gravado: {} ({pw}x{ph})", saida.display());
Ok(())
}
}
// ---- --janela: uma janela comum com a barra desenhada dentro
struct EstadoJanela {
rec: desenho::Recursos,
estilo: desenho::Estilo,
app: String,
rt: Option<ID2D1HwndRenderTarget>,
}
thread_local! {
static ESTADO: RefCell<Option<EstadoJanela>> = const { RefCell::new(None) };
}
unsafe fn pintar(hwnd: HWND, st: &mut EstadoJanela) -> Result<()> {
let mut rc = RECT::default();
GetClientRect(hwnd, &mut rc)?;
let tam = D2D_SIZE_U { width: (rc.right - rc.left) as u32, height: (rc.bottom - rc.top) as u32 };
if st.rt.is_none() {
let hp = D2D1_HWND_RENDER_TARGET_PROPERTIES { hwnd, pixelSize: tam, presentOptions: D2D1_PRESENT_OPTIONS_NONE };
let dpi = GetDpiForWindow(hwnd) as f32;
st.rt = Some(st.rec.d2d.CreateHwndRenderTarget(&props_rt(dpi / 96.0), &hp)?);
}
let rt = st.rt.as_ref().unwrap();
rt.Resize(&tam)?;
let mut dx = 96.0f32;
let mut dy = 96.0f32;
rt.GetDpi(&mut dx, &mut dy);
let (w, h) = (tam.width as f32 * 96.0 / dx, tam.height as f32 * 96.0 / dy);
rt.BeginDraw();
desenho::papel_de_parede(rt, w, h, st.estilo.escuro)?;
desenho::barra(rt, &st.rec, &st.estilo, w, &st.app, &MENUS)?;
if let Err(e) = rt.EndDraw(None, None) {
if e.code() == D2DERR_RECREATE_TARGET {
st.rt = None; // a placa de vídeo resetou: recria na próxima pintura
} else {
return Err(e);
}
}
Ok(())
}
extern "system" fn proc_janela(hwnd: HWND, msg: u32, wp: WPARAM, lp: LPARAM) -> LRESULT {
unsafe {
match msg {
WM_PAINT => {
ESTADO.with(|e| {
if let Some(st) = e.borrow_mut().as_mut() {
if let Err(err) = pintar(hwnd, st) {
eprintln!("pintura falhou: {err}");
}
}
});
let _ = ValidateRect(hwnd, None);
LRESULT(0)
}
WM_SIZE => {
let _ = InvalidateRect(hwnd, None, FALSE);
LRESULT(0)
}
WM_DPICHANGED => {
ESTADO.with(|e| {
if let Some(st) = e.borrow_mut().as_mut() {
st.rt = None;
}
});
let r = &*(lp.0 as *const RECT);
let _ = SetWindowPos(hwnd, None, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOACTIVATE);
LRESULT(0)
}
WM_DESTROY => {
PostQuitMessage(0);
LRESULT(0)
}
_ => DefWindowProcW(hwnd, msg, wp, lp),
}
}
}
use windows::Win32::Graphics::Gdi::InvalidateRect;
fn janela(o: &Opcoes, rec: desenho::Recursos, estilo: desenho::Estilo) -> Result<()> {
unsafe {
let inst = GetModuleHandleW(None)?;
let classe = w!("WacOSRustTeste");
let wc = WNDCLASSW {
hInstance: inst.into(),
lpszClassName: classe,
lpfnWndProc: Some(proc_janela),
hCursor: LoadCursorW(None, IDC_ARROW)?,
..Default::default()
};
if RegisterClassW(&wc) == 0 {
return Err(windows::core::Error::from_win32());
}
ESTADO.with(|e| *e.borrow_mut() = Some(EstadoJanela { rec, estilo, app: o.app.clone(), rt: None }));
let hwnd = CreateWindowExW(
WINDOW_EX_STYLE::default(),
classe,
w!("WacOS — barra de menus em Rust (teste)"),
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
1100,
200,
None,
None,
inst,
None,
)?;
let _ = hwnd;
let mut msg = MSG::default();
while GetMessageW(&mut msg, None, 0, 0).as_bool() {
let _ = TranslateMessage(&msg);
DispatchMessageW(&msg);
}
Ok(())
}
}
fn main() {
let t0 = Instant::now();
unsafe {
let _ = SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
}
let o = opcoes();
let caminho = o.ajustes.clone().or_else(ajustes::caminho_padrao);
let m: BTreeMap<String, String> = match &caminho {
Some(p) => match ajustes::ler(p) {
Ok(m) => {
println!("ajustes: {} ({} chaves)", p.display(), m.len());
m
}
Err(e) => {
println!("ajustes: {} não abriu ({e}); usando os padrões", p.display());
BTreeMap::new()
}
},
None => BTreeMap::new(),
};
for k in ["liquid_glass", "golden_gate", "leopard", "barra_fundo", "barra_embaixo"] {
println!(" {k} = {}", m.get(k).map(String::as_str).unwrap_or("(padrão)"));
}
let escuro = o.escuro.unwrap_or_else(escuro_do_sistema);
let estilo = desenho::Estilo::dos_ajustes(&m, escuro);
println!("estilo: {estilo:?}");
let rec = match desenho::Recursos::novo(&estilo) {
Ok(r) => r,
Err(e) => {
eprintln!("Direct2D/DirectWrite falhou: {e}");
std::process::exit(1);
}
};
println!("fonte: {}", rec.familia);
println!("início até aqui: {:.2} ms", t0.elapsed().as_secs_f64() * 1000.0);
let r = if let Some(saida) = o.foto.clone() {
foto(&o, &rec, &estilo, &saida)
} else if o.janela {
janela(&o, rec, estilo)
} else {
println!("\nuse --foto saida.bmp (sem janela) ou --janela");
Ok(())
};
if let Err(e) = r {
eprintln!("erro: {e}");
std::process::exit(1);
}
}