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
9.9 KB
Raw Blame
//! A barra de menus do WacOS (src\shell\menubar.cpp, Render/DrawLogo/DrawCC) em Direct2D pelo crate `windows`.
//!
//! Só o desenho, sem a lógica do Shell (menus reais do app, bandeja, Wi-Fi...): o logo próprio de quatro
//! quadradinhos, o nome do app em negrito, os menus, a Central de Controle e o relógio. As medidas e cores vêm do
//! C++: altura 26 pt (BAR_PT_SEQUOIA), texto 13,5 pt médio/negrito, texto branco 96 % ou preto 90 % no Liquid Glass
//! sem fundo, e a barra translúcida clara do Leopard (248 -> 204, Lucida Sans Unicode 14).

use std::collections::BTreeMap;

use windows::core::{w, Result, PCWSTR};
use windows::Win32::Foundation::BOOL;
use windows::Win32::Graphics::Direct2D::Common::*;
use windows::Win32::Graphics::Direct2D::*;
use windows::Win32::Graphics::DirectWrite::*;

use crate::ajustes;

pub const ALTURA_PT: f32 = 26.0; // BAR_PT_SEQUOIA

/// O que a barra precisa saber dos ajustes (shell::Setting no C++)
#[derive(Debug, Clone)]
pub struct Estilo {
    pub escuro: bool,
    pub leopard: bool,
    pub liquid: bool,
    pub fundo: bool, // "Mostrar fundo da barra de menus" (barra_fundo)
}

impl Estilo {
    pub fn dos_ajustes(m: &BTreeMap<String, String>, escuro_sistema: bool) -> Self {
        let leopard = ajustes::valor(m, "leopard", "0") == "1";
        let liquid = ajustes::valor(m, "liquid_glass", "0") == "1";
        // BarBackground(): Leopard sempre tem fundo; Liquid Glass nunca; senão o ajuste barra_fundo
        let fundo = leopard || (!liquid && ajustes::valor(m, "barra_fundo", "1") != "0");
        Estilo { escuro: escuro_sistema && !leopard, leopard, liquid, fundo }
    }
}

pub struct Recursos {
    pub d2d: ID2D1Factory,
    pub dw: IDWriteFactory,
    tf: IDWriteTextFormat,
    tf_negrito: IDWriteTextFormat,
    pub familia: String,
}

fn ws(s: &str) -> Vec<u16> {
    s.encode_utf16().collect()
}
fn wsz(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}
fn cor(r: f32, g: f32, b: f32, a: f32) -> D2D1_COLOR_F {
    D2D1_COLOR_F { r, g, b, a }
}
fn ret(l: f32, t: f32, r: f32, b: f32) -> D2D_RECT_F {
    D2D_RECT_F { left: l, top: t, right: r, bottom: b }
}

unsafe fn tem_familia(dw: &IDWriteFactory, nome: &str) -> bool {
    let mut col: Option<IDWriteFontCollection> = None;
    if dw.GetSystemFontCollection(&mut col, BOOL(0)).is_err() {
        return false;
    }
    let Some(col) = col else { return false };
    let mut idx = 0u32;
    let mut existe = BOOL(0);
    let n = wsz(nome);
    col.FindFamilyName(PCWSTR(n.as_ptr()), &mut idx, &mut existe).is_ok() && existe.as_bool()
}

unsafe fn formato(dw: &IDWriteFactory, familia: &str, tam: f32, peso: DWRITE_FONT_WEIGHT) -> Result<IDWriteTextFormat> {
    let f = wsz(familia);
    let tf = dw.CreateTextFormat(
        PCWSTR(f.as_ptr()),
        None,
        peso,
        DWRITE_FONT_STYLE_NORMAL,
        DWRITE_FONT_STRETCH_NORMAL,
        tam,
        w!("pt-br"),
    )?;
    tf.SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER)?;
    tf.SetWordWrapping(DWRITE_WORD_WRAPPING_NO_WRAP)?;
    Ok(tf)
}

impl Recursos {
    pub fn novo(estilo: &Estilo) -> Result<Self> {
        unsafe {
            let d2d: ID2D1Factory = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, None)?;
            let dw: IDWriteFactory = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)?;
            // a mesma ordem do ui::Init do Shell
            let familia = if estilo.leopard {
                "Lucida Sans Unicode".to_string()
            } else {
                ["SF Pro Text", "Inter", "Segoe UI Variable Text", "Segoe UI"]
                    .into_iter()
                    .find(|f| tem_familia(&dw, f))
                    .unwrap_or("Segoe UI")
                    .to_string()
            };
            let (tam, normal) = if estilo.leopard { (14.0, DWRITE_FONT_WEIGHT_NORMAL) } else { (13.5, DWRITE_FONT_WEIGHT_MEDIUM) };
            let tf = formato(&dw, &familia, tam, normal)?;
            let tf_negrito = formato(&dw, &familia, tam, DWRITE_FONT_WEIGHT_BOLD)?;
            Ok(Recursos { d2d, dw, tf, tf_negrito, familia })
        }
    }

    unsafe fn largura(&self, tf: &IDWriteTextFormat, s: &str) -> f32 {
        let t = ws(s);
        let Ok(lay) = self.dw.CreateTextLayout(&t, tf, 10000.0, 100.0) else { return 0.0 };
        let mut m = DWRITE_TEXT_METRICS::default();
        if lay.GetMetrics(&mut m).is_ok() {
            m.widthIncludingTrailingWhitespace
        } else {
            0.0
        }
    }
}

/// logo próprio do WacOS (não é a marca da Apple): quatro quadradinhos arredondados (DrawLogo)
unsafe fn logo(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, cx: f32, cy: f32) {
    let (s, g) = (5.4f32, 1.6f32);
    for i in 0..4 {
        let x = cx - s - g / 2.0 + (i % 2) as f32 * (s + g);
        let y = cy - s - g / 2.0 + (i / 2) as f32 * (s + g);
        let rr = D2D1_ROUNDED_RECT { rect: ret(x, y, x + s, y + s), radiusX: 1.5, radiusY: 1.5 };
        rt.FillRoundedRectangle(&rr, br);
    }
}

/// Central de Controle: duas chavinhas (DrawCC)
unsafe fn central(rt: &ID2D1RenderTarget, br: &ID2D1SolidColorBrush, cx: f32, cy: f32) {
    for k in 0..2 {
        let y = cy - 3.6 + k as f32 * 7.2;
        let rr = D2D1_ROUNDED_RECT { rect: ret(cx - 7.5, y - 2.8, cx + 7.5, y + 2.8), radiusX: 2.8, radiusY: 2.8 };
        rt.DrawRoundedRectangle(&rr, br, 1.2, None);
        let kx = if k == 0 { cx - 4.7 } else { cx + 4.7 };
        let e = D2D1_ELLIPSE { point: D2D_POINT_2F { x: kx, y }, radiusX: 2.0, radiusY: 2.0 };
        rt.FillEllipse(&e, br);
    }
}

/// "ter. 24 de nov. 18:02", como o relógio da barra em pt-BR
pub fn texto_relogio() -> String {
    let t = unsafe { windows::Win32::System::SystemInformation::GetLocalTime() };
    const DIAS: [&str; 7] = ["dom.", "seg.", "ter.", "qua.", "qui.", "sex.", "sáb."];
    const MESES: [&str; 12] = ["jan.", "fev.", "mar.", "abr.", "mai.", "jun.", "jul.", "ago.", "set.", "out.", "nov.", "dez."];
    format!(
        "{} {} de {} {:02}:{:02}",
        DIAS[t.wDayOfWeek as usize % 7],
        t.wDay,
        MESES[(t.wMonth as usize + 11) % 12],
        t.wHour,
        t.wMinute
    )
}

unsafe fn texto(rt: &ID2D1RenderTarget, tf: &IDWriteTextFormat, s: &str, x: f32, h: f32, br: &ID2D1SolidColorBrush) {
    let t = ws(s);
    rt.DrawText(&t, tf, &ret(x, 0.0, x + 2000.0, h), br, D2D1_DRAW_TEXT_OPTIONS_NONE, DWRITE_MEASURING_MODE_NATURAL);
}

/// Um "papel de parede" falso atrás da barra (no Shell é o papel de parede de verdade, visto pelo vidro)
pub unsafe fn papel_de_parede(rt: &ID2D1RenderTarget, w: f32, h: f32, escuro: bool) -> Result<()> {
    let (a, b) = if escuro {
        (cor(0.10, 0.16, 0.36, 1.0), cor(0.45, 0.20, 0.40, 1.0))
    } else {
        (cor(0.55, 0.75, 0.95, 1.0), cor(0.95, 0.80, 0.70, 1.0))
    };
    let paradas = [D2D1_GRADIENT_STOP { position: 0.0, color: a }, D2D1_GRADIENT_STOP { position: 1.0, color: b }];
    let col = rt.CreateGradientStopCollection(&paradas, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP)?;
    let props = D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES {
        startPoint: D2D_POINT_2F { x: 0.0, y: 0.0 },
        endPoint: D2D_POINT_2F { x: w, y: h },
    };
    let br = rt.CreateLinearGradientBrush(&props, None, &col)?;
    rt.FillRectangle(&ret(0.0, 0.0, w, h), &br);
    Ok(())
}

/// Desenha a barra inteira em `rt` (já entre BeginDraw/EndDraw), em DIPs: largura `w`, altura ALTURA_PT.
pub unsafe fn barra(rt: &ID2D1RenderTarget, rec: &Recursos, e: &Estilo, w: f32, app: &str, menus: &[&str]) -> Result<()> {
    let h = ALTURA_PT;
    let escuro = e.escuro;
    // Menubar Image do macOS 26: branco 90-92 % no escuro, preto 85 % no claro; Liquid Glass sem fundo: 96 / 90 %
    let mut fg = if escuro { cor(1.0, 1.0, 1.0, if e.liquid { 0.90 } else { 0.92 }) } else { cor(0.0, 0.0, 0.0, 0.85) };
    if e.liquid && !e.fundo {
        fg = if escuro { cor(1.0, 1.0, 1.0, 0.96) } else { cor(0.0, 0.0, 0.0, 0.90) };
    }

    if e.leopard {
        // barra translúcida clara do 10.5: 248 no alto -> 204 embaixo, fio de luz em cima e linha escura embaixo
        let paradas = [
            D2D1_GRADIENT_STOP { position: 0.0, color: cor(248.0 / 255.0, 248.0 / 255.0, 248.0 / 255.0, 0.92) },
            D2D1_GRADIENT_STOP { position: 1.0, color: cor(204.0 / 255.0, 204.0 / 255.0, 204.0 / 255.0, 0.92) },
        ];
        let col = rt.CreateGradientStopCollection(&paradas, D2D1_GAMMA_2_2, D2D1_EXTEND_MODE_CLAMP)?;
        let props = D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES {
            startPoint: D2D_POINT_2F { x: 0.0, y: 0.0 },
            endPoint: D2D_POINT_2F { x: 0.0, y: h },
        };
        let g = rt.CreateLinearGradientBrush(&props, None, &col)?;
        rt.FillRectangle(&ret(0.0, 0.0, w, h), &g);
        let linha = rt.CreateSolidColorBrush(&cor(0.0, 0.0, 0.0, 0.55), None)?;
        rt.FillRectangle(&ret(0.0, h - 1.0, w, h), &linha);
        fg = cor(0.0, 0.0, 0.0, 1.0);
    } else {
        // tinta leve por cima do acrílico (o "veil" do Render); sem fundo (Tahoe) fica transparente
        let mut veu = if escuro { cor(0.06, 0.06, 0.07, 0.18) } else { cor(1.0, 1.0, 1.0, 0.26) };
        if e.liquid {
            veu.a *= 0.35;
        }
        if !e.fundo {
            veu.a = 0.0;
        }
        let br = rt.CreateSolidColorBrush(&veu, None)?;
        rt.FillRectangle(&ret(0.0, 0.0, w, h), &br);
    }

    let br = rt.CreateSolidColorBrush(&fg, None)?;
    let x0 = 10.0;
    logo(rt, &br, x0 + 12.0, h / 2.0);

    // nome do app em negrito e os menus, cada um com ~10 pt de cada lado (como o Mac)
    let mut x = x0 + 24.0 + 10.0;
    texto(rt, &rec.tf_negrito, app, x, h, &br);
    x += rec.largura(&rec.tf_negrito, app) + 20.0;
    for m in menus {
        texto(rt, &rec.tf, m, x, h, &br);
        x += rec.largura(&rec.tf, m) + 20.0;
    }

    // direita: relógio e Central de Controle
    let relogio = texto_relogio();
    let lr = rec.largura(&rec.tf, &relogio);
    let xr = w - 12.0 - lr;
    texto(rt, &rec.tf, &relogio, xr, h, &br);
    central(rt, &br, xr - 10.0 - 7.5 - 4.0, h / 2.0);
    Ok(())
}